1 /*-------------------------------------------------------------------------
3 * pl_exec.c - Executor for the PL/pgSQL
6 * Portions Copyright (c) 1996-2007, 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.186 2007/01/30 18:02:22 tgl Exp $
13 *-------------------------------------------------------------------------
21 #include "access/heapam.h"
22 #include "access/transam.h"
23 #include "catalog/pg_proc.h"
24 #include "catalog/pg_type.h"
25 #include "executor/spi_priv.h"
27 #include "optimizer/clauses.h"
28 #include "parser/parse_expr.h"
29 #include "parser/scansup.h"
30 #include "tcop/tcopprot.h"
31 #include "utils/array.h"
32 #include "utils/builtins.h"
33 #include "utils/lsyscache.h"
34 #include "utils/memutils.h"
35 #include "utils/typcache.h"
38 static const char *const raise_skip_msg = "RAISE";
41 * All plpgsql function executions within a single transaction share the same
42 * executor EState for evaluating "simple" expressions. Each function call
43 * creates its own "eval_econtext" ExprContext within this estate for
44 * per-evaluation workspace. eval_econtext is freed at normal function exit,
45 * and the EState is freed at transaction end (in case of error, we assume
46 * that the abort mechanisms clean it all up). In order to be sure
47 * ExprContext callbacks are handled properly, each subtransaction has to have
48 * its own such EState; hence we need a stack. We use a simple counter to
49 * distinguish different instantiations of the EState, so that we can tell
50 * whether we have a current copy of a prepared expression.
52 * This arrangement is a bit tedious to maintain, but it's worth the trouble
53 * so that we don't have to re-prepare simple expressions on each trip through
54 * a function. (We assume the case to optimize is many repetitions of a
55 * function within a transaction.)
57 typedef struct SimpleEstateStackEntry
59 EState *xact_eval_estate; /* EState for current xact level */
60 long int xact_estate_simple_id; /* ID for xact_eval_estate */
61 SubTransactionId xact_subxid; /* ID for current subxact */
62 struct SimpleEstateStackEntry *next; /* next stack entry up */
63 } SimpleEstateStackEntry;
65 static SimpleEstateStackEntry *simple_estate_stack = NULL;
66 static long int simple_estate_id_counter = 0;
68 /************************************************************
69 * Local function forward declarations
70 ************************************************************/
71 static void plpgsql_exec_error_callback(void *arg);
72 static PLpgSQL_datum *copy_plpgsql_datum(PLpgSQL_datum *datum);
74 static int exec_stmt_block(PLpgSQL_execstate *estate,
75 PLpgSQL_stmt_block *block);
76 static int exec_stmts(PLpgSQL_execstate *estate,
78 static int exec_stmt(PLpgSQL_execstate *estate,
80 static int exec_stmt_assign(PLpgSQL_execstate *estate,
81 PLpgSQL_stmt_assign *stmt);
82 static int exec_stmt_perform(PLpgSQL_execstate *estate,
83 PLpgSQL_stmt_perform *stmt);
84 static int exec_stmt_getdiag(PLpgSQL_execstate *estate,
85 PLpgSQL_stmt_getdiag *stmt);
86 static int exec_stmt_if(PLpgSQL_execstate *estate,
87 PLpgSQL_stmt_if *stmt);
88 static int exec_stmt_loop(PLpgSQL_execstate *estate,
89 PLpgSQL_stmt_loop *stmt);
90 static int exec_stmt_while(PLpgSQL_execstate *estate,
91 PLpgSQL_stmt_while *stmt);
92 static int exec_stmt_fori(PLpgSQL_execstate *estate,
93 PLpgSQL_stmt_fori *stmt);
94 static int exec_stmt_fors(PLpgSQL_execstate *estate,
95 PLpgSQL_stmt_fors *stmt);
96 static int exec_stmt_open(PLpgSQL_execstate *estate,
97 PLpgSQL_stmt_open *stmt);
98 static int exec_stmt_fetch(PLpgSQL_execstate *estate,
99 PLpgSQL_stmt_fetch *stmt);
100 static int exec_stmt_close(PLpgSQL_execstate *estate,
101 PLpgSQL_stmt_close *stmt);
102 static int exec_stmt_exit(PLpgSQL_execstate *estate,
103 PLpgSQL_stmt_exit *stmt);
104 static int exec_stmt_return(PLpgSQL_execstate *estate,
105 PLpgSQL_stmt_return *stmt);
106 static int exec_stmt_return_next(PLpgSQL_execstate *estate,
107 PLpgSQL_stmt_return_next *stmt);
108 static int exec_stmt_raise(PLpgSQL_execstate *estate,
109 PLpgSQL_stmt_raise *stmt);
110 static int exec_stmt_execsql(PLpgSQL_execstate *estate,
111 PLpgSQL_stmt_execsql *stmt);
112 static int exec_stmt_dynexecute(PLpgSQL_execstate *estate,
113 PLpgSQL_stmt_dynexecute *stmt);
114 static int exec_stmt_dynfors(PLpgSQL_execstate *estate,
115 PLpgSQL_stmt_dynfors *stmt);
117 static void plpgsql_estate_setup(PLpgSQL_execstate *estate,
118 PLpgSQL_function *func,
120 static void exec_eval_cleanup(PLpgSQL_execstate *estate);
122 static void exec_prepare_plan(PLpgSQL_execstate *estate,
124 static bool exec_simple_check_node(Node *node);
125 static void exec_simple_check_plan(PLpgSQL_expr *expr);
126 static Datum exec_eval_simple_expr(PLpgSQL_execstate *estate,
131 static void exec_assign_expr(PLpgSQL_execstate *estate,
132 PLpgSQL_datum *target,
134 static void exec_assign_value(PLpgSQL_execstate *estate,
135 PLpgSQL_datum *target,
136 Datum value, Oid valtype, bool *isNull);
137 static void exec_eval_datum(PLpgSQL_execstate *estate,
138 PLpgSQL_datum *datum,
143 static int exec_eval_integer(PLpgSQL_execstate *estate,
146 static bool exec_eval_boolean(PLpgSQL_execstate *estate,
149 static Datum exec_eval_expr(PLpgSQL_execstate *estate,
153 static int exec_run_select(PLpgSQL_execstate *estate,
154 PLpgSQL_expr *expr, long maxtuples, Portal *portalP);
155 static void exec_move_row(PLpgSQL_execstate *estate,
158 HeapTuple tup, TupleDesc tupdesc);
159 static HeapTuple make_tuple_from_row(PLpgSQL_execstate *estate,
162 static char *convert_value_to_string(Datum value, Oid valtype);
163 static Datum exec_cast_value(Datum value, Oid valtype,
169 static Datum exec_simple_cast_value(Datum value, Oid valtype,
170 Oid reqtype, int32 reqtypmod,
172 static void exec_init_tuple_store(PLpgSQL_execstate *estate);
173 static bool compatible_tupdesc(TupleDesc td1, TupleDesc td2);
174 static void exec_set_found(PLpgSQL_execstate *estate, bool state);
175 static void plpgsql_create_econtext(PLpgSQL_execstate *estate);
176 static void free_var(PLpgSQL_var *var);
180 * plpgsql_exec_function Called by the call handler for
181 * function execution.
185 plpgsql_exec_function(PLpgSQL_function *func, FunctionCallInfo fcinfo)
187 PLpgSQL_execstate estate;
188 ErrorContextCallback plerrcontext;
193 * Setup the execution state
195 plpgsql_estate_setup(&estate, func, (ReturnSetInfo *) fcinfo->resultinfo);
198 * Setup error traceback support for ereport()
200 plerrcontext.callback = plpgsql_exec_error_callback;
201 plerrcontext.arg = &estate;
202 plerrcontext.previous = error_context_stack;
203 error_context_stack = &plerrcontext;
206 * Make local execution copies of all the datums
208 estate.err_text = gettext_noop("during initialization of execution state");
209 for (i = 0; i < estate.ndatums; i++)
210 estate.datums[i] = copy_plpgsql_datum(func->datums[i]);
213 * Store the actual call argument values into the appropriate variables
215 estate.err_text = gettext_noop("while storing call arguments into local variables");
216 for (i = 0; i < func->fn_nargs; i++)
218 int n = func->fn_argvarnos[i];
220 switch (estate.datums[n]->dtype)
222 case PLPGSQL_DTYPE_VAR:
224 PLpgSQL_var *var = (PLpgSQL_var *) estate.datums[n];
226 var->value = fcinfo->arg[i];
227 var->isnull = fcinfo->argnull[i];
228 var->freeval = false;
232 case PLPGSQL_DTYPE_ROW:
234 PLpgSQL_row *row = (PLpgSQL_row *) estate.datums[n];
236 if (!fcinfo->argnull[i])
242 HeapTupleData tmptup;
244 td = DatumGetHeapTupleHeader(fcinfo->arg[i]);
245 /* Extract rowtype info and find a tupdesc */
246 tupType = HeapTupleHeaderGetTypeId(td);
247 tupTypmod = HeapTupleHeaderGetTypMod(td);
248 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
249 /* Build a temporary HeapTuple control structure */
250 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
251 ItemPointerSetInvalid(&(tmptup.t_self));
252 tmptup.t_tableOid = InvalidOid;
254 exec_move_row(&estate, NULL, row, &tmptup, tupdesc);
255 ReleaseTupleDesc(tupdesc);
259 /* If arg is null, treat it as an empty row */
260 exec_move_row(&estate, NULL, row, NULL, NULL);
266 elog(ERROR, "unrecognized dtype: %d", func->datums[i]->dtype);
270 estate.err_text = gettext_noop("during function entry");
273 * Set the magic variable FOUND to false
275 exec_set_found(&estate, false);
278 * Let the instrumentation plugin peek at this function
280 if (*plugin_ptr && (*plugin_ptr)->func_beg)
281 ((*plugin_ptr)->func_beg) (&estate, func);
284 * Now call the toplevel block of statements
286 estate.err_text = NULL;
287 estate.err_stmt = (PLpgSQL_stmt *) (func->action);
288 rc = exec_stmt_block(&estate, func->action);
289 if (rc != PLPGSQL_RC_RETURN)
291 estate.err_stmt = NULL;
292 estate.err_text = NULL;
295 * Provide a more helpful message if a CONTINUE has been used outside
298 if (rc == PLPGSQL_RC_CONTINUE)
300 (errcode(ERRCODE_SYNTAX_ERROR),
301 errmsg("CONTINUE cannot be used outside a loop")));
304 (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
305 errmsg("control reached end of function without RETURN")));
309 * We got a return value - process it
311 estate.err_stmt = NULL;
312 estate.err_text = gettext_noop("while casting return value to function's return type");
314 fcinfo->isnull = estate.retisnull;
318 ReturnSetInfo *rsi = estate.rsi;
320 /* Check caller can handle a set result */
321 if (!rsi || !IsA(rsi, ReturnSetInfo) ||
322 (rsi->allowedModes & SFRM_Materialize) == 0)
324 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
325 errmsg("set-valued function called in context that cannot accept a set")));
326 rsi->returnMode = SFRM_Materialize;
328 /* If we produced any tuples, send back the result */
329 if (estate.tuple_store)
331 rsi->setResult = estate.tuple_store;
332 if (estate.rettupdesc)
334 MemoryContext oldcxt;
336 oldcxt = MemoryContextSwitchTo(estate.tuple_store_cxt);
337 rsi->setDesc = CreateTupleDescCopy(estate.rettupdesc);
338 MemoryContextSwitchTo(oldcxt);
341 estate.retval = (Datum) 0;
342 fcinfo->isnull = true;
344 else if (!estate.retisnull)
346 if (estate.retistuple)
349 * We have to check that the returned tuple actually matches the
350 * expected result type. XXX would be better to cache the tupdesc
351 * instead of repeating get_call_result_type()
355 switch (get_call_result_type(fcinfo, NULL, &tupdesc))
357 case TYPEFUNC_COMPOSITE:
358 /* got the expected result rowtype, now check it */
359 if (estate.rettupdesc == NULL ||
360 !compatible_tupdesc(estate.rettupdesc, tupdesc))
362 (errcode(ERRCODE_DATATYPE_MISMATCH),
363 errmsg("returned record type does not match expected record type")));
365 case TYPEFUNC_RECORD:
368 * Failed to determine actual type of RECORD. We could
369 * raise an error here, but what this means in practice is
370 * that the caller is expecting any old generic rowtype,
371 * so we don't really need to be restrictive. Pass back
372 * the generated result type, instead.
374 tupdesc = estate.rettupdesc;
375 if (tupdesc == NULL) /* shouldn't happen */
376 elog(ERROR, "return type must be a row type");
379 /* shouldn't get here if retistuple is true ... */
380 elog(ERROR, "return type must be a row type");
385 * Copy tuple to upper executor memory, as a tuple Datum. Make
386 * sure it is labeled with the caller-supplied tuple type.
389 PointerGetDatum(SPI_returntuple((HeapTuple) (estate.retval),
394 /* Cast value to proper type */
395 estate.retval = exec_cast_value(estate.retval, estate.rettype,
397 &(func->fn_retinput),
398 func->fn_rettypioparam,
403 * If the function's return type isn't by value, copy the value
404 * into upper executor memory context.
406 if (!fcinfo->isnull && !func->fn_retbyval)
411 len = datumGetSize(estate.retval, false, func->fn_rettyplen);
412 tmp = (void *) SPI_palloc(len);
413 memcpy(tmp, DatumGetPointer(estate.retval), len);
414 estate.retval = PointerGetDatum(tmp);
419 estate.err_text = gettext_noop("during function exit");
422 * Let the instrumentation plugin peek at this function
424 if (*plugin_ptr && (*plugin_ptr)->func_end)
425 ((*plugin_ptr)->func_end) (&estate, func);
427 /* Clean up any leftover temporary memory */
428 FreeExprContext(estate.eval_econtext);
429 estate.eval_econtext = NULL;
430 exec_eval_cleanup(&estate);
433 * Pop the error context stack
435 error_context_stack = plerrcontext.previous;
438 * Return the function's result
440 return estate.retval;
445 * plpgsql_exec_trigger Called by the call handler for
450 plpgsql_exec_trigger(PLpgSQL_function *func,
451 TriggerData *trigdata)
453 PLpgSQL_execstate estate;
454 ErrorContextCallback plerrcontext;
458 PLpgSQL_rec *rec_new,
463 * Setup the execution state
465 plpgsql_estate_setup(&estate, func, NULL);
468 * Setup error traceback support for ereport()
470 plerrcontext.callback = plpgsql_exec_error_callback;
471 plerrcontext.arg = &estate;
472 plerrcontext.previous = error_context_stack;
473 error_context_stack = &plerrcontext;
476 * Make local execution copies of all the datums
478 estate.err_text = gettext_noop("during initialization of execution state");
479 for (i = 0; i < estate.ndatums; i++)
480 estate.datums[i] = copy_plpgsql_datum(func->datums[i]);
483 * Put the OLD and NEW tuples into record variables
485 rec_new = (PLpgSQL_rec *) (estate.datums[func->new_varno]);
486 rec_new->freetup = false;
487 rec_new->freetupdesc = false;
488 rec_old = (PLpgSQL_rec *) (estate.datums[func->old_varno]);
489 rec_old->freetup = false;
490 rec_old->freetupdesc = false;
492 if (TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
495 * Per-statement triggers don't use OLD/NEW variables
498 rec_new->tupdesc = NULL;
500 rec_old->tupdesc = NULL;
502 else if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
504 rec_new->tup = trigdata->tg_trigtuple;
505 rec_new->tupdesc = trigdata->tg_relation->rd_att;
507 rec_old->tupdesc = NULL;
509 else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
511 rec_new->tup = trigdata->tg_newtuple;
512 rec_new->tupdesc = trigdata->tg_relation->rd_att;
513 rec_old->tup = trigdata->tg_trigtuple;
514 rec_old->tupdesc = trigdata->tg_relation->rd_att;
516 else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
519 rec_new->tupdesc = NULL;
520 rec_old->tup = trigdata->tg_trigtuple;
521 rec_old->tupdesc = trigdata->tg_relation->rd_att;
524 elog(ERROR, "unrecognized trigger action: not INSERT, DELETE, or UPDATE");
527 * Assign the special tg_ variables
530 var = (PLpgSQL_var *) (estate.datums[func->tg_op_varno]);
531 if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
532 var->value = DirectFunctionCall1(textin, CStringGetDatum("INSERT"));
533 else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
534 var->value = DirectFunctionCall1(textin, CStringGetDatum("UPDATE"));
535 else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
536 var->value = DirectFunctionCall1(textin, CStringGetDatum("DELETE"));
538 elog(ERROR, "unrecognized trigger action: not INSERT, DELETE, or UPDATE");
542 var = (PLpgSQL_var *) (estate.datums[func->tg_name_varno]);
543 var->value = DirectFunctionCall1(namein,
544 CStringGetDatum(trigdata->tg_trigger->tgname));
548 var = (PLpgSQL_var *) (estate.datums[func->tg_when_varno]);
549 if (TRIGGER_FIRED_BEFORE(trigdata->tg_event))
550 var->value = DirectFunctionCall1(textin, CStringGetDatum("BEFORE"));
551 else if (TRIGGER_FIRED_AFTER(trigdata->tg_event))
552 var->value = DirectFunctionCall1(textin, CStringGetDatum("AFTER"));
554 elog(ERROR, "unrecognized trigger execution time: not BEFORE or AFTER");
558 var = (PLpgSQL_var *) (estate.datums[func->tg_level_varno]);
559 if (TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
560 var->value = DirectFunctionCall1(textin, CStringGetDatum("ROW"));
561 else if (TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
562 var->value = DirectFunctionCall1(textin, CStringGetDatum("STATEMENT"));
564 elog(ERROR, "unrecognized trigger event type: not ROW or STATEMENT");
568 var = (PLpgSQL_var *) (estate.datums[func->tg_relid_varno]);
569 var->value = ObjectIdGetDatum(trigdata->tg_relation->rd_id);
571 var->freeval = false;
573 var = (PLpgSQL_var *) (estate.datums[func->tg_relname_varno]);
574 var->value = DirectFunctionCall1(namein,
575 CStringGetDatum(RelationGetRelationName(trigdata->tg_relation)));
579 var = (PLpgSQL_var *) (estate.datums[func->tg_table_name_varno]);
580 var->value = DirectFunctionCall1(namein,
581 CStringGetDatum(RelationGetRelationName(trigdata->tg_relation)));
585 var = (PLpgSQL_var *) (estate.datums[func->tg_table_schema_varno]);
586 var->value = DirectFunctionCall1(namein,
589 RelationGetNamespace(
590 trigdata->tg_relation))));
594 var = (PLpgSQL_var *) (estate.datums[func->tg_nargs_varno]);
595 var->value = Int16GetDatum(trigdata->tg_trigger->tgnargs);
597 var->freeval = false;
600 * Store the trigger argument values into the special execution state
603 estate.err_text = gettext_noop("while storing call arguments into local variables");
604 estate.trig_nargs = trigdata->tg_trigger->tgnargs;
605 if (estate.trig_nargs == 0)
606 estate.trig_argv = NULL;
609 estate.trig_argv = palloc(sizeof(Datum) * estate.trig_nargs);
610 for (i = 0; i < trigdata->tg_trigger->tgnargs; i++)
611 estate.trig_argv[i] = DirectFunctionCall1(textin,
612 CStringGetDatum(trigdata->tg_trigger->tgargs[i]));
615 estate.err_text = gettext_noop("during function entry");
618 * Set the magic variable FOUND to false
620 exec_set_found(&estate, false);
623 * Let the instrumentation plugin peek at this function
625 if (*plugin_ptr && (*plugin_ptr)->func_beg)
626 ((*plugin_ptr)->func_beg) (&estate, func);
629 * Now call the toplevel block of statements
631 estate.err_text = NULL;
632 estate.err_stmt = (PLpgSQL_stmt *) (func->action);
633 rc = exec_stmt_block(&estate, func->action);
634 if (rc != PLPGSQL_RC_RETURN)
636 estate.err_stmt = NULL;
637 estate.err_text = NULL;
640 * Provide a more helpful message if a CONTINUE has been used outside
643 if (rc == PLPGSQL_RC_CONTINUE)
645 (errcode(ERRCODE_SYNTAX_ERROR),
646 errmsg("CONTINUE cannot be used outside a loop")));
649 (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
650 errmsg("control reached end of trigger procedure without RETURN")));
653 estate.err_stmt = NULL;
654 estate.err_text = gettext_noop("during function exit");
658 (errcode(ERRCODE_DATATYPE_MISMATCH),
659 errmsg("trigger procedure cannot return a set")));
662 * Check that the returned tuple structure has the same attributes, the
663 * relation that fired the trigger has. A per-statement trigger always
664 * needs to return NULL, so we ignore any return value the function itself
665 * produces (XXX: is this a good idea?)
667 * XXX This way it is possible, that the trigger returns a tuple where
668 * attributes don't have the correct atttypmod's length. It's up to the
669 * trigger's programmer to ensure that this doesn't happen. Jan
671 if (estate.retisnull || TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
675 if (!compatible_tupdesc(estate.rettupdesc,
676 trigdata->tg_relation->rd_att))
678 (errcode(ERRCODE_DATATYPE_MISMATCH),
679 errmsg("returned tuple structure does not match table of trigger event")));
680 /* Copy tuple to upper executor memory */
681 rettup = SPI_copytuple((HeapTuple) (estate.retval));
685 * Let the instrumentation plugin peek at this function
687 if (*plugin_ptr && (*plugin_ptr)->func_end)
688 ((*plugin_ptr)->func_end) (&estate, func);
690 /* Clean up any leftover temporary memory */
691 FreeExprContext(estate.eval_econtext);
692 estate.eval_econtext = NULL;
693 exec_eval_cleanup(&estate);
696 * Pop the error context stack
698 error_context_stack = plerrcontext.previous;
701 * Return the trigger's result
708 * error context callback to let us supply a call-stack traceback
711 plpgsql_exec_error_callback(void *arg)
713 PLpgSQL_execstate *estate = (PLpgSQL_execstate *) arg;
715 /* safety check, shouldn't happen */
716 if (estate->err_func == NULL)
719 /* if we are doing RAISE, don't report its location */
720 if (estate->err_text == raise_skip_msg)
723 if (estate->err_text != NULL)
726 * We don't expend the cycles to run gettext() on err_text unless we
727 * actually need it. Therefore, places that set up err_text should
728 * use gettext_noop() to ensure the strings get recorded in the
729 * message dictionary.
731 * If both err_text and err_stmt are set, use the err_text as
732 * description, but report the err_stmt's line number. When
733 * err_stmt is not set, we're in function entry/exit, or some such
734 * place not attached to a specific line number.
736 if (estate->err_stmt != NULL)
739 * translator: last %s is a phrase such as "during statement
740 * block local variable initialization"
742 errcontext("PL/pgSQL function \"%s\" line %d %s",
743 estate->err_func->fn_name,
744 estate->err_stmt->lineno,
745 gettext(estate->err_text));
750 * translator: last %s is a phrase such as "while storing call
751 * arguments into local variables"
753 errcontext("PL/pgSQL function \"%s\" %s",
754 estate->err_func->fn_name,
755 gettext(estate->err_text));
758 else if (estate->err_stmt != NULL)
760 /* translator: last %s is a plpgsql statement type name */
761 errcontext("PL/pgSQL function \"%s\" line %d at %s",
762 estate->err_func->fn_name,
763 estate->err_stmt->lineno,
764 plpgsql_stmt_typename(estate->err_stmt));
767 errcontext("PL/pgSQL function \"%s\"",
768 estate->err_func->fn_name);
773 * Support function for initializing local execution variables
776 static PLpgSQL_datum *
777 copy_plpgsql_datum(PLpgSQL_datum *datum)
779 PLpgSQL_datum *result;
781 switch (datum->dtype)
783 case PLPGSQL_DTYPE_VAR:
785 PLpgSQL_var *new = palloc(sizeof(PLpgSQL_var));
787 memcpy(new, datum, sizeof(PLpgSQL_var));
788 /* Ensure the value is null (possibly not needed?) */
791 new->freeval = false;
793 result = (PLpgSQL_datum *) new;
797 case PLPGSQL_DTYPE_REC:
799 PLpgSQL_rec *new = palloc(sizeof(PLpgSQL_rec));
801 memcpy(new, datum, sizeof(PLpgSQL_rec));
802 /* Ensure the value is null (possibly not needed?) */
805 new->freetup = false;
806 new->freetupdesc = false;
808 result = (PLpgSQL_datum *) new;
812 case PLPGSQL_DTYPE_ROW:
813 case PLPGSQL_DTYPE_RECFIELD:
814 case PLPGSQL_DTYPE_ARRAYELEM:
815 case PLPGSQL_DTYPE_TRIGARG:
818 * These datum records are read-only at runtime, so no need to
825 elog(ERROR, "unrecognized dtype: %d", datum->dtype);
826 result = NULL; /* keep compiler quiet */
835 exception_matches_conditions(ErrorData *edata, PLpgSQL_condition *cond)
837 for (; cond != NULL; cond = cond->next)
839 int sqlerrstate = cond->sqlerrstate;
842 * OTHERS matches everything *except* query-canceled; if you're
843 * foolish enough, you can match that explicitly.
845 if (sqlerrstate == 0)
847 if (edata->sqlerrcode != ERRCODE_QUERY_CANCELED)
851 else if (edata->sqlerrcode == sqlerrstate)
853 /* Category match? */
854 else if (ERRCODE_IS_CATEGORY(sqlerrstate) &&
855 ERRCODE_TO_CATEGORY(edata->sqlerrcode) == sqlerrstate)
863 * exec_stmt_block Execute a block of statements
867 exec_stmt_block(PLpgSQL_execstate *estate, PLpgSQL_stmt_block *block)
869 volatile int rc = -1;
874 * First initialize all variables declared in this block
876 estate->err_text = gettext_noop("during statement block local variable initialization");
878 for (i = 0; i < block->n_initvars; i++)
880 n = block->initvarnos[i];
882 switch (estate->datums[n]->dtype)
884 case PLPGSQL_DTYPE_VAR:
886 PLpgSQL_var *var = (PLpgSQL_var *) (estate->datums[n]);
889 if (!var->isconst || var->isnull)
891 if (var->default_val == NULL)
893 var->value = (Datum) 0;
897 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
898 errmsg("variable \"%s\" declared NOT NULL cannot default to NULL",
903 exec_assign_expr(estate, (PLpgSQL_datum *) var,
910 case PLPGSQL_DTYPE_REC:
912 PLpgSQL_rec *rec = (PLpgSQL_rec *) (estate->datums[n]);
916 heap_freetuple(rec->tup);
917 FreeTupleDesc(rec->tupdesc);
918 rec->freetup = false;
926 case PLPGSQL_DTYPE_RECFIELD:
927 case PLPGSQL_DTYPE_ARRAYELEM:
931 elog(ERROR, "unrecognized dtype: %d",
932 estate->datums[n]->dtype);
936 if (block->exceptions)
939 * Execute the statements in the block's body inside a sub-transaction
941 MemoryContext oldcontext = CurrentMemoryContext;
942 ResourceOwner oldowner = CurrentResourceOwner;
943 ExprContext *old_eval_econtext = estate->eval_econtext;
944 EState *old_eval_estate = estate->eval_estate;
945 long int old_eval_estate_simple_id = estate->eval_estate_simple_id;
947 estate->err_text = gettext_noop("during statement block entry");
949 BeginInternalSubTransaction(NULL);
950 /* Want to run statements inside function's memory context */
951 MemoryContextSwitchTo(oldcontext);
956 * We need to run the block's statements with a new eval_econtext
957 * that belongs to the current subtransaction; if we try to use
958 * the outer econtext then ExprContext shutdown callbacks will be
959 * called at the wrong times.
961 plpgsql_create_econtext(estate);
963 estate->err_text = NULL;
965 /* Run the block's statements */
966 rc = exec_stmts(estate, block->body);
968 estate->err_text = gettext_noop("during statement block exit");
970 /* Commit the inner transaction, return to outer xact context */
971 ReleaseCurrentSubTransaction();
972 MemoryContextSwitchTo(oldcontext);
973 CurrentResourceOwner = oldowner;
975 /* Revert to outer eval_econtext */
976 estate->eval_econtext = old_eval_econtext;
977 estate->eval_estate = old_eval_estate;
978 estate->eval_estate_simple_id = old_eval_estate_simple_id;
981 * AtEOSubXact_SPI() should not have popped any SPI context, but
982 * just in case it did, make sure we remain connected.
984 SPI_restore_connection();
991 estate->err_text = gettext_noop("during exception cleanup");
993 /* Save error info */
994 MemoryContextSwitchTo(oldcontext);
995 edata = CopyErrorData();
998 /* Abort the inner transaction */
999 RollbackAndReleaseCurrentSubTransaction();
1000 MemoryContextSwitchTo(oldcontext);
1001 CurrentResourceOwner = oldowner;
1003 /* Revert to outer eval_econtext */
1004 estate->eval_econtext = old_eval_econtext;
1005 estate->eval_estate = old_eval_estate;
1006 estate->eval_estate_simple_id = old_eval_estate_simple_id;
1009 * If AtEOSubXact_SPI() popped any SPI context of the subxact, it
1010 * will have left us in a disconnected state. We need this hack
1011 * to return to connected state.
1013 SPI_restore_connection();
1015 /* Look for a matching exception handler */
1016 foreach(e, block->exceptions->exc_list)
1018 PLpgSQL_exception *exception = (PLpgSQL_exception *) lfirst(e);
1020 if (exception_matches_conditions(edata, exception->conditions))
1023 * Initialize the magic SQLSTATE and SQLERRM variables for
1024 * the exception block. We needn't do this until we have
1025 * found a matching exception.
1027 PLpgSQL_var *state_var;
1028 PLpgSQL_var *errm_var;
1030 state_var = (PLpgSQL_var *)
1031 estate->datums[block->exceptions->sqlstate_varno];
1032 state_var->value = DirectFunctionCall1(textin,
1033 CStringGetDatum(unpack_sql_state(edata->sqlerrcode)));
1034 state_var->freeval = true;
1035 state_var->isnull = false;
1037 errm_var = (PLpgSQL_var *)
1038 estate->datums[block->exceptions->sqlerrm_varno];
1039 errm_var->value = DirectFunctionCall1(textin,
1040 CStringGetDatum(edata->message));
1041 errm_var->freeval = true;
1042 errm_var->isnull = false;
1044 estate->err_text = NULL;
1046 rc = exec_stmts(estate, exception->action);
1048 free_var(state_var);
1054 /* If no match found, re-throw the error */
1056 ReThrowError(edata);
1058 FreeErrorData(edata);
1065 * Just execute the statements in the block's body
1067 estate->err_text = NULL;
1069 rc = exec_stmts(estate, block->body);
1072 estate->err_text = NULL;
1075 * Handle the return code.
1080 case PLPGSQL_RC_CONTINUE:
1081 case PLPGSQL_RC_RETURN:
1084 case PLPGSQL_RC_EXIT:
1085 if (estate->exitlabel == NULL)
1086 return PLPGSQL_RC_OK;
1087 if (block->label == NULL)
1088 return PLPGSQL_RC_EXIT;
1089 if (strcmp(block->label, estate->exitlabel))
1090 return PLPGSQL_RC_EXIT;
1091 estate->exitlabel = NULL;
1092 return PLPGSQL_RC_OK;
1095 elog(ERROR, "unrecognized rc: %d", rc);
1098 return PLPGSQL_RC_OK;
1103 * exec_stmts Iterate over a list of statements
1104 * as long as their return code is OK
1108 exec_stmts(PLpgSQL_execstate *estate, List *stmts)
1115 * Ensure we do a CHECK_FOR_INTERRUPTS() even though there is no
1116 * statement. This prevents hangup in a tight loop if, for instance,
1117 * there is a LOOP construct with an empty body.
1119 CHECK_FOR_INTERRUPTS();
1120 return PLPGSQL_RC_OK;
1125 PLpgSQL_stmt *stmt = (PLpgSQL_stmt *) lfirst(s);
1126 int rc = exec_stmt(estate, stmt);
1128 if (rc != PLPGSQL_RC_OK)
1132 return PLPGSQL_RC_OK;
1137 * exec_stmt Distribute one statement to the statements
1138 * type specific execution function.
1142 exec_stmt(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
1144 PLpgSQL_stmt *save_estmt;
1147 save_estmt = estate->err_stmt;
1148 estate->err_stmt = stmt;
1150 /* Let the plugin know that we are about to execute this statement */
1151 if (*plugin_ptr && (*plugin_ptr)->stmt_beg)
1152 ((*plugin_ptr)->stmt_beg) (estate, stmt);
1154 CHECK_FOR_INTERRUPTS();
1156 switch (stmt->cmd_type)
1158 case PLPGSQL_STMT_BLOCK:
1159 rc = exec_stmt_block(estate, (PLpgSQL_stmt_block *) stmt);
1162 case PLPGSQL_STMT_ASSIGN:
1163 rc = exec_stmt_assign(estate, (PLpgSQL_stmt_assign *) stmt);
1166 case PLPGSQL_STMT_PERFORM:
1167 rc = exec_stmt_perform(estate, (PLpgSQL_stmt_perform *) stmt);
1170 case PLPGSQL_STMT_GETDIAG:
1171 rc = exec_stmt_getdiag(estate, (PLpgSQL_stmt_getdiag *) stmt);
1174 case PLPGSQL_STMT_IF:
1175 rc = exec_stmt_if(estate, (PLpgSQL_stmt_if *) stmt);
1178 case PLPGSQL_STMT_LOOP:
1179 rc = exec_stmt_loop(estate, (PLpgSQL_stmt_loop *) stmt);
1182 case PLPGSQL_STMT_WHILE:
1183 rc = exec_stmt_while(estate, (PLpgSQL_stmt_while *) stmt);
1186 case PLPGSQL_STMT_FORI:
1187 rc = exec_stmt_fori(estate, (PLpgSQL_stmt_fori *) stmt);
1190 case PLPGSQL_STMT_FORS:
1191 rc = exec_stmt_fors(estate, (PLpgSQL_stmt_fors *) stmt);
1194 case PLPGSQL_STMT_EXIT:
1195 rc = exec_stmt_exit(estate, (PLpgSQL_stmt_exit *) stmt);
1198 case PLPGSQL_STMT_RETURN:
1199 rc = exec_stmt_return(estate, (PLpgSQL_stmt_return *) stmt);
1202 case PLPGSQL_STMT_RETURN_NEXT:
1203 rc = exec_stmt_return_next(estate, (PLpgSQL_stmt_return_next *) stmt);
1206 case PLPGSQL_STMT_RAISE:
1207 rc = exec_stmt_raise(estate, (PLpgSQL_stmt_raise *) stmt);
1210 case PLPGSQL_STMT_EXECSQL:
1211 rc = exec_stmt_execsql(estate, (PLpgSQL_stmt_execsql *) stmt);
1214 case PLPGSQL_STMT_DYNEXECUTE:
1215 rc = exec_stmt_dynexecute(estate, (PLpgSQL_stmt_dynexecute *) stmt);
1218 case PLPGSQL_STMT_DYNFORS:
1219 rc = exec_stmt_dynfors(estate, (PLpgSQL_stmt_dynfors *) stmt);
1222 case PLPGSQL_STMT_OPEN:
1223 rc = exec_stmt_open(estate, (PLpgSQL_stmt_open *) stmt);
1226 case PLPGSQL_STMT_FETCH:
1227 rc = exec_stmt_fetch(estate, (PLpgSQL_stmt_fetch *) stmt);
1230 case PLPGSQL_STMT_CLOSE:
1231 rc = exec_stmt_close(estate, (PLpgSQL_stmt_close *) stmt);
1235 estate->err_stmt = save_estmt;
1236 elog(ERROR, "unrecognized cmdtype: %d", stmt->cmd_type);
1239 /* Let the plugin know that we have finished executing this statement */
1240 if (*plugin_ptr && (*plugin_ptr)->stmt_end)
1241 ((*plugin_ptr)->stmt_end) (estate, stmt);
1243 estate->err_stmt = save_estmt;
1250 * exec_stmt_assign Evaluate an expression and
1251 * put the result into a variable.
1255 exec_stmt_assign(PLpgSQL_execstate *estate, PLpgSQL_stmt_assign *stmt)
1257 Assert(stmt->varno >= 0);
1259 exec_assign_expr(estate, estate->datums[stmt->varno], stmt->expr);
1261 return PLPGSQL_RC_OK;
1265 * exec_stmt_perform Evaluate query and discard result (but set
1266 * FOUND depending on whether at least one row
1271 exec_stmt_perform(PLpgSQL_execstate *estate, PLpgSQL_stmt_perform *stmt)
1273 PLpgSQL_expr *expr = stmt->expr;
1275 (void) exec_run_select(estate, expr, 0, NULL);
1276 exec_set_found(estate, (estate->eval_processed != 0));
1277 exec_eval_cleanup(estate);
1279 return PLPGSQL_RC_OK;
1283 * exec_stmt_getdiag Put internal PG information into
1284 * specified variables.
1288 exec_stmt_getdiag(PLpgSQL_execstate *estate, PLpgSQL_stmt_getdiag *stmt)
1292 foreach(lc, stmt->diag_items)
1294 PLpgSQL_diag_item *diag_item = (PLpgSQL_diag_item *) lfirst(lc);
1296 bool isnull = false;
1298 if (diag_item->target <= 0)
1301 var = estate->datums[diag_item->target];
1306 switch (diag_item->kind)
1308 case PLPGSQL_GETDIAG_ROW_COUNT:
1310 exec_assign_value(estate, var,
1311 UInt32GetDatum(estate->eval_processed),
1315 case PLPGSQL_GETDIAG_RESULT_OID:
1317 exec_assign_value(estate, var,
1318 ObjectIdGetDatum(estate->eval_lastoid),
1323 elog(ERROR, "unrecognized attribute request: %d",
1328 return PLPGSQL_RC_OK;
1332 * exec_stmt_if Evaluate a bool expression and
1333 * execute the true or false body
1338 exec_stmt_if(PLpgSQL_execstate *estate, PLpgSQL_stmt_if *stmt)
1343 value = exec_eval_boolean(estate, stmt->cond, &isnull);
1344 exec_eval_cleanup(estate);
1346 if (!isnull && value)
1348 if (stmt->true_body != NIL)
1349 return exec_stmts(estate, stmt->true_body);
1353 if (stmt->false_body != NIL)
1354 return exec_stmts(estate, stmt->false_body);
1357 return PLPGSQL_RC_OK;
1362 * exec_stmt_loop Loop over statements until
1367 exec_stmt_loop(PLpgSQL_execstate *estate, PLpgSQL_stmt_loop *stmt)
1371 int rc = exec_stmts(estate, stmt->body);
1378 case PLPGSQL_RC_EXIT:
1379 if (estate->exitlabel == NULL)
1380 return PLPGSQL_RC_OK;
1381 if (stmt->label == NULL)
1382 return PLPGSQL_RC_EXIT;
1383 if (strcmp(stmt->label, estate->exitlabel) != 0)
1384 return PLPGSQL_RC_EXIT;
1385 estate->exitlabel = NULL;
1386 return PLPGSQL_RC_OK;
1388 case PLPGSQL_RC_CONTINUE:
1389 if (estate->exitlabel == NULL)
1390 /* anonymous continue, so re-run the loop */
1392 else if (stmt->label != NULL &&
1393 strcmp(stmt->label, estate->exitlabel) == 0)
1394 /* label matches named continue, so re-run loop */
1395 estate->exitlabel = NULL;
1397 /* label doesn't match named continue, so propagate upward */
1398 return PLPGSQL_RC_CONTINUE;
1401 case PLPGSQL_RC_RETURN:
1402 return PLPGSQL_RC_RETURN;
1405 elog(ERROR, "unrecognized rc: %d", rc);
1409 return PLPGSQL_RC_OK;
1414 * exec_stmt_while Loop over statements as long
1415 * as an expression evaluates to
1416 * true or an exit occurs.
1420 exec_stmt_while(PLpgSQL_execstate *estate, PLpgSQL_stmt_while *stmt)
1428 value = exec_eval_boolean(estate, stmt->cond, &isnull);
1429 exec_eval_cleanup(estate);
1431 if (isnull || !value)
1434 rc = exec_stmts(estate, stmt->body);
1441 case PLPGSQL_RC_EXIT:
1442 if (estate->exitlabel == NULL)
1443 return PLPGSQL_RC_OK;
1444 if (stmt->label == NULL)
1445 return PLPGSQL_RC_EXIT;
1446 if (strcmp(stmt->label, estate->exitlabel))
1447 return PLPGSQL_RC_EXIT;
1448 estate->exitlabel = NULL;
1449 return PLPGSQL_RC_OK;
1451 case PLPGSQL_RC_CONTINUE:
1452 if (estate->exitlabel == NULL)
1453 /* anonymous continue, so re-run loop */
1455 else if (stmt->label != NULL &&
1456 strcmp(stmt->label, estate->exitlabel) == 0)
1457 /* label matches named continue, so re-run loop */
1458 estate->exitlabel = NULL;
1460 /* label doesn't match named continue, propagate upward */
1461 return PLPGSQL_RC_CONTINUE;
1464 case PLPGSQL_RC_RETURN:
1465 return PLPGSQL_RC_RETURN;
1468 elog(ERROR, "unrecognized rc: %d", rc);
1472 return PLPGSQL_RC_OK;
1477 * exec_stmt_fori Iterate an integer variable
1478 * from a lower to an upper value
1479 * incrementing or decrementing in BY value
1480 * Loop can be left with exit.
1484 exec_stmt_fori(PLpgSQL_execstate *estate, PLpgSQL_stmt_fori *stmt)
1492 int rc = PLPGSQL_RC_OK;
1494 var = (PLpgSQL_var *) (estate->datums[stmt->var->varno]);
1497 * Get the value of the lower bound into the loop var
1499 value = exec_eval_expr(estate, stmt->lower, &isnull, &valtype);
1500 value = exec_cast_value(value, valtype, var->datatype->typoid,
1501 &(var->datatype->typinput),
1502 var->datatype->typioparam,
1503 var->datatype->atttypmod, isnull);
1506 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1507 errmsg("lower bound of FOR loop cannot be NULL")));
1509 var->isnull = false;
1510 exec_eval_cleanup(estate);
1513 * Get the value of the upper bound
1515 value = exec_eval_expr(estate, stmt->upper, &isnull, &valtype);
1516 value = exec_cast_value(value, valtype, var->datatype->typoid,
1517 &(var->datatype->typinput),
1518 var->datatype->typioparam,
1519 var->datatype->atttypmod, isnull);
1522 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1523 errmsg("upper bound of FOR loop cannot be NULL")));
1524 exec_eval_cleanup(estate);
1529 by_value = exec_eval_expr(estate, stmt->by, &isnull, &valtype);
1530 by_value = exec_cast_value(by_value, valtype, var->datatype->typoid,
1531 &(var->datatype->typinput),
1532 var->datatype->typioparam,
1533 var->datatype->atttypmod, isnull);
1537 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1538 errmsg("by value of FOR loop cannot be NULL")));
1539 exec_eval_cleanup(estate);
1551 if ((int4) (var->value) < (int4) value)
1556 if ((int4) (var->value) > (int4) value)
1560 found = true; /* looped at least once */
1563 * Execute the statements
1565 rc = exec_stmts(estate, stmt->body);
1567 if (rc == PLPGSQL_RC_RETURN)
1568 break; /* return from function */
1569 else if (rc == PLPGSQL_RC_EXIT)
1571 if (estate->exitlabel == NULL)
1572 /* unlabelled exit, finish the current loop */
1574 else if (stmt->label != NULL &&
1575 strcmp(stmt->label, estate->exitlabel) == 0)
1577 /* labelled exit, matches the current stmt's label */
1578 estate->exitlabel = NULL;
1583 * otherwise, this is a labelled exit that does not match the
1584 * current statement's label, if any: return RC_EXIT so that the
1585 * EXIT continues to propagate up the stack.
1590 else if (rc == PLPGSQL_RC_CONTINUE)
1592 if (estate->exitlabel == NULL)
1593 /* anonymous continue, so re-run the current loop */
1595 else if (stmt->label != NULL &&
1596 strcmp(stmt->label, estate->exitlabel) == 0)
1598 /* label matches named continue, so re-run loop */
1599 estate->exitlabel = NULL;
1605 * otherwise, this is a named continue that does not match the
1606 * current statement's label, if any: return RC_CONTINUE so
1607 * that the CONTINUE will propagate up the stack.
1614 * Increase/decrease loop var
1617 var->value -= by_value;
1619 var->value += by_value;
1623 * Set the FOUND variable to indicate the result of executing the loop
1624 * (namely, whether we looped one or more times). This must be set here so
1625 * that it does not interfere with the value of the FOUND variable inside
1626 * the loop processing itself.
1628 exec_set_found(estate, found);
1635 * exec_stmt_fors Execute a query, assign each
1636 * tuple to a record or row and
1637 * execute a group of statements
1642 exec_stmt_fors(PLpgSQL_execstate *estate, PLpgSQL_stmt_fors *stmt)
1644 PLpgSQL_rec *rec = NULL;
1645 PLpgSQL_row *row = NULL;
1646 SPITupleTable *tuptab;
1649 int rc = PLPGSQL_RC_OK;
1654 * Determine if we assign to a record or a row
1656 if (stmt->rec != NULL)
1657 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
1658 else if (stmt->row != NULL)
1659 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
1661 elog(ERROR, "unsupported target");
1664 * Open the implicit cursor for the statement and fetch the initial 10
1667 exec_run_select(estate, stmt->query, 0, &portal);
1669 SPI_cursor_fetch(portal, true, 10);
1670 tuptab = SPI_tuptable;
1674 * If the query didn't return any rows, set the target to NULL and return
1675 * with FOUND = false.
1678 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
1680 found = true; /* processed at least one tuple */
1687 for (i = 0; i < n; i++)
1690 * Assign the tuple to the target
1692 exec_move_row(estate, rec, row, tuptab->vals[i], tuptab->tupdesc);
1695 * Execute the statements
1697 rc = exec_stmts(estate, stmt->body);
1698 if (rc != PLPGSQL_RC_OK)
1700 if (rc == PLPGSQL_RC_EXIT)
1702 if (estate->exitlabel == NULL)
1703 /* unlabelled exit, finish the current loop */
1705 else if (stmt->label != NULL &&
1706 strcmp(stmt->label, estate->exitlabel) == 0)
1708 /* labelled exit, matches the current stmt's label */
1709 estate->exitlabel = NULL;
1714 * otherwise, we processed a labelled exit that does not
1715 * match the current statement's label, if any: return
1716 * RC_EXIT so that the EXIT continues to recurse upward.
1719 else if (rc == PLPGSQL_RC_CONTINUE)
1721 if (estate->exitlabel == NULL)
1723 /* anonymous continue, so re-run the current loop */
1727 else if (stmt->label != NULL &&
1728 strcmp(stmt->label, estate->exitlabel) == 0)
1730 /* label matches named continue, so re-run loop */
1732 estate->exitlabel = NULL;
1737 * otherwise, we processed a named continue that does not
1738 * match the current statement's label, if any: return
1739 * RC_CONTINUE so that the CONTINUE will propagate up the
1745 * We're aborting the loop, so cleanup and set FOUND. (This
1746 * code should match the code after the loop.)
1748 SPI_freetuptable(tuptab);
1749 SPI_cursor_close(portal);
1750 exec_set_found(estate, found);
1756 SPI_freetuptable(tuptab);
1759 * Fetch the next 50 tuples
1761 SPI_cursor_fetch(portal, true, 50);
1763 tuptab = SPI_tuptable;
1767 * Release last group of tuples
1769 SPI_freetuptable(tuptab);
1772 * Close the implicit cursor
1774 SPI_cursor_close(portal);
1777 * Set the FOUND variable to indicate the result of executing the loop
1778 * (namely, whether we looped one or more times). This must be set here so
1779 * that it does not interfere with the value of the FOUND variable inside
1780 * the loop processing itself.
1782 exec_set_found(estate, found);
1789 * exec_stmt_exit Implements EXIT and CONTINUE
1791 * This begins the process of exiting / restarting a loop.
1795 exec_stmt_exit(PLpgSQL_execstate *estate, PLpgSQL_stmt_exit *stmt)
1798 * If the exit / continue has a condition, evaluate it
1800 if (stmt->cond != NULL)
1805 value = exec_eval_boolean(estate, stmt->cond, &isnull);
1806 exec_eval_cleanup(estate);
1807 if (isnull || value == false)
1808 return PLPGSQL_RC_OK;
1811 estate->exitlabel = stmt->label;
1813 return PLPGSQL_RC_EXIT;
1815 return PLPGSQL_RC_CONTINUE;
1820 * exec_stmt_return Evaluate an expression and start
1821 * returning from the function.
1825 exec_stmt_return(PLpgSQL_execstate *estate, PLpgSQL_stmt_return *stmt)
1828 * If processing a set-returning PL/PgSQL function, the final RETURN
1829 * indicates that the function is finished producing tuples. The rest of
1830 * the work will be done at the top level.
1832 if (estate->retisset)
1833 return PLPGSQL_RC_RETURN;
1835 /* initialize for null result (possibly a tuple) */
1836 estate->retval = (Datum) 0;
1837 estate->rettupdesc = NULL;
1838 estate->retisnull = true;
1840 if (stmt->retvarno >= 0)
1842 PLpgSQL_datum *retvar = estate->datums[stmt->retvarno];
1844 switch (retvar->dtype)
1846 case PLPGSQL_DTYPE_VAR:
1848 PLpgSQL_var *var = (PLpgSQL_var *) retvar;
1850 estate->retval = var->value;
1851 estate->retisnull = var->isnull;
1852 estate->rettype = var->datatype->typoid;
1856 case PLPGSQL_DTYPE_REC:
1858 PLpgSQL_rec *rec = (PLpgSQL_rec *) retvar;
1860 if (HeapTupleIsValid(rec->tup))
1862 estate->retval = (Datum) rec->tup;
1863 estate->rettupdesc = rec->tupdesc;
1864 estate->retisnull = false;
1869 case PLPGSQL_DTYPE_ROW:
1871 PLpgSQL_row *row = (PLpgSQL_row *) retvar;
1873 Assert(row->rowtupdesc);
1874 estate->retval = (Datum) make_tuple_from_row(estate, row,
1876 if (estate->retval == (Datum) NULL) /* should not happen */
1877 elog(ERROR, "row not compatible with its own tupdesc");
1878 estate->rettupdesc = row->rowtupdesc;
1879 estate->retisnull = false;
1884 elog(ERROR, "unrecognized dtype: %d", retvar->dtype);
1887 return PLPGSQL_RC_RETURN;
1890 if (stmt->expr != NULL)
1892 if (estate->retistuple)
1894 exec_run_select(estate, stmt->expr, 1, NULL);
1895 if (estate->eval_processed > 0)
1897 estate->retval = (Datum) estate->eval_tuptable->vals[0];
1898 estate->rettupdesc = estate->eval_tuptable->tupdesc;
1899 estate->retisnull = false;
1904 /* Normal case for scalar results */
1905 estate->retval = exec_eval_expr(estate, stmt->expr,
1906 &(estate->retisnull),
1907 &(estate->rettype));
1910 return PLPGSQL_RC_RETURN;
1914 * Special hack for function returning VOID: instead of NULL, return a
1915 * non-null VOID value. This is of dubious importance but is kept for
1916 * backwards compatibility. Note that the only other way to get here is
1917 * to have written "RETURN NULL" in a function returning tuple.
1919 if (estate->fn_rettype == VOIDOID)
1921 estate->retval = (Datum) 0;
1922 estate->retisnull = false;
1923 estate->rettype = VOIDOID;
1926 return PLPGSQL_RC_RETURN;
1930 * exec_stmt_return_next Evaluate an expression and add it to the
1931 * list of tuples returned by the current
1936 exec_stmt_return_next(PLpgSQL_execstate *estate,
1937 PLpgSQL_stmt_return_next *stmt)
1942 bool free_tuple = false;
1944 if (!estate->retisset)
1946 (errcode(ERRCODE_SYNTAX_ERROR),
1947 errmsg("cannot use RETURN NEXT in a non-SETOF function")));
1949 if (estate->tuple_store == NULL)
1950 exec_init_tuple_store(estate);
1952 /* rettupdesc will be filled by exec_init_tuple_store */
1953 tupdesc = estate->rettupdesc;
1954 natts = tupdesc->natts;
1956 if (stmt->retvarno >= 0)
1958 PLpgSQL_datum *retvar = estate->datums[stmt->retvarno];
1960 switch (retvar->dtype)
1962 case PLPGSQL_DTYPE_VAR:
1964 PLpgSQL_var *var = (PLpgSQL_var *) retvar;
1965 Datum retval = var->value;
1966 bool isNull = var->isnull;
1970 (errcode(ERRCODE_DATATYPE_MISMATCH),
1971 errmsg("wrong result type supplied in RETURN NEXT")));
1973 /* coerce type if needed */
1974 retval = exec_simple_cast_value(retval,
1975 var->datatype->typoid,
1976 tupdesc->attrs[0]->atttypid,
1977 tupdesc->attrs[0]->atttypmod,
1980 tuple = heap_form_tuple(tupdesc, &retval, &isNull);
1986 case PLPGSQL_DTYPE_REC:
1988 PLpgSQL_rec *rec = (PLpgSQL_rec *) retvar;
1990 if (!HeapTupleIsValid(rec->tup))
1992 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1993 errmsg("record \"%s\" is not assigned yet",
1995 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
1996 if (!compatible_tupdesc(tupdesc, rec->tupdesc))
1998 (errcode(ERRCODE_DATATYPE_MISMATCH),
1999 errmsg("wrong record type supplied in RETURN NEXT")));
2004 case PLPGSQL_DTYPE_ROW:
2006 PLpgSQL_row *row = (PLpgSQL_row *) retvar;
2008 tuple = make_tuple_from_row(estate, row, tupdesc);
2011 (errcode(ERRCODE_DATATYPE_MISMATCH),
2012 errmsg("wrong record type supplied in RETURN NEXT")));
2018 elog(ERROR, "unrecognized dtype: %d", retvar->dtype);
2019 tuple = NULL; /* keep compiler quiet */
2023 else if (stmt->expr)
2031 (errcode(ERRCODE_DATATYPE_MISMATCH),
2032 errmsg("wrong result type supplied in RETURN NEXT")));
2034 retval = exec_eval_expr(estate,
2039 /* coerce type if needed */
2040 retval = exec_simple_cast_value(retval,
2042 tupdesc->attrs[0]->atttypid,
2043 tupdesc->attrs[0]->atttypmod,
2046 tuple = heap_form_tuple(tupdesc, &retval, &isNull);
2050 exec_eval_cleanup(estate);
2055 (errcode(ERRCODE_SYNTAX_ERROR),
2056 errmsg("RETURN NEXT must have a parameter")));
2057 tuple = NULL; /* keep compiler quiet */
2060 if (HeapTupleIsValid(tuple))
2062 MemoryContext oldcxt;
2064 oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
2065 tuplestore_puttuple(estate->tuple_store, tuple);
2066 MemoryContextSwitchTo(oldcxt);
2069 heap_freetuple(tuple);
2072 return PLPGSQL_RC_OK;
2076 exec_init_tuple_store(PLpgSQL_execstate *estate)
2078 ReturnSetInfo *rsi = estate->rsi;
2079 MemoryContext oldcxt;
2082 * Check caller can handle a set result in the way we want
2084 if (!rsi || !IsA(rsi, ReturnSetInfo) ||
2085 (rsi->allowedModes & SFRM_Materialize) == 0 ||
2086 rsi->expectedDesc == NULL)
2088 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2089 errmsg("set-valued function called in context that cannot accept a set")));
2091 estate->tuple_store_cxt = rsi->econtext->ecxt_per_query_memory;
2093 oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
2094 estate->tuple_store = tuplestore_begin_heap(true, false, work_mem);
2095 MemoryContextSwitchTo(oldcxt);
2097 estate->rettupdesc = rsi->expectedDesc;
2101 * exec_stmt_raise Build a message and throw it with elog()
2105 exec_stmt_raise(PLpgSQL_execstate *estate, PLpgSQL_stmt_raise *stmt)
2109 ListCell *current_param;
2111 plpgsql_dstring_init(&ds);
2112 current_param = list_head(stmt->params);
2114 for (cp = stmt->message; *cp; cp++)
2117 * Occurrences of a single % are replaced by the next parameter's
2118 * external representation. Double %'s are converted to one %.
2129 plpgsql_dstring_append_char(&ds, cp[1]);
2134 if (current_param == NULL)
2136 (errcode(ERRCODE_SYNTAX_ERROR),
2137 errmsg("too few parameters specified for RAISE")));
2139 paramvalue = exec_eval_expr(estate,
2140 (PLpgSQL_expr *) lfirst(current_param),
2147 extval = convert_value_to_string(paramvalue, paramtypeid);
2148 plpgsql_dstring_append(&ds, extval);
2149 current_param = lnext(current_param);
2150 exec_eval_cleanup(estate);
2154 plpgsql_dstring_append_char(&ds, cp[0]);
2158 * If more parameters were specified than were required to process the
2159 * format string, throw an error
2161 if (current_param != NULL)
2163 (errcode(ERRCODE_SYNTAX_ERROR),
2164 errmsg("too many parameters specified for RAISE")));
2167 * Throw the error (may or may not come back)
2169 estate->err_text = raise_skip_msg; /* suppress traceback of raise */
2171 ereport(stmt->elog_level,
2172 ((stmt->elog_level >= ERROR) ? errcode(ERRCODE_RAISE_EXCEPTION) : 0,
2173 errmsg_internal("%s", plpgsql_dstring_get(&ds))));
2175 estate->err_text = NULL; /* un-suppress... */
2177 plpgsql_dstring_free(&ds);
2179 return PLPGSQL_RC_OK;
2184 * Initialize a mostly empty execution state
2188 plpgsql_estate_setup(PLpgSQL_execstate *estate,
2189 PLpgSQL_function *func,
2192 estate->retval = (Datum) 0;
2193 estate->retisnull = true;
2194 estate->rettype = InvalidOid;
2196 estate->fn_rettype = func->fn_rettype;
2197 estate->retistuple = func->fn_retistuple;
2198 estate->retisset = func->fn_retset;
2200 estate->readonly_func = func->fn_readonly;
2202 estate->rettupdesc = NULL;
2203 estate->exitlabel = NULL;
2205 estate->tuple_store = NULL;
2206 estate->tuple_store_cxt = NULL;
2209 estate->trig_nargs = 0;
2210 estate->trig_argv = NULL;
2212 estate->found_varno = func->found_varno;
2213 estate->ndatums = func->ndatums;
2214 estate->datums = palloc(sizeof(PLpgSQL_datum *) * estate->ndatums);
2215 /* caller is expected to fill the datums array */
2217 estate->eval_tuptable = NULL;
2218 estate->eval_processed = 0;
2219 estate->eval_lastoid = InvalidOid;
2221 estate->err_func = func;
2222 estate->err_stmt = NULL;
2223 estate->err_text = NULL;
2226 * Create an EState and ExprContext for evaluation of simple expressions.
2228 plpgsql_create_econtext(estate);
2231 * Let the plugin see this function before we initialize any local
2232 * PL/pgSQL variables - note that we also give the plugin a few function
2233 * pointers so it can call back into PL/pgSQL for doing things like
2234 * variable assignments and stack traces
2238 (*plugin_ptr)->error_callback = plpgsql_exec_error_callback;
2239 (*plugin_ptr)->assign_expr = exec_assign_expr;
2241 if ((*plugin_ptr)->func_setup)
2242 ((*plugin_ptr)->func_setup) (estate, func);
2247 * Release temporary memory used by expression/subselect evaluation
2249 * NB: the result of the evaluation is no longer valid after this is done,
2250 * unless it is a pass-by-value datatype.
2254 exec_eval_cleanup(PLpgSQL_execstate *estate)
2256 /* Clear result of a full SPI_execute */
2257 if (estate->eval_tuptable != NULL)
2258 SPI_freetuptable(estate->eval_tuptable);
2259 estate->eval_tuptable = NULL;
2261 /* Clear result of exec_eval_simple_expr (but keep the econtext) */
2262 if (estate->eval_econtext != NULL)
2263 ResetExprContext(estate->eval_econtext);
2268 * Generate a prepared plan
2272 exec_prepare_plan(PLpgSQL_execstate *estate,
2276 _SPI_plan *spi_plan;
2281 * We need a temporary argtypes array to load with data. (The finished
2282 * plan structure will contain a copy of it.)
2284 argtypes = (Oid *) palloc(expr->nparams * sizeof(Oid));
2286 for (i = 0; i < expr->nparams; i++)
2291 exec_eval_datum(estate, estate->datums[expr->params[i]],
2293 &argtypes[i], ¶mval, ¶misnull);
2297 * Generate and save the plan
2299 plan = SPI_prepare(expr->query, expr->nparams, argtypes);
2302 /* Some SPI errors deserve specific error messages */
2305 case SPI_ERROR_COPY:
2307 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2308 errmsg("cannot COPY to/from client in PL/pgSQL")));
2309 case SPI_ERROR_CURSOR:
2311 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2312 errmsg("cannot manipulate cursors directly in PL/pgSQL"),
2313 errhint("Use PL/pgSQL's cursor features instead.")));
2314 case SPI_ERROR_TRANSACTION:
2316 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2317 errmsg("cannot begin/end transactions in PL/pgSQL"),
2318 errhint("Use a BEGIN block with an EXCEPTION clause instead.")));
2320 elog(ERROR, "SPI_prepare failed for \"%s\": %s",
2321 expr->query, SPI_result_code_string(SPI_result));
2324 expr->plan = SPI_saveplan(plan);
2325 spi_plan = (_SPI_plan *) expr->plan;
2326 expr->plan_argtypes = spi_plan->argtypes;
2327 expr->expr_simple_expr = NULL;
2328 exec_simple_check_plan(expr);
2336 * exec_stmt_execsql Execute an SQL statement (possibly with INTO).
2340 exec_stmt_execsql(PLpgSQL_execstate *estate,
2341 PLpgSQL_stmt_execsql *stmt)
2348 PLpgSQL_expr *expr = stmt->sqlstmt;
2351 * On the first call for this statement generate the plan, and detect
2352 * whether the statement is INSERT/UPDATE/DELETE
2354 if (expr->plan == NULL)
2356 _SPI_plan *spi_plan;
2359 exec_prepare_plan(estate, expr);
2360 stmt->mod_stmt = false;
2361 spi_plan = (_SPI_plan *) expr->plan;
2362 foreach(l, spi_plan->qtlist)
2366 foreach(l2, (List *) lfirst(l))
2368 Query *q = (Query *) lfirst(l2);
2370 Assert(IsA(q, Query));
2373 if (q->commandType == CMD_INSERT ||
2374 q->commandType == CMD_UPDATE ||
2375 q->commandType == CMD_DELETE)
2376 stmt->mod_stmt = true;
2383 * Now build up the values and nulls arguments for SPI_execute_plan()
2385 values = (Datum *) palloc(expr->nparams * sizeof(Datum));
2386 nulls = (char *) palloc(expr->nparams * sizeof(char));
2388 for (i = 0; i < expr->nparams; i++)
2390 PLpgSQL_datum *datum = estate->datums[expr->params[i]];
2394 exec_eval_datum(estate, datum, expr->plan_argtypes[i],
2395 ¶mtypeid, &values[i], ¶misnull);
2403 * If we have INTO, then we only need one row back ... but if we have INTO
2404 * STRICT, ask for two rows, so that we can verify the statement returns
2405 * only one. INSERT/UPDATE/DELETE are always treated strictly. Without
2406 * INTO, just run the statement to completion (tcount = 0).
2408 * We could just ask for two rows always when using INTO, but there are
2409 * some cases where demanding the extra row costs significant time, eg by
2410 * forcing completion of a sequential scan. So don't do it unless we need
2411 * to enforce strictness.
2415 if (stmt->strict || stmt->mod_stmt)
2426 rc = SPI_execute_plan(expr->plan, values, nulls,
2427 estate->readonly_func, tcount);
2430 * Check for error, and set FOUND if appropriate (for historical reasons
2431 * we set FOUND only for certain query types). Also Assert that we
2432 * identified the statement type the same as SPI did.
2437 Assert(!stmt->mod_stmt);
2438 exec_set_found(estate, (SPI_processed != 0));
2444 case SPI_OK_INSERT_RETURNING:
2445 case SPI_OK_UPDATE_RETURNING:
2446 case SPI_OK_DELETE_RETURNING:
2447 Assert(stmt->mod_stmt);
2448 exec_set_found(estate, (SPI_processed != 0));
2451 case SPI_OK_SELINTO:
2452 case SPI_OK_UTILITY:
2453 Assert(!stmt->mod_stmt);
2457 elog(ERROR, "SPI_execute_plan failed executing query \"%s\": %s",
2458 expr->query, SPI_result_code_string(rc));
2461 /* All variants should save result info for GET DIAGNOSTICS */
2462 estate->eval_processed = SPI_processed;
2463 estate->eval_lastoid = SPI_lastoid;
2465 /* Process INTO if present */
2468 SPITupleTable *tuptab = SPI_tuptable;
2469 uint32 n = SPI_processed;
2470 PLpgSQL_rec *rec = NULL;
2471 PLpgSQL_row *row = NULL;
2473 /* If the statement did not return a tuple table, complain */
2476 (errcode(ERRCODE_SYNTAX_ERROR),
2477 errmsg("INTO used with a command that cannot return data")));
2479 /* Determine if we assign to a record or a row */
2480 if (stmt->rec != NULL)
2481 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
2482 else if (stmt->row != NULL)
2483 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
2485 elog(ERROR, "unsupported target");
2488 * If SELECT ... INTO specified STRICT, and the query didn't find
2489 * exactly one row, throw an error. If STRICT was not specified, then
2490 * allow the query to find any number of rows.
2496 (errcode(ERRCODE_NO_DATA_FOUND),
2497 errmsg("query returned no rows")));
2498 /* set the target to NULL(s) */
2499 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
2503 if (n > 1 && (stmt->strict || stmt->mod_stmt))
2505 (errcode(ERRCODE_TOO_MANY_ROWS),
2506 errmsg("query returned more than one row")));
2507 /* Put the first result row into the target */
2508 exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
2512 SPI_freetuptable(SPI_tuptable);
2516 /* If the statement returned a tuple table, complain */
2517 if (SPI_tuptable != NULL)
2519 (errcode(ERRCODE_SYNTAX_ERROR),
2520 errmsg("query has no destination for result data"),
2521 (rc == SPI_OK_SELECT) ? errhint("If you want to discard the results of a SELECT, use PERFORM instead.") : 0));
2527 return PLPGSQL_RC_OK;
2532 * exec_stmt_dynexecute Execute a dynamic SQL query
2533 * (possibly with INTO).
2537 exec_stmt_dynexecute(PLpgSQL_execstate *estate,
2538 PLpgSQL_stmt_dynexecute *stmt)
2541 bool isnull = false;
2547 * First we evaluate the string expression after the EXECUTE keyword. Its
2548 * result is the querystring we have to execute.
2550 query = exec_eval_expr(estate, stmt->query, &isnull, &restype);
2553 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2554 errmsg("cannot EXECUTE a null querystring")));
2556 /* Get the C-String representation */
2557 querystr = convert_value_to_string(query, restype);
2559 exec_eval_cleanup(estate);
2562 * Call SPI_execute() without preparing a saved plan.
2564 exec_res = SPI_execute(querystr, estate->readonly_func, 0);
2572 case SPI_OK_INSERT_RETURNING:
2573 case SPI_OK_UPDATE_RETURNING:
2574 case SPI_OK_DELETE_RETURNING:
2575 case SPI_OK_UTILITY:
2581 * Also allow a zero return, which implies the querystring
2582 * contained no commands.
2586 case SPI_OK_SELINTO:
2589 * We want to disallow SELECT INTO for now, because its behavior
2590 * is not consistent with SELECT INTO in a normal plpgsql context.
2591 * (We need to reimplement EXECUTE to parse the string as a
2592 * plpgsql command, not just feed it to SPI_execute.) However,
2593 * CREATE AS should be allowed ... and since it produces the same
2594 * parsetree as SELECT INTO, there's no way to tell the difference
2595 * except to look at the source text. Wotta kluge!
2600 for (ptr = querystr; *ptr; ptr++)
2601 if (!scanner_isspace(*ptr))
2603 if (*ptr == 'S' || *ptr == 's')
2605 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2606 errmsg("EXECUTE of SELECT ... INTO is not implemented yet")));
2610 /* Some SPI errors deserve specific error messages */
2611 case SPI_ERROR_COPY:
2613 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2614 errmsg("cannot COPY to/from client in PL/pgSQL")));
2615 case SPI_ERROR_CURSOR:
2617 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2618 errmsg("cannot manipulate cursors directly in PL/pgSQL"),
2619 errhint("Use PL/pgSQL's cursor features instead.")));
2620 case SPI_ERROR_TRANSACTION:
2622 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2623 errmsg("cannot begin/end transactions in PL/pgSQL"),
2624 errhint("Use a BEGIN block with an EXCEPTION clause instead.")));
2627 elog(ERROR, "SPI_execute failed executing query \"%s\": %s",
2628 querystr, SPI_result_code_string(exec_res));
2632 /* Save result info for GET DIAGNOSTICS */
2633 estate->eval_processed = SPI_processed;
2634 estate->eval_lastoid = SPI_lastoid;
2636 /* Process INTO if present */
2639 SPITupleTable *tuptab = SPI_tuptable;
2640 uint32 n = SPI_processed;
2641 PLpgSQL_rec *rec = NULL;
2642 PLpgSQL_row *row = NULL;
2644 /* If the statement did not return a tuple table, complain */
2647 (errcode(ERRCODE_SYNTAX_ERROR),
2648 errmsg("INTO used with a command that cannot return data")));
2650 /* Determine if we assign to a record or a row */
2651 if (stmt->rec != NULL)
2652 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
2653 else if (stmt->row != NULL)
2654 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
2656 elog(ERROR, "unsupported target");
2659 * If SELECT ... INTO specified STRICT, and the query didn't find
2660 * exactly one row, throw an error. If STRICT was not specified, then
2661 * allow the query to find any number of rows.
2667 (errcode(ERRCODE_NO_DATA_FOUND),
2668 errmsg("query returned no rows")));
2669 /* set the target to NULL(s) */
2670 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
2674 if (n > 1 && stmt->strict)
2676 (errcode(ERRCODE_TOO_MANY_ROWS),
2677 errmsg("query returned more than one row")));
2678 /* Put the first result row into the target */
2679 exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
2685 * It might be a good idea to raise an error if the query returned
2686 * tuples that are being ignored, but historically we have not done
2691 /* Release any result from SPI_execute, as well as the querystring */
2692 SPI_freetuptable(SPI_tuptable);
2695 return PLPGSQL_RC_OK;
2700 * exec_stmt_dynfors Execute a dynamic query, assign each
2701 * tuple to a record or row and
2702 * execute a group of statements
2707 exec_stmt_dynfors(PLpgSQL_execstate *estate, PLpgSQL_stmt_dynfors *stmt)
2713 PLpgSQL_rec *rec = NULL;
2714 PLpgSQL_row *row = NULL;
2715 SPITupleTable *tuptab;
2722 * Determine if we assign to a record or a row
2724 if (stmt->rec != NULL)
2725 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
2726 else if (stmt->row != NULL)
2727 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
2729 elog(ERROR, "unsupported target");
2732 * Evaluate the string expression after the EXECUTE keyword. It's result
2733 * is the querystring we have to execute.
2735 query = exec_eval_expr(estate, stmt->query, &isnull, &restype);
2738 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2739 errmsg("cannot EXECUTE a null querystring")));
2741 /* Get the C-String representation */
2742 querystr = convert_value_to_string(query, restype);
2744 exec_eval_cleanup(estate);
2747 * Prepare a plan and open an implicit cursor for the query
2749 plan = SPI_prepare(querystr, 0, NULL);
2751 elog(ERROR, "SPI_prepare failed for \"%s\": %s",
2752 querystr, SPI_result_code_string(SPI_result));
2753 portal = SPI_cursor_open(NULL, plan, NULL, NULL,
2754 estate->readonly_func);
2756 elog(ERROR, "could not open implicit cursor for query \"%s\": %s",
2757 querystr, SPI_result_code_string(SPI_result));
2762 * Fetch the initial 10 tuples
2764 SPI_cursor_fetch(portal, true, 10);
2765 tuptab = SPI_tuptable;
2769 * If the query didn't return any rows, set the target to NULL and return
2770 * with FOUND = false.
2773 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
2775 found = true; /* processed at least one tuple */
2784 for (i = 0; i < n; i++)
2789 * Assign the tuple to the target
2791 exec_move_row(estate, rec, row, tuptab->vals[i], tuptab->tupdesc);
2794 * Execute the statements
2796 rc = exec_stmts(estate, stmt->body);
2798 if (rc != PLPGSQL_RC_OK)
2800 if (rc == PLPGSQL_RC_EXIT)
2802 if (estate->exitlabel == NULL)
2803 /* unlabelled exit, finish the current loop */
2805 else if (stmt->label != NULL &&
2806 strcmp(stmt->label, estate->exitlabel) == 0)
2808 /* labelled exit, matches the current stmt's label */
2809 estate->exitlabel = NULL;
2814 * otherwise, we processed a labelled exit that does not
2815 * match the current statement's label, if any: return
2816 * RC_EXIT so that the EXIT continues to recurse upward.
2819 else if (rc == PLPGSQL_RC_CONTINUE)
2821 if (estate->exitlabel == NULL)
2822 /* unlabelled continue, continue the current loop */
2824 else if (stmt->label != NULL &&
2825 strcmp(stmt->label, estate->exitlabel) == 0)
2827 /* labelled continue, matches the current stmt's label */
2828 estate->exitlabel = NULL;
2833 * otherwise, we process a labelled continue that does not
2834 * match the current statement's label, so propagate
2835 * RC_CONTINUE upward in the stack.
2840 * We're aborting the loop, so cleanup and set FOUND. (This
2841 * code should match the code after the loop.)
2843 SPI_freetuptable(tuptab);
2844 SPI_cursor_close(portal);
2845 exec_set_found(estate, found);
2851 SPI_freetuptable(tuptab);
2854 * Fetch the next 50 tuples
2856 SPI_cursor_fetch(portal, true, 50);
2858 tuptab = SPI_tuptable;
2862 * Release last group of tuples
2864 SPI_freetuptable(tuptab);
2867 * Close the implicit cursor
2869 SPI_cursor_close(portal);
2872 * Set the FOUND variable to indicate the result of executing the loop
2873 * (namely, whether we looped one or more times). This must be set here so
2874 * that it does not interfere with the value of the FOUND variable inside
2875 * the loop processing itself.
2877 exec_set_found(estate, found);
2879 return PLPGSQL_RC_OK;
2884 * exec_stmt_open Execute an OPEN cursor statement
2888 exec_stmt_open(PLpgSQL_execstate *estate, PLpgSQL_stmt_open *stmt)
2890 PLpgSQL_var *curvar = NULL;
2891 char *curname = NULL;
2892 PLpgSQL_expr *query = NULL;
2901 * Get the cursor variable and if it has an assigned name, check
2902 * that it's not in use currently.
2905 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
2906 if (!curvar->isnull)
2908 curname = DatumGetCString(DirectFunctionCall1(textout, curvar->value));
2909 if (SPI_cursor_find(curname) != NULL)
2911 (errcode(ERRCODE_DUPLICATE_CURSOR),
2912 errmsg("cursor \"%s\" already in use", curname)));
2916 * Process the OPEN according to it's type.
2919 if (stmt->query != NULL)
2922 * This is an OPEN refcursor FOR SELECT ...
2924 * We just make sure the query is planned. The real work is
2928 query = stmt->query;
2929 if (query->plan == NULL)
2930 exec_prepare_plan(estate, query);
2932 else if (stmt->dynquery != NULL)
2935 * This is an OPEN refcursor FOR EXECUTE ...
2944 * We evaluate the string expression after the
2945 * EXECUTE keyword. It's result is the querystring we have
2949 queryD = exec_eval_expr(estate, stmt->dynquery, &isnull, &restype);
2952 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2953 errmsg("cannot EXECUTE a null querystring")));
2955 /* Get the C-String representation */
2956 querystr = convert_value_to_string(queryD, restype);
2958 exec_eval_cleanup(estate);
2961 * Now we prepare a query plan for it and open a cursor
2964 curplan = SPI_prepare(querystr, 0, NULL);
2965 if (curplan == NULL)
2966 elog(ERROR, "SPI_prepare failed for \"%s\": %s",
2967 querystr, SPI_result_code_string(SPI_result));
2968 portal = SPI_cursor_open(curname, curplan, NULL, NULL,
2969 estate->readonly_func);
2971 elog(ERROR, "could not open cursor for query \"%s\": %s",
2972 querystr, SPI_result_code_string(SPI_result));
2974 SPI_freeplan(curplan);
2977 * Store the eventually assigned cursor name in the cursor variable
2981 curvar->value = DirectFunctionCall1(textin, CStringGetDatum(portal->name));
2982 curvar->isnull = false;
2983 curvar->freeval = true;
2985 return PLPGSQL_RC_OK;
2990 * This is an OPEN cursor
2992 * Note: parser should already have checked that statement supplies
2993 * args iff cursor needs them, but we check again to be safe.
2996 if (stmt->argquery != NULL)
2999 * OPEN CURSOR with args. We fake a SELECT ... INTO ...
3000 * statement to evaluate the args and put 'em into the
3004 PLpgSQL_stmt_execsql set_args;
3006 if (curvar->cursor_explicit_argrow < 0)
3008 (errcode(ERRCODE_SYNTAX_ERROR),
3009 errmsg("arguments given for cursor without arguments")));
3011 memset(&set_args, 0, sizeof(set_args));
3012 set_args.cmd_type = PLPGSQL_STMT_EXECSQL;
3013 set_args.lineno = stmt->lineno;
3014 set_args.sqlstmt = stmt->argquery;
3015 set_args.into = true;
3016 /* XXX historically this has not been STRICT */
3017 set_args.row = (PLpgSQL_row *)
3018 (estate->datums[curvar->cursor_explicit_argrow]);
3020 if (exec_stmt_execsql(estate, &set_args) != PLPGSQL_RC_OK)
3021 elog(ERROR, "open cursor failed during argument processing");
3025 if (curvar->cursor_explicit_argrow >= 0)
3027 (errcode(ERRCODE_SYNTAX_ERROR),
3028 errmsg("arguments required for cursor")));
3031 query = curvar->cursor_explicit_expr;
3032 if (query->plan == NULL)
3033 exec_prepare_plan(estate, query);
3037 * Here we go if we have a saved plan where we have to put
3038 * values into, either from an explicit cursor or from a
3039 * refcursor opened with OPEN ... FOR SELECT ...;
3042 values = (Datum *) palloc(query->nparams * sizeof(Datum));
3043 nulls = (char *) palloc(query->nparams * sizeof(char));
3045 for (i = 0; i < query->nparams; i++)
3047 PLpgSQL_datum *datum = estate->datums[query->params[i]];
3051 exec_eval_datum(estate, datum, query->plan_argtypes[i],
3052 ¶mtypeid, &values[i], ¶misnull);
3063 portal = SPI_cursor_open(curname, query->plan, values, nulls,
3064 estate->readonly_func);
3066 elog(ERROR, "could not open cursor: %s",
3067 SPI_result_code_string(SPI_result));
3075 * Store the eventually assigned portal name in the cursor variable
3079 curvar->value = DirectFunctionCall1(textin, CStringGetDatum(portal->name));
3080 curvar->isnull = false;
3081 curvar->freeval = true;
3083 return PLPGSQL_RC_OK;
3088 * exec_stmt_fetch Fetch from a cursor into a target
3092 exec_stmt_fetch(PLpgSQL_execstate *estate, PLpgSQL_stmt_fetch *stmt)
3094 PLpgSQL_var *curvar = NULL;
3095 PLpgSQL_rec *rec = NULL;
3096 PLpgSQL_row *row = NULL;
3097 SPITupleTable *tuptab;
3103 * Get the portal of the cursor by name
3106 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
3109 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3110 errmsg("cursor variable \"%s\" is NULL", curvar->refname)));
3111 curname = DatumGetCString(DirectFunctionCall1(textout, curvar->value));
3113 portal = SPI_cursor_find(curname);
3116 (errcode(ERRCODE_UNDEFINED_CURSOR),
3117 errmsg("cursor \"%s\" does not exist", curname)));
3121 * Determine if we fetch into a record or a row
3124 if (stmt->rec != NULL)
3125 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
3126 else if (stmt->row != NULL)
3127 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
3129 elog(ERROR, "unsupported target");
3132 * Fetch 1 tuple from the cursor
3135 SPI_cursor_fetch(portal, true, 1);
3136 tuptab = SPI_tuptable;
3140 * Set the target and the global FOUND variable appropriately.
3145 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
3146 exec_set_found(estate, false);
3150 exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
3151 exec_set_found(estate, true);
3154 SPI_freetuptable(tuptab);
3156 return PLPGSQL_RC_OK;
3161 * exec_stmt_close Close a cursor
3165 exec_stmt_close(PLpgSQL_execstate *estate, PLpgSQL_stmt_close *stmt)
3167 PLpgSQL_var *curvar = NULL;
3172 * Get the portal of the cursor by name
3175 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
3178 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3179 errmsg("cursor variable \"%s\" is NULL", curvar->refname)));
3180 curname = DatumGetCString(DirectFunctionCall1(textout, curvar->value));
3182 portal = SPI_cursor_find(curname);
3185 (errcode(ERRCODE_UNDEFINED_CURSOR),
3186 errmsg("cursor \"%s\" does not exist", curname)));
3193 SPI_cursor_close(portal);
3195 return PLPGSQL_RC_OK;
3200 * exec_assign_expr Put an expression's result into
3205 exec_assign_expr(PLpgSQL_execstate *estate, PLpgSQL_datum *target,
3210 bool isnull = false;
3212 value = exec_eval_expr(estate, expr, &isnull, &valtype);
3213 exec_assign_value(estate, target, value, valtype, &isnull);
3214 exec_eval_cleanup(estate);
3219 * exec_assign_value Put a value into a target field
3223 exec_assign_value(PLpgSQL_execstate *estate,
3224 PLpgSQL_datum *target,
3225 Datum value, Oid valtype, bool *isNull)
3227 switch (target->dtype)
3229 case PLPGSQL_DTYPE_VAR:
3232 * Target is a variable
3234 PLpgSQL_var *var = (PLpgSQL_var *) target;
3237 newvalue = exec_cast_value(value, valtype, var->datatype->typoid,
3238 &(var->datatype->typinput),
3239 var->datatype->typioparam,
3240 var->datatype->atttypmod,
3243 if (*isNull && var->notnull)
3245 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3246 errmsg("NULL cannot be assigned to variable \"%s\" declared NOT NULL",
3250 * If type is by-reference, make sure we have a freshly
3251 * palloc'd copy; the originally passed value may not live as
3252 * long as the variable! But we don't need to re-copy if
3253 * exec_cast_value performed a conversion; its output must
3254 * already be palloc'd.
3256 if (!var->datatype->typbyval && !*isNull)
3258 if (newvalue == value)
3259 newvalue = datumCopy(newvalue,
3261 var->datatype->typlen);
3265 * Now free the old value. (We can't do this any earlier
3266 * because of the possibility that we are assigning the var's
3267 * old value to it, eg "foo := foo". We could optimize out
3268 * the assignment altogether in such cases, but it's too
3269 * infrequent to be worth testing for.)
3273 var->value = newvalue;
3274 var->isnull = *isNull;
3275 if (!var->datatype->typbyval && !*isNull)
3276 var->freeval = true;
3280 case PLPGSQL_DTYPE_ROW:
3283 * Target is a row variable
3285 PLpgSQL_row *row = (PLpgSQL_row *) target;
3287 /* Source must be of RECORD or composite type */
3288 if (!(valtype == RECORDOID ||
3289 get_typtype(valtype) == 'c'))
3291 (errcode(ERRCODE_DATATYPE_MISMATCH),
3292 errmsg("cannot assign non-composite value to a row variable")));
3295 /* If source is null, just assign nulls to the row */
3296 exec_move_row(estate, NULL, row, NULL, NULL);
3304 HeapTupleData tmptup;
3306 /* Else source is a tuple Datum, safe to do this: */
3307 td = DatumGetHeapTupleHeader(value);
3308 /* Extract rowtype info and find a tupdesc */
3309 tupType = HeapTupleHeaderGetTypeId(td);
3310 tupTypmod = HeapTupleHeaderGetTypMod(td);
3311 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
3312 /* Build a temporary HeapTuple control structure */
3313 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
3314 ItemPointerSetInvalid(&(tmptup.t_self));
3315 tmptup.t_tableOid = InvalidOid;
3317 exec_move_row(estate, NULL, row, &tmptup, tupdesc);
3318 ReleaseTupleDesc(tupdesc);
3323 case PLPGSQL_DTYPE_REC:
3326 * Target is a record variable
3328 PLpgSQL_rec *rec = (PLpgSQL_rec *) target;
3330 /* Source must be of RECORD or composite type */
3331 if (!(valtype == RECORDOID ||
3332 get_typtype(valtype) == 'c'))
3334 (errcode(ERRCODE_DATATYPE_MISMATCH),
3335 errmsg("cannot assign non-composite value to a record variable")));
3338 /* If source is null, just assign nulls to the record */
3339 exec_move_row(estate, rec, NULL, NULL, NULL);
3347 HeapTupleData tmptup;
3349 /* Else source is a tuple Datum, safe to do this: */
3350 td = DatumGetHeapTupleHeader(value);
3351 /* Extract rowtype info and find a tupdesc */
3352 tupType = HeapTupleHeaderGetTypeId(td);
3353 tupTypmod = HeapTupleHeaderGetTypMod(td);
3354 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
3355 /* Build a temporary HeapTuple control structure */
3356 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
3357 ItemPointerSetInvalid(&(tmptup.t_self));
3358 tmptup.t_tableOid = InvalidOid;
3360 exec_move_row(estate, rec, NULL, &tmptup, tupdesc);
3361 ReleaseTupleDesc(tupdesc);
3366 case PLPGSQL_DTYPE_RECFIELD:
3369 * Target is a field of a record
3371 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) target;
3384 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
3387 * Check that there is already a tuple in the record. We need
3388 * that because records don't have any predefined field
3391 if (!HeapTupleIsValid(rec->tup))
3393 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3394 errmsg("record \"%s\" is not assigned yet",
3396 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
3399 * Get the number of the records field to change and the
3400 * number of attributes in the tuple.
3402 fno = SPI_fnumber(rec->tupdesc, recfield->fieldname);
3403 if (fno == SPI_ERROR_NOATTRIBUTE)
3405 (errcode(ERRCODE_UNDEFINED_COLUMN),
3406 errmsg("record \"%s\" has no field \"%s\"",
3407 rec->refname, recfield->fieldname)));
3409 natts = rec->tupdesc->natts;
3412 * Set up values/datums arrays for heap_formtuple. For all
3413 * the attributes except the one we want to replace, use the
3414 * value that's in the old tuple.
3416 values = palloc(sizeof(Datum) * natts);
3417 nulls = palloc(natts);
3419 for (i = 0; i < natts; i++)
3423 values[i] = SPI_getbinval(rec->tup, rec->tupdesc,
3432 * Now insert the new value, being careful to cast it to the
3435 atttype = SPI_gettypeid(rec->tupdesc, fno + 1);
3436 atttypmod = rec->tupdesc->attrs[fno]->atttypmod;
3437 attisnull = *isNull;
3438 values[fno] = exec_simple_cast_value(value,
3449 * Avoid leaking the result of exec_simple_cast_value, if it
3450 * performed a conversion to a pass-by-ref type.
3452 if (!attisnull && values[fno] != value && !get_typbyval(atttype))
3453 mustfree = DatumGetPointer(values[fno]);
3458 * Now call heap_formtuple() to create a new tuple that
3459 * replaces the old one in the record.
3461 newtup = heap_formtuple(rec->tupdesc, values, nulls);
3464 heap_freetuple(rec->tup);
3467 rec->freetup = true;
3477 case PLPGSQL_DTYPE_ARRAYELEM:
3481 PLpgSQL_expr *subscripts[MAXDIM];
3482 int subscriptvals[MAXDIM];
3483 bool oldarrayisnull;
3490 Datum oldarraydatum,
3492 ArrayType *oldarrayval;
3493 ArrayType *newarrayval;
3496 * Target is an element of an array
3498 * To handle constructs like x[1][2] := something, we have to
3499 * be prepared to deal with a chain of arrayelem datums. Chase
3500 * back to find the base array datum, and save the subscript
3501 * expressions as we go. (We are scanning right to left here,
3502 * but want to evaluate the subscripts left-to-right to
3503 * minimize surprises.)
3508 PLpgSQL_arrayelem *arrayelem = (PLpgSQL_arrayelem *) target;
3510 if (nsubscripts >= MAXDIM)
3512 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
3513 errmsg("number of array dimensions exceeds the maximum allowed, %d",
3515 subscripts[nsubscripts++] = arrayelem->subscript;
3516 target = estate->datums[arrayelem->arrayparentno];
3517 } while (target->dtype == PLPGSQL_DTYPE_ARRAYELEM);
3519 /* Fetch current value of array datum */
3520 exec_eval_datum(estate, target, InvalidOid,
3521 &arraytypeid, &oldarraydatum, &oldarrayisnull);
3523 arrayelemtypeid = get_element_type(arraytypeid);
3524 if (!OidIsValid(arrayelemtypeid))
3526 (errcode(ERRCODE_DATATYPE_MISMATCH),
3527 errmsg("subscripted object is not an array")));
3529 get_typlenbyvalalign(arrayelemtypeid,
3533 arraytyplen = get_typlen(arraytypeid);
3536 * Evaluate the subscripts, switch into left-to-right order.
3537 * Like ExecEvalArrayRef(), complain if any subscript is null.
3539 for (i = 0; i < nsubscripts; i++)
3544 exec_eval_integer(estate,
3545 subscripts[nsubscripts - 1 - i],
3549 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3550 errmsg("array subscript in assignment must not be NULL")));
3553 /* Coerce source value to match array element type. */
3554 coerced_value = exec_simple_cast_value(value,
3561 * If the original array is null, cons up an empty array so
3562 * that the assignment can proceed; we'll end with a
3563 * one-element array containing just the assigned-to
3564 * subscript. This only works for varlena arrays, though; for
3565 * fixed-length array types we skip the assignment. We can't
3566 * support assignment of a null entry into a fixed-length
3567 * array, either, so that's a no-op too. This is all ugly but
3568 * corresponds to the current behavior of ExecEvalArrayRef().
3570 if (arraytyplen > 0 && /* fixed-length array? */
3571 (oldarrayisnull || *isNull))
3575 oldarrayval = construct_empty_array(arrayelemtypeid);
3577 oldarrayval = (ArrayType *) DatumGetPointer(oldarraydatum);
3580 * Build the modified array value.
3582 newarrayval = array_set(oldarrayval,
3593 * Avoid leaking the result of exec_simple_cast_value, if it
3594 * performed a conversion to a pass-by-ref type.
3596 if (!*isNull && coerced_value != value && !elemtypbyval)
3597 pfree(DatumGetPointer(coerced_value));
3600 * Assign the new array to the base variable. It's never NULL
3604 exec_assign_value(estate, target,
3605 PointerGetDatum(newarrayval),
3606 arraytypeid, isNull);
3609 * Avoid leaking the modified array value, too.
3616 elog(ERROR, "unrecognized dtype: %d", target->dtype);
3621 * exec_eval_datum Get current value of a PLpgSQL_datum
3623 * The type oid, value in Datum format, and null flag are returned.
3625 * If expectedtypeid isn't InvalidOid, it is checked against the actual type.
3627 * At present this doesn't handle PLpgSQL_expr or PLpgSQL_arrayelem datums.
3629 * NOTE: caller must not modify the returned value, since it points right
3630 * at the stored value in the case of pass-by-reference datatypes. In some
3631 * cases we have to palloc a return value, and in such cases we put it into
3632 * the estate's short-term memory context.
3635 exec_eval_datum(PLpgSQL_execstate *estate,
3636 PLpgSQL_datum *datum,
3642 MemoryContext oldcontext;
3644 switch (datum->dtype)
3646 case PLPGSQL_DTYPE_VAR:
3648 PLpgSQL_var *var = (PLpgSQL_var *) datum;
3650 *typeid = var->datatype->typoid;
3651 *value = var->value;
3652 *isnull = var->isnull;
3653 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3655 (errcode(ERRCODE_DATATYPE_MISMATCH),
3656 errmsg("type of \"%s\" does not match that when preparing the plan",
3661 case PLPGSQL_DTYPE_ROW:
3663 PLpgSQL_row *row = (PLpgSQL_row *) datum;
3666 if (!row->rowtupdesc) /* should not happen */
3667 elog(ERROR, "row variable has no tupdesc");
3668 /* Make sure we have a valid type/typmod setting */
3669 BlessTupleDesc(row->rowtupdesc);
3670 oldcontext = MemoryContextSwitchTo(estate->eval_econtext->ecxt_per_tuple_memory);
3671 tup = make_tuple_from_row(estate, row, row->rowtupdesc);
3672 if (tup == NULL) /* should not happen */
3673 elog(ERROR, "row not compatible with its own tupdesc");
3674 MemoryContextSwitchTo(oldcontext);
3675 *typeid = row->rowtupdesc->tdtypeid;
3676 *value = HeapTupleGetDatum(tup);
3678 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3680 (errcode(ERRCODE_DATATYPE_MISMATCH),
3681 errmsg("type of \"%s\" does not match that when preparing the plan",
3686 case PLPGSQL_DTYPE_REC:
3688 PLpgSQL_rec *rec = (PLpgSQL_rec *) datum;
3689 HeapTupleData worktup;
3691 if (!HeapTupleIsValid(rec->tup))
3693 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3694 errmsg("record \"%s\" is not assigned yet",
3696 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
3697 Assert(rec->tupdesc != NULL);
3698 /* Make sure we have a valid type/typmod setting */
3699 BlessTupleDesc(rec->tupdesc);
3702 * In a trigger, the NEW and OLD parameters are likely to be
3703 * on-disk tuples that don't have the desired Datum fields.
3704 * Copy the tuple body and insert the right values.
3706 oldcontext = MemoryContextSwitchTo(estate->eval_econtext->ecxt_per_tuple_memory);
3707 heap_copytuple_with_tuple(rec->tup, &worktup);
3708 HeapTupleHeaderSetDatumLength(worktup.t_data, worktup.t_len);
3709 HeapTupleHeaderSetTypeId(worktup.t_data, rec->tupdesc->tdtypeid);
3710 HeapTupleHeaderSetTypMod(worktup.t_data, rec->tupdesc->tdtypmod);
3711 MemoryContextSwitchTo(oldcontext);
3712 *typeid = rec->tupdesc->tdtypeid;
3713 *value = HeapTupleGetDatum(&worktup);
3715 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3717 (errcode(ERRCODE_DATATYPE_MISMATCH),
3718 errmsg("type of \"%s\" does not match that when preparing the plan",
3723 case PLPGSQL_DTYPE_RECFIELD:
3725 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) datum;
3729 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
3730 if (!HeapTupleIsValid(rec->tup))
3732 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3733 errmsg("record \"%s\" is not assigned yet",
3735 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
3736 fno = SPI_fnumber(rec->tupdesc, recfield->fieldname);
3737 if (fno == SPI_ERROR_NOATTRIBUTE)
3739 (errcode(ERRCODE_UNDEFINED_COLUMN),
3740 errmsg("record \"%s\" has no field \"%s\"",
3741 rec->refname, recfield->fieldname)));
3742 *typeid = SPI_gettypeid(rec->tupdesc, fno);
3743 *value = SPI_getbinval(rec->tup, rec->tupdesc, fno, isnull);
3744 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3746 (errcode(ERRCODE_DATATYPE_MISMATCH),
3747 errmsg("type of \"%s.%s\" does not match that when preparing the plan",
3748 rec->refname, recfield->fieldname)));
3752 case PLPGSQL_DTYPE_TRIGARG:
3754 PLpgSQL_trigarg *trigarg = (PLpgSQL_trigarg *) datum;
3758 tgargno = exec_eval_integer(estate, trigarg->argnum, isnull);
3759 if (*isnull || tgargno < 0 || tgargno >= estate->trig_nargs)
3766 *value = estate->trig_argv[tgargno];
3769 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3771 (errcode(ERRCODE_DATATYPE_MISMATCH),
3772 errmsg("type of tgargv[%d] does not match that when preparing the plan",
3778 elog(ERROR, "unrecognized dtype: %d", datum->dtype);
3783 * exec_eval_integer Evaluate an expression, coerce result to int4
3785 * Note we do not do exec_eval_cleanup here; the caller must do it at
3786 * some later point. (We do this because the caller may be holding the
3787 * results of other, pass-by-reference, expression evaluations, such as
3788 * an array value to be subscripted. Also see notes in exec_eval_simple_expr
3789 * about allocation of the parameter array.)
3793 exec_eval_integer(PLpgSQL_execstate *estate,
3800 exprdatum = exec_eval_expr(estate, expr, isNull, &exprtypeid);
3801 exprdatum = exec_simple_cast_value(exprdatum, exprtypeid,
3804 return DatumGetInt32(exprdatum);
3808 * exec_eval_boolean Evaluate an expression, coerce result to bool
3810 * Note we do not do exec_eval_cleanup here; the caller must do it at
3815 exec_eval_boolean(PLpgSQL_execstate *estate,
3822 exprdatum = exec_eval_expr(estate, expr, isNull, &exprtypeid);
3823 exprdatum = exec_simple_cast_value(exprdatum, exprtypeid,
3826 return DatumGetBool(exprdatum);
3830 * exec_eval_expr Evaluate an expression and return
3833 * NOTE: caller must do exec_eval_cleanup when done with the Datum.
3837 exec_eval_expr(PLpgSQL_execstate *estate,
3845 * If not already done create a plan for this expression
3847 if (expr->plan == NULL)
3848 exec_prepare_plan(estate, expr);
3851 * If this is a simple expression, bypass SPI and use the executor
3854 if (expr->expr_simple_expr != NULL)
3855 return exec_eval_simple_expr(estate, expr, isNull, rettype);
3857 rc = exec_run_select(estate, expr, 2, NULL);
3858 if (rc != SPI_OK_SELECT)
3860 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3861 errmsg("query \"%s\" did not return data", expr->query)));
3864 * If there are no rows selected, the result is NULL.
3866 if (estate->eval_processed == 0)
3873 * Check that the expression returned one single Datum
3875 if (estate->eval_processed > 1)
3877 (errcode(ERRCODE_CARDINALITY_VIOLATION),
3878 errmsg("query \"%s\" returned more than one row",
3880 if (estate->eval_tuptable->tupdesc->natts != 1)
3882 (errcode(ERRCODE_SYNTAX_ERROR),
3883 errmsg("query \"%s\" returned %d columns", expr->query,
3884 estate->eval_tuptable->tupdesc->natts)));
3887 * Return the result and its type
3889 *rettype = SPI_gettypeid(estate->eval_tuptable->tupdesc, 1);
3890 return SPI_getbinval(estate->eval_tuptable->vals[0],
3891 estate->eval_tuptable->tupdesc, 1, isNull);
3896 * exec_run_select Execute a select query
3900 exec_run_select(PLpgSQL_execstate *estate,
3901 PLpgSQL_expr *expr, long maxtuples, Portal *portalP)
3909 * On the first call for this expression generate the plan
3911 if (expr->plan == NULL)
3912 exec_prepare_plan(estate, expr);
3915 * Now build up the values and nulls arguments for SPI_execute_plan()
3917 values = (Datum *) palloc(expr->nparams * sizeof(Datum));
3918 nulls = (char *) palloc(expr->nparams * sizeof(char));
3920 for (i = 0; i < expr->nparams; i++)
3922 PLpgSQL_datum *datum = estate->datums[expr->params[i]];
3926 exec_eval_datum(estate, datum, expr->plan_argtypes[i],
3927 ¶mtypeid, &values[i], ¶misnull);
3935 * If a portal was requested, put the query into the portal
3937 if (portalP != NULL)
3939 *portalP = SPI_cursor_open(NULL, expr->plan, values, nulls,
3940 estate->readonly_func);
3941 if (*portalP == NULL)
3942 elog(ERROR, "could not open implicit cursor for query \"%s\": %s",
3943 expr->query, SPI_result_code_string(SPI_result));
3946 return SPI_OK_CURSOR;
3952 rc = SPI_execute_plan(expr->plan, values, nulls,
3953 estate->readonly_func, maxtuples);
3954 if (rc != SPI_OK_SELECT)
3956 (errcode(ERRCODE_SYNTAX_ERROR),
3957 errmsg("query \"%s\" is not a SELECT", expr->query)));
3959 /* Save query results for eventual cleanup */
3960 Assert(estate->eval_tuptable == NULL);
3961 estate->eval_tuptable = SPI_tuptable;
3962 estate->eval_processed = SPI_processed;
3963 estate->eval_lastoid = SPI_lastoid;
3973 * exec_eval_simple_expr - Evaluate a simple expression returning
3974 * a Datum by directly calling ExecEvalExpr().
3976 * Note: if pass-by-reference, the result is in the eval_econtext's
3977 * temporary memory context. It will be freed when exec_eval_cleanup
3982 exec_eval_simple_expr(PLpgSQL_execstate *estate,
3988 ExprContext *econtext = estate->eval_econtext;
3989 ParamListInfo paramLI;
3991 Snapshot saveActiveSnapshot;
3994 * Pass back previously-determined result type.
3996 *rettype = expr->expr_simple_type;
3999 * Prepare the expression for execution, if it's not been done already in
4000 * the current eval_estate.
4002 if (expr->expr_simple_id != estate->eval_estate_simple_id)
4004 expr->expr_simple_state = ExecPrepareExpr(expr->expr_simple_expr,
4005 estate->eval_estate);
4006 expr->expr_simple_id = estate->eval_estate_simple_id;
4010 * Param list can live in econtext's temporary memory context.
4012 * XXX think about avoiding repeated palloc's for param lists? Beware
4013 * however that this routine is re-entrant: exec_eval_datum() can call it
4014 * back for subscript evaluation, and so there can be a need to have more
4015 * than one active param list.
4017 if (expr->nparams > 0)
4019 /* sizeof(ParamListInfoData) includes the first array element */
4020 paramLI = (ParamListInfo)
4021 MemoryContextAlloc(econtext->ecxt_per_tuple_memory,
4022 sizeof(ParamListInfoData) +
4023 (expr->nparams - 1) *sizeof(ParamExternData));
4024 paramLI->numParams = expr->nparams;
4026 for (i = 0; i < expr->nparams; i++)
4028 ParamExternData *prm = ¶mLI->params[i];
4029 PLpgSQL_datum *datum = estate->datums[expr->params[i]];
4032 exec_eval_datum(estate, datum, expr->plan_argtypes[i],
4034 &prm->value, &prm->isnull);
4041 * Now we can safely make the econtext point to the param list.
4043 econtext->ecxt_param_list_info = paramLI;
4046 * We have to do some of the things SPI_execute_plan would do, in
4047 * particular advance the snapshot if we are in a non-read-only function.
4048 * Without this, stable functions within the expression would fail to see
4049 * updates made so far by our own function.
4052 saveActiveSnapshot = ActiveSnapshot;
4056 MemoryContext oldcontext;
4058 oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
4059 if (!estate->readonly_func)
4061 CommandCounterIncrement();
4062 ActiveSnapshot = CopySnapshot(GetTransactionSnapshot());
4066 * Finally we can call the executor to evaluate the expression
4068 retval = ExecEvalExpr(expr->expr_simple_state,
4072 MemoryContextSwitchTo(oldcontext);
4076 /* Restore global vars and propagate error */
4077 ActiveSnapshot = saveActiveSnapshot;
4082 ActiveSnapshot = saveActiveSnapshot;
4093 * exec_move_row Move one tuple's values into a record or row
4097 exec_move_row(PLpgSQL_execstate *estate,
4100 HeapTuple tup, TupleDesc tupdesc)
4103 * Record is simple - just copy the tuple and its descriptor into the
4109 * copy input first, just in case it is pointing at variable's value
4111 if (HeapTupleIsValid(tup))
4112 tup = heap_copytuple(tup);
4114 tupdesc = CreateTupleDescCopy(tupdesc);
4118 heap_freetuple(rec->tup);
4119 rec->freetup = false;
4121 if (rec->freetupdesc)
4123 FreeTupleDesc(rec->tupdesc);
4124 rec->freetupdesc = false;
4127 if (HeapTupleIsValid(tup))
4130 rec->freetup = true;
4134 /* If we have a tupdesc but no data, form an all-nulls tuple */
4137 nulls = (char *) palloc(tupdesc->natts * sizeof(char));
4138 memset(nulls, 'n', tupdesc->natts * sizeof(char));
4140 rec->tup = heap_formtuple(tupdesc, NULL, nulls);
4141 rec->freetup = true;
4150 rec->tupdesc = tupdesc;
4151 rec->freetupdesc = true;
4154 rec->tupdesc = NULL;
4160 * Row is a bit more complicated in that we assign the individual
4161 * attributes of the tuple to the variables the row points to.
4163 * NOTE: this code used to demand row->nfields == HeapTupleHeaderGetNatts(tup->t_data,
4164 * but that's wrong. The tuple might have more fields than we expected if
4165 * it's from an inheritance-child table of the current table, or it might
4166 * have fewer if the table has had columns added by ALTER TABLE. Ignore
4167 * extra columns and assume NULL for missing columns, the same as
4168 * heap_getattr would do. We also have to skip over dropped columns in
4169 * either the source or destination.
4171 * If we have no tuple data at all, we'll assign NULL to all columns of
4180 if (HeapTupleIsValid(tup))
4181 t_natts = HeapTupleHeaderGetNatts(tup->t_data);
4186 for (fnum = 0; fnum < row->nfields; fnum++)
4193 if (row->varnos[fnum] < 0)
4194 continue; /* skip dropped column in row struct */
4196 var = (PLpgSQL_var *) (estate->datums[row->varnos[fnum]]);
4198 while (anum < t_natts && tupdesc->attrs[anum]->attisdropped)
4199 anum++; /* skip dropped column in tuple */
4203 value = SPI_getbinval(tup, tupdesc, anum + 1, &isnull);
4204 valtype = SPI_gettypeid(tupdesc, anum + 1);
4211 valtype = InvalidOid;
4214 exec_assign_value(estate, (PLpgSQL_datum *) var,
4215 value, valtype, &isnull);
4221 elog(ERROR, "unsupported target");
4225 * make_tuple_from_row Make a tuple from the values of a row object
4227 * A NULL return indicates rowtype mismatch; caller must raise suitable error
4231 make_tuple_from_row(PLpgSQL_execstate *estate,
4235 int natts = tupdesc->natts;
4241 if (natts != row->nfields)
4244 dvalues = (Datum *) palloc0(natts * sizeof(Datum));
4245 nulls = (bool *) palloc(natts * sizeof(bool));
4247 for (i = 0; i < natts; i++)
4251 if (tupdesc->attrs[i]->attisdropped)
4253 nulls[i] = true; /* leave the column as null */
4256 if (row->varnos[i] < 0) /* should not happen */
4257 elog(ERROR, "dropped rowtype entry for non-dropped column");
4259 exec_eval_datum(estate, estate->datums[row->varnos[i]],
4260 InvalidOid, &fieldtypeid, &dvalues[i], &nulls[i]);
4261 if (fieldtypeid != tupdesc->attrs[i]->atttypid)
4265 tuple = heap_form_tuple(tupdesc, dvalues, nulls);
4274 * convert_value_to_string Convert a non-null Datum to C string
4276 * Note: callers generally assume that the result is a palloc'd string and
4277 * should be pfree'd. This is not all that safe an assumption ...
4279 * Note: not caching the conversion function lookup is bad for performance.
4283 convert_value_to_string(Datum value, Oid valtype)
4289 getTypeOutputInfo(valtype, &typoutput, &typIsVarlena);
4292 * We do SPI_push to allow the datatype output function to use SPI.
4293 * However we do not mess around with CommandCounterIncrement or advancing
4294 * the snapshot, which means that a stable output function would not see
4295 * updates made so far by our own function. The use-case for such
4296 * scenarios seems too narrow to justify the cycles that would be
4301 str = OidOutputFunctionCall(typoutput, value);
4309 * exec_cast_value Cast a value if required
4313 exec_cast_value(Datum value, Oid valtype,
4321 * If the type of the queries return value isn't that of the variable,
4324 if (valtype != reqtype || reqtypmod != -1)
4330 extval = convert_value_to_string(value, valtype);
4332 /* Allow input function to use SPI ... see notes above */
4335 value = InputFunctionCall(reqinput, extval,
4336 reqtypioparam, reqtypmod);
4346 value = InputFunctionCall(reqinput, NULL,
4347 reqtypioparam, reqtypmod);
4357 * exec_simple_cast_value Cast a value if required
4359 * As above, but need not supply details about target type. Note that this
4360 * is slower than exec_cast_value with cached type info, and so should be
4361 * avoided in heavily used code paths.
4365 exec_simple_cast_value(Datum value, Oid valtype,
4366 Oid reqtype, int32 reqtypmod,
4371 if (valtype != reqtype || reqtypmod != -1)
4375 FmgrInfo finfo_input;
4377 getTypeInputInfo(reqtype, &typinput, &typioparam);
4379 fmgr_info(typinput, &finfo_input);
4381 value = exec_cast_value(value,
4396 * exec_simple_check_node - Recursively check if an expression
4397 * is made only of simple things we can
4398 * hand out directly to ExecEvalExpr()
4399 * instead of calling SPI.
4403 exec_simple_check_node(Node *node)
4408 switch (nodeTag(node))
4418 ArrayRef *expr = (ArrayRef *) node;
4420 if (!exec_simple_check_node((Node *) expr->refupperindexpr))
4422 if (!exec_simple_check_node((Node *) expr->reflowerindexpr))
4424 if (!exec_simple_check_node((Node *) expr->refexpr))
4426 if (!exec_simple_check_node((Node *) expr->refassgnexpr))
4434 FuncExpr *expr = (FuncExpr *) node;
4436 if (expr->funcretset)
4438 if (!exec_simple_check_node((Node *) expr->args))
4446 OpExpr *expr = (OpExpr *) node;
4450 if (!exec_simple_check_node((Node *) expr->args))
4456 case T_DistinctExpr:
4458 DistinctExpr *expr = (DistinctExpr *) node;
4462 if (!exec_simple_check_node((Node *) expr->args))
4468 case T_ScalarArrayOpExpr:
4470 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
4472 if (!exec_simple_check_node((Node *) expr->args))
4480 BoolExpr *expr = (BoolExpr *) node;
4482 if (!exec_simple_check_node((Node *) expr->args))
4489 return exec_simple_check_node((Node *) ((FieldSelect *) node)->arg);
4493 FieldStore *expr = (FieldStore *) node;
4495 if (!exec_simple_check_node((Node *) expr->arg))
4497 if (!exec_simple_check_node((Node *) expr->newvals))
4504 return exec_simple_check_node((Node *) ((RelabelType *) node)->arg);
4506 case T_ConvertRowtypeExpr:
4507 return exec_simple_check_node((Node *) ((ConvertRowtypeExpr *) node)->arg);
4511 CaseExpr *expr = (CaseExpr *) node;
4513 if (!exec_simple_check_node((Node *) expr->arg))
4515 if (!exec_simple_check_node((Node *) expr->args))
4517 if (!exec_simple_check_node((Node *) expr->defresult))
4525 CaseWhen *when = (CaseWhen *) node;
4527 if (!exec_simple_check_node((Node *) when->expr))
4529 if (!exec_simple_check_node((Node *) when->result))
4535 case T_CaseTestExpr:
4540 ArrayExpr *expr = (ArrayExpr *) node;
4542 if (!exec_simple_check_node((Node *) expr->elements))
4550 RowExpr *expr = (RowExpr *) node;
4552 if (!exec_simple_check_node((Node *) expr->args))
4558 case T_RowCompareExpr:
4560 RowCompareExpr *expr = (RowCompareExpr *) node;
4562 if (!exec_simple_check_node((Node *) expr->largs))
4564 if (!exec_simple_check_node((Node *) expr->rargs))
4570 case T_CoalesceExpr:
4572 CoalesceExpr *expr = (CoalesceExpr *) node;
4574 if (!exec_simple_check_node((Node *) expr->args))
4582 MinMaxExpr *expr = (MinMaxExpr *) node;
4584 if (!exec_simple_check_node((Node *) expr->args))
4592 XmlExpr *expr = (XmlExpr *) node;
4594 if (!exec_simple_check_node((Node *) expr->named_args))
4596 if (!exec_simple_check_node((Node *) expr->args))
4604 NullIfExpr *expr = (NullIfExpr *) node;
4608 if (!exec_simple_check_node((Node *) expr->args))
4615 return exec_simple_check_node((Node *) ((NullTest *) node)->arg);
4618 return exec_simple_check_node((Node *) ((BooleanTest *) node)->arg);
4620 case T_CoerceToDomain:
4621 return exec_simple_check_node((Node *) ((CoerceToDomain *) node)->arg);
4623 case T_CoerceToDomainValue:
4628 List *expr = (List *) node;
4633 if (!exec_simple_check_node(lfirst(l)))
4647 * exec_simple_check_plan - Check if a plan is simple enough to
4648 * be evaluated by ExecEvalExpr() instead
4653 exec_simple_check_plan(PLpgSQL_expr *expr)
4655 _SPI_plan *spi_plan = (_SPI_plan *) expr->plan;
4659 expr->expr_simple_expr = NULL;
4662 * 1. We can only evaluate queries that resulted in one single execution
4665 if (list_length(spi_plan->ptlist) != 1)
4668 plan = (Plan *) linitial(spi_plan->ptlist);
4671 * 2. It must be a RESULT plan --> no scan's required
4673 if (plan == NULL) /* utility statement produces this */
4676 if (!IsA(plan, Result))
4680 * 3. Can't have any subplan or qual clause, either
4682 if (plan->lefttree != NULL ||
4683 plan->righttree != NULL ||
4684 plan->initPlan != NULL ||
4685 plan->qual != NULL ||
4686 ((Result *) plan)->resconstantqual != NULL)
4690 * 4. The plan must have a single attribute as result
4692 if (list_length(plan->targetlist) != 1)
4695 tle = (TargetEntry *) linitial(plan->targetlist);
4698 * 5. Check that all the nodes in the expression are non-scary.
4700 if (!exec_simple_check_node((Node *) tle->expr))
4704 * Yes - this is a simple expression. Mark it as such, and initialize
4705 * state to "not valid in current transaction".
4707 expr->expr_simple_expr = tle->expr;
4708 expr->expr_simple_state = NULL;
4709 expr->expr_simple_id = -1;
4710 /* Also stash away the expression result type */
4711 expr->expr_simple_type = exprType((Node *) tle->expr);
4715 * Check two tupledescs have matching number and types of attributes
4718 compatible_tupdesc(TupleDesc td1, TupleDesc td2)
4722 if (td1->natts != td2->natts)
4725 for (i = 0; i < td1->natts; i++)
4727 if (td1->attrs[i]->atttypid != td2->attrs[i]->atttypid)
4735 * exec_set_found Set the global found variable
4740 exec_set_found(PLpgSQL_execstate *estate, bool state)
4744 var = (PLpgSQL_var *) (estate->datums[estate->found_varno]);
4745 var->value = (Datum) state;
4746 var->isnull = false;
4750 * plpgsql_create_econtext --- create an eval_econtext for the current function
4752 * We may need to create a new eval_estate too, if there's not one already
4753 * for the current (sub) transaction. The EState will be cleaned up at
4754 * (sub) transaction end.
4757 plpgsql_create_econtext(PLpgSQL_execstate *estate)
4759 SubTransactionId my_subxid = GetCurrentSubTransactionId();
4760 SimpleEstateStackEntry *entry = simple_estate_stack;
4762 /* Create new EState if not one for current subxact */
4763 if (entry == NULL ||
4764 entry->xact_subxid != my_subxid)
4766 MemoryContext oldcontext;
4768 /* Stack entries are kept in TopTransactionContext for simplicity */
4769 entry = (SimpleEstateStackEntry *)
4770 MemoryContextAlloc(TopTransactionContext,
4771 sizeof(SimpleEstateStackEntry));
4773 /* But each EState should be a child of its CurTransactionContext */
4774 oldcontext = MemoryContextSwitchTo(CurTransactionContext);
4775 entry->xact_eval_estate = CreateExecutorState();
4776 MemoryContextSwitchTo(oldcontext);
4778 /* Assign a reasonably-unique ID to this EState */
4779 entry->xact_estate_simple_id = simple_estate_id_counter++;
4780 entry->xact_subxid = my_subxid;
4782 entry->next = simple_estate_stack;
4783 simple_estate_stack = entry;
4786 /* Link plpgsql estate to it */
4787 estate->eval_estate = entry->xact_eval_estate;
4788 estate->eval_estate_simple_id = entry->xact_estate_simple_id;
4790 /* And create a child econtext for the current function */
4791 estate->eval_econtext = CreateExprContext(estate->eval_estate);
4795 * plpgsql_xact_cb --- post-transaction-commit-or-abort cleanup
4797 * If a simple-expression EState was created in the current transaction,
4798 * it has to be cleaned up.
4801 plpgsql_xact_cb(XactEvent event, void *arg)
4804 * If we are doing a clean transaction shutdown, free the EState (so that
4805 * any remaining resources will be released correctly). In an abort, we
4806 * expect the regular abort recovery procedures to release everything of
4807 * interest. We don't need to free the individual stack entries since
4808 * TopTransactionContext is about to go away anyway.
4810 * Note: if plpgsql_subxact_cb is doing its job, there should be at most
4811 * one stack entry, but we may as well code this as a loop.
4813 if (event != XACT_EVENT_ABORT)
4815 while (simple_estate_stack != NULL)
4817 FreeExecutorState(simple_estate_stack->xact_eval_estate);
4818 simple_estate_stack = simple_estate_stack->next;
4822 simple_estate_stack = NULL;
4826 * plpgsql_subxact_cb --- post-subtransaction-commit-or-abort cleanup
4828 * If a simple-expression EState was created in the current subtransaction,
4829 * it has to be cleaned up.
4832 plpgsql_subxact_cb(SubXactEvent event, SubTransactionId mySubid,
4833 SubTransactionId parentSubid, void *arg)
4835 if (event == SUBXACT_EVENT_START_SUB)
4838 if (simple_estate_stack != NULL &&
4839 simple_estate_stack->xact_subxid == mySubid)
4841 SimpleEstateStackEntry *next;
4843 if (event == SUBXACT_EVENT_COMMIT_SUB)
4844 FreeExecutorState(simple_estate_stack->xact_eval_estate);
4845 next = simple_estate_stack->next;
4846 pfree(simple_estate_stack);
4847 simple_estate_stack = next;
4852 free_var(PLpgSQL_var *var)
4856 pfree(DatumGetPointer(var->value));
4857 var->freeval = false;