1 /*-------------------------------------------------------------------------
3 * pl_exec.c - Executor for the PL/pgSQL
6 * Portions Copyright (c) 1996-2006, 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.179 2006/09/22 21:39:58 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";
42 * All plpgsql function executions within a single transaction share
43 * the same executor EState for evaluating "simple" expressions. Each
44 * function call creates its own "eval_econtext" ExprContext within this
45 * estate. We destroy the estate at transaction shutdown to ensure there
46 * is no permanent leakage of memory (especially for xact abort case).
48 static EState *simple_eval_estate = NULL;
50 /************************************************************
51 * Local function forward declarations
52 ************************************************************/
53 static void plpgsql_exec_error_callback(void *arg);
54 static PLpgSQL_datum *copy_plpgsql_datum(PLpgSQL_datum *datum);
56 static int exec_stmt_block(PLpgSQL_execstate *estate,
57 PLpgSQL_stmt_block *block);
58 static int exec_stmts(PLpgSQL_execstate *estate,
60 static int exec_stmt(PLpgSQL_execstate *estate,
62 static int exec_stmt_assign(PLpgSQL_execstate *estate,
63 PLpgSQL_stmt_assign *stmt);
64 static int exec_stmt_perform(PLpgSQL_execstate *estate,
65 PLpgSQL_stmt_perform *stmt);
66 static int exec_stmt_getdiag(PLpgSQL_execstate *estate,
67 PLpgSQL_stmt_getdiag *stmt);
68 static int exec_stmt_if(PLpgSQL_execstate *estate,
69 PLpgSQL_stmt_if *stmt);
70 static int exec_stmt_loop(PLpgSQL_execstate *estate,
71 PLpgSQL_stmt_loop *stmt);
72 static int exec_stmt_while(PLpgSQL_execstate *estate,
73 PLpgSQL_stmt_while *stmt);
74 static int exec_stmt_fori(PLpgSQL_execstate *estate,
75 PLpgSQL_stmt_fori *stmt);
76 static int exec_stmt_fors(PLpgSQL_execstate *estate,
77 PLpgSQL_stmt_fors *stmt);
78 static int exec_stmt_open(PLpgSQL_execstate *estate,
79 PLpgSQL_stmt_open *stmt);
80 static int exec_stmt_fetch(PLpgSQL_execstate *estate,
81 PLpgSQL_stmt_fetch *stmt);
82 static int exec_stmt_close(PLpgSQL_execstate *estate,
83 PLpgSQL_stmt_close *stmt);
84 static int exec_stmt_exit(PLpgSQL_execstate *estate,
85 PLpgSQL_stmt_exit *stmt);
86 static int exec_stmt_return(PLpgSQL_execstate *estate,
87 PLpgSQL_stmt_return *stmt);
88 static int exec_stmt_return_next(PLpgSQL_execstate *estate,
89 PLpgSQL_stmt_return_next *stmt);
90 static int exec_stmt_raise(PLpgSQL_execstate *estate,
91 PLpgSQL_stmt_raise *stmt);
92 static int exec_stmt_execsql(PLpgSQL_execstate *estate,
93 PLpgSQL_stmt_execsql *stmt);
94 static int exec_stmt_dynexecute(PLpgSQL_execstate *estate,
95 PLpgSQL_stmt_dynexecute *stmt);
96 static int exec_stmt_dynfors(PLpgSQL_execstate *estate,
97 PLpgSQL_stmt_dynfors *stmt);
99 static void plpgsql_estate_setup(PLpgSQL_execstate *estate,
100 PLpgSQL_function *func,
102 static void exec_eval_cleanup(PLpgSQL_execstate *estate);
104 static void exec_prepare_plan(PLpgSQL_execstate *estate,
106 static bool exec_simple_check_node(Node *node);
107 static void exec_simple_check_plan(PLpgSQL_expr *expr);
108 static Datum exec_eval_simple_expr(PLpgSQL_execstate *estate,
113 static void exec_assign_expr(PLpgSQL_execstate *estate,
114 PLpgSQL_datum *target,
116 static void exec_assign_value(PLpgSQL_execstate *estate,
117 PLpgSQL_datum *target,
118 Datum value, Oid valtype, bool *isNull);
119 static void exec_eval_datum(PLpgSQL_execstate *estate,
120 PLpgSQL_datum *datum,
125 static int exec_eval_integer(PLpgSQL_execstate *estate,
128 static bool exec_eval_boolean(PLpgSQL_execstate *estate,
131 static Datum exec_eval_expr(PLpgSQL_execstate *estate,
135 static int exec_run_select(PLpgSQL_execstate *estate,
136 PLpgSQL_expr *expr, long maxtuples, Portal *portalP);
137 static void exec_move_row(PLpgSQL_execstate *estate,
140 HeapTuple tup, TupleDesc tupdesc);
141 static HeapTuple make_tuple_from_row(PLpgSQL_execstate *estate,
144 static char *convert_value_to_string(Datum value, Oid valtype);
145 static Datum exec_cast_value(Datum value, Oid valtype,
151 static Datum exec_simple_cast_value(Datum value, Oid valtype,
152 Oid reqtype, int32 reqtypmod,
154 static void exec_init_tuple_store(PLpgSQL_execstate *estate);
155 static bool compatible_tupdesc(TupleDesc td1, TupleDesc td2);
156 static void exec_set_found(PLpgSQL_execstate *estate, bool state);
157 static void free_var(PLpgSQL_var *var);
161 * plpgsql_exec_function Called by the call handler for
162 * function execution.
166 plpgsql_exec_function(PLpgSQL_function *func, FunctionCallInfo fcinfo)
168 PLpgSQL_execstate estate;
169 ErrorContextCallback plerrcontext;
174 * Setup the execution state
176 plpgsql_estate_setup(&estate, func, (ReturnSetInfo *) fcinfo->resultinfo);
179 * Setup error traceback support for ereport()
181 plerrcontext.callback = plpgsql_exec_error_callback;
182 plerrcontext.arg = &estate;
183 plerrcontext.previous = error_context_stack;
184 error_context_stack = &plerrcontext;
187 * Make local execution copies of all the datums
189 estate.err_text = gettext_noop("during initialization of execution state");
190 for (i = 0; i < estate.ndatums; i++)
191 estate.datums[i] = copy_plpgsql_datum(func->datums[i]);
194 * Store the actual call argument values into the appropriate variables
196 estate.err_text = gettext_noop("while storing call arguments into local variables");
197 for (i = 0; i < func->fn_nargs; i++)
199 int n = func->fn_argvarnos[i];
201 switch (estate.datums[n]->dtype)
203 case PLPGSQL_DTYPE_VAR:
205 PLpgSQL_var *var = (PLpgSQL_var *) estate.datums[n];
207 var->value = fcinfo->arg[i];
208 var->isnull = fcinfo->argnull[i];
209 var->freeval = false;
213 case PLPGSQL_DTYPE_ROW:
215 PLpgSQL_row *row = (PLpgSQL_row *) estate.datums[n];
217 if (!fcinfo->argnull[i])
223 HeapTupleData tmptup;
225 td = DatumGetHeapTupleHeader(fcinfo->arg[i]);
226 /* Extract rowtype info and find a tupdesc */
227 tupType = HeapTupleHeaderGetTypeId(td);
228 tupTypmod = HeapTupleHeaderGetTypMod(td);
229 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
230 /* Build a temporary HeapTuple control structure */
231 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
232 ItemPointerSetInvalid(&(tmptup.t_self));
233 tmptup.t_tableOid = InvalidOid;
235 exec_move_row(&estate, NULL, row, &tmptup, tupdesc);
236 ReleaseTupleDesc(tupdesc);
240 /* If arg is null, treat it as an empty row */
241 exec_move_row(&estate, NULL, row, NULL, NULL);
247 elog(ERROR, "unrecognized dtype: %d", func->datums[i]->dtype);
252 * Set the magic variable FOUND to false
254 exec_set_found(&estate, false);
257 * Let the instrumentation plugin peek at this function
259 if (*plugin_ptr && (*plugin_ptr)->func_beg)
260 ((*plugin_ptr)->func_beg)(&estate, func);
263 * Now call the toplevel block of statements
265 estate.err_text = NULL;
266 estate.err_stmt = (PLpgSQL_stmt *) (func->action);
267 rc = exec_stmt_block(&estate, func->action);
268 if (rc != PLPGSQL_RC_RETURN)
270 estate.err_stmt = NULL;
271 estate.err_text = NULL;
274 * Provide a more helpful message if a CONTINUE has been used outside
277 if (rc == PLPGSQL_RC_CONTINUE)
279 (errcode(ERRCODE_SYNTAX_ERROR),
280 errmsg("CONTINUE cannot be used outside a loop")));
283 (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
284 errmsg("control reached end of function without RETURN")));
288 * We got a return value - process it
290 estate.err_stmt = NULL;
291 estate.err_text = gettext_noop("while casting return value to function's return type");
293 fcinfo->isnull = estate.retisnull;
297 ReturnSetInfo *rsi = estate.rsi;
299 /* Check caller can handle a set result */
300 if (!rsi || !IsA(rsi, ReturnSetInfo) ||
301 (rsi->allowedModes & SFRM_Materialize) == 0)
303 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
304 errmsg("set-valued function called in context that cannot accept a set")));
305 rsi->returnMode = SFRM_Materialize;
307 /* If we produced any tuples, send back the result */
308 if (estate.tuple_store)
310 rsi->setResult = estate.tuple_store;
311 if (estate.rettupdesc)
313 MemoryContext oldcxt;
315 oldcxt = MemoryContextSwitchTo(estate.tuple_store_cxt);
316 rsi->setDesc = CreateTupleDescCopy(estate.rettupdesc);
317 MemoryContextSwitchTo(oldcxt);
320 estate.retval = (Datum) 0;
321 fcinfo->isnull = true;
323 else if (!estate.retisnull)
325 if (estate.retistuple)
328 * We have to check that the returned tuple actually matches
329 * the expected result type. XXX would be better to cache the
330 * tupdesc instead of repeating get_call_result_type()
334 switch (get_call_result_type(fcinfo, NULL, &tupdesc))
336 case TYPEFUNC_COMPOSITE:
337 /* got the expected result rowtype, now check it */
338 if (estate.rettupdesc == NULL ||
339 !compatible_tupdesc(estate.rettupdesc, tupdesc))
341 (errcode(ERRCODE_DATATYPE_MISMATCH),
342 errmsg("returned record type does not match expected record type")));
344 case TYPEFUNC_RECORD:
346 * Failed to determine actual type of RECORD. We could
347 * raise an error here, but what this means in practice
348 * is that the caller is expecting any old generic
349 * rowtype, so we don't really need to be restrictive.
350 * Pass back the generated result type, instead.
352 tupdesc = estate.rettupdesc;
353 if (tupdesc == NULL) /* shouldn't happen */
354 elog(ERROR, "return type must be a row type");
357 /* shouldn't get here if retistuple is true ... */
358 elog(ERROR, "return type must be a row type");
363 * Copy tuple to upper executor memory, as a tuple Datum.
364 * Make sure it is labeled with the caller-supplied tuple type.
367 PointerGetDatum(SPI_returntuple((HeapTuple) (estate.retval),
372 /* Cast value to proper type */
373 estate.retval = exec_cast_value(estate.retval, estate.rettype,
375 &(func->fn_retinput),
376 func->fn_rettypioparam,
381 * If the function's return type isn't by value, copy the value
382 * into upper executor memory context.
384 if (!fcinfo->isnull && !func->fn_retbyval)
389 len = datumGetSize(estate.retval, false, func->fn_rettyplen);
390 tmp = (void *) SPI_palloc(len);
391 memcpy(tmp, DatumGetPointer(estate.retval), len);
392 estate.retval = PointerGetDatum(tmp);
398 * Let the instrumentation plugin peek at this function
400 if (*plugin_ptr && (*plugin_ptr)->func_end)
401 ((*plugin_ptr)->func_end)(&estate, func);
403 /* Clean up any leftover temporary memory */
404 FreeExprContext(estate.eval_econtext);
405 estate.eval_econtext = NULL;
406 exec_eval_cleanup(&estate);
409 * Pop the error context stack
411 error_context_stack = plerrcontext.previous;
414 * Return the function's result
416 return estate.retval;
421 * plpgsql_exec_trigger Called by the call handler for
426 plpgsql_exec_trigger(PLpgSQL_function *func,
427 TriggerData *trigdata)
429 PLpgSQL_execstate estate;
430 ErrorContextCallback plerrcontext;
434 PLpgSQL_rec *rec_new,
439 * Setup the execution state
441 plpgsql_estate_setup(&estate, func, NULL);
444 * Setup error traceback support for ereport()
446 plerrcontext.callback = plpgsql_exec_error_callback;
447 plerrcontext.arg = &estate;
448 plerrcontext.previous = error_context_stack;
449 error_context_stack = &plerrcontext;
452 * Make local execution copies of all the datums
454 estate.err_text = gettext_noop("during initialization of execution state");
455 for (i = 0; i < estate.ndatums; i++)
456 estate.datums[i] = copy_plpgsql_datum(func->datums[i]);
459 * Put the OLD and NEW tuples into record variables
461 rec_new = (PLpgSQL_rec *) (estate.datums[func->new_varno]);
462 rec_new->freetup = false;
463 rec_new->freetupdesc = false;
464 rec_old = (PLpgSQL_rec *) (estate.datums[func->old_varno]);
465 rec_old->freetup = false;
466 rec_old->freetupdesc = false;
468 if (TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
471 * Per-statement triggers don't use OLD/NEW variables
474 rec_new->tupdesc = NULL;
476 rec_old->tupdesc = NULL;
478 else if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
480 rec_new->tup = trigdata->tg_trigtuple;
481 rec_new->tupdesc = trigdata->tg_relation->rd_att;
483 rec_old->tupdesc = NULL;
485 else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
487 rec_new->tup = trigdata->tg_newtuple;
488 rec_new->tupdesc = trigdata->tg_relation->rd_att;
489 rec_old->tup = trigdata->tg_trigtuple;
490 rec_old->tupdesc = trigdata->tg_relation->rd_att;
492 else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
495 rec_new->tupdesc = NULL;
496 rec_old->tup = trigdata->tg_trigtuple;
497 rec_old->tupdesc = trigdata->tg_relation->rd_att;
500 elog(ERROR, "unrecognized trigger action: not INSERT, DELETE, or UPDATE");
503 * Assign the special tg_ variables
506 var = (PLpgSQL_var *) (estate.datums[func->tg_op_varno]);
507 if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
508 var->value = DirectFunctionCall1(textin, CStringGetDatum("INSERT"));
509 else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
510 var->value = DirectFunctionCall1(textin, CStringGetDatum("UPDATE"));
511 else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
512 var->value = DirectFunctionCall1(textin, CStringGetDatum("DELETE"));
514 elog(ERROR, "unrecognized trigger action: not INSERT, DELETE, or UPDATE");
518 var = (PLpgSQL_var *) (estate.datums[func->tg_name_varno]);
519 var->value = DirectFunctionCall1(namein,
520 CStringGetDatum(trigdata->tg_trigger->tgname));
524 var = (PLpgSQL_var *) (estate.datums[func->tg_when_varno]);
525 if (TRIGGER_FIRED_BEFORE(trigdata->tg_event))
526 var->value = DirectFunctionCall1(textin, CStringGetDatum("BEFORE"));
527 else if (TRIGGER_FIRED_AFTER(trigdata->tg_event))
528 var->value = DirectFunctionCall1(textin, CStringGetDatum("AFTER"));
530 elog(ERROR, "unrecognized trigger execution time: not BEFORE or AFTER");
534 var = (PLpgSQL_var *) (estate.datums[func->tg_level_varno]);
535 if (TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
536 var->value = DirectFunctionCall1(textin, CStringGetDatum("ROW"));
537 else if (TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
538 var->value = DirectFunctionCall1(textin, CStringGetDatum("STATEMENT"));
540 elog(ERROR, "unrecognized trigger event type: not ROW or STATEMENT");
544 var = (PLpgSQL_var *) (estate.datums[func->tg_relid_varno]);
545 var->value = ObjectIdGetDatum(trigdata->tg_relation->rd_id);
547 var->freeval = false;
549 var = (PLpgSQL_var *) (estate.datums[func->tg_relname_varno]);
550 var->value = DirectFunctionCall1(namein,
551 CStringGetDatum(RelationGetRelationName(trigdata->tg_relation)));
555 var = (PLpgSQL_var *) (estate.datums[func->tg_table_name_varno]);
556 var->value = DirectFunctionCall1(namein,
557 CStringGetDatum(RelationGetRelationName(trigdata->tg_relation)));
561 var = (PLpgSQL_var *) (estate.datums[func->tg_table_schema_varno]);
562 var->value = DirectFunctionCall1(namein,
565 RelationGetNamespace(
566 trigdata->tg_relation))));
570 var = (PLpgSQL_var *) (estate.datums[func->tg_nargs_varno]);
571 var->value = Int16GetDatum(trigdata->tg_trigger->tgnargs);
573 var->freeval = false;
576 * Store the trigger argument values into the special execution state
579 estate.err_text = gettext_noop("while storing call arguments into local variables");
580 estate.trig_nargs = trigdata->tg_trigger->tgnargs;
581 if (estate.trig_nargs == 0)
582 estate.trig_argv = NULL;
585 estate.trig_argv = palloc(sizeof(Datum) * estate.trig_nargs);
586 for (i = 0; i < trigdata->tg_trigger->tgnargs; i++)
587 estate.trig_argv[i] = DirectFunctionCall1(textin,
588 CStringGetDatum(trigdata->tg_trigger->tgargs[i]));
592 * Set the magic variable FOUND to false
594 exec_set_found(&estate, false);
597 * Let the instrumentation plugin peek at this function
599 if (*plugin_ptr && (*plugin_ptr)->func_beg)
600 ((*plugin_ptr)->func_beg)(&estate, func);
603 * Now call the toplevel block of statements
605 estate.err_text = NULL;
606 estate.err_stmt = (PLpgSQL_stmt *) (func->action);
607 rc = exec_stmt_block(&estate, func->action);
608 if (rc != PLPGSQL_RC_RETURN)
610 estate.err_stmt = NULL;
611 estate.err_text = NULL;
614 * Provide a more helpful message if a CONTINUE has been used outside
617 if (rc == PLPGSQL_RC_CONTINUE)
619 (errcode(ERRCODE_SYNTAX_ERROR),
620 errmsg("CONTINUE cannot be used outside a loop")));
623 (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
624 errmsg("control reached end of trigger procedure without RETURN")));
629 (errcode(ERRCODE_DATATYPE_MISMATCH),
630 errmsg("trigger procedure cannot return a set")));
633 * Check that the returned tuple structure has the same attributes, the
634 * relation that fired the trigger has. A per-statement trigger always
635 * needs to return NULL, so we ignore any return value the function itself
636 * produces (XXX: is this a good idea?)
638 * XXX This way it is possible, that the trigger returns a tuple where
639 * attributes don't have the correct atttypmod's length. It's up to the
640 * trigger's programmer to ensure that this doesn't happen. Jan
642 if (estate.retisnull || TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
646 if (!compatible_tupdesc(estate.rettupdesc,
647 trigdata->tg_relation->rd_att))
649 (errcode(ERRCODE_DATATYPE_MISMATCH),
650 errmsg("returned tuple structure does not match table of trigger event")));
651 /* Copy tuple to upper executor memory */
652 rettup = SPI_copytuple((HeapTuple) (estate.retval));
656 * Let the instrumentation plugin peek at this function
658 if (*plugin_ptr && (*plugin_ptr)->func_end)
659 ((*plugin_ptr)->func_end)(&estate, func);
661 /* Clean up any leftover temporary memory */
662 FreeExprContext(estate.eval_econtext);
663 estate.eval_econtext = NULL;
664 exec_eval_cleanup(&estate);
667 * Pop the error context stack
669 error_context_stack = plerrcontext.previous;
672 * Return the trigger's result
679 * error context callback to let us supply a call-stack traceback
682 plpgsql_exec_error_callback(void *arg)
684 PLpgSQL_execstate *estate = (PLpgSQL_execstate *) arg;
686 /* safety check, shouldn't happen */
687 if (estate->err_func == NULL)
690 /* if we are doing RAISE, don't report its location */
691 if (estate->err_text == raise_skip_msg)
694 if (estate->err_stmt != NULL)
696 /* translator: last %s is a plpgsql statement type name */
697 errcontext("PL/pgSQL function \"%s\" line %d at %s",
698 estate->err_func->fn_name,
699 estate->err_stmt->lineno,
700 plpgsql_stmt_typename(estate->err_stmt));
702 else if (estate->err_text != NULL)
705 * We don't expend the cycles to run gettext() on err_text unless we
706 * actually need it. Therefore, places that set up err_text should
707 * use gettext_noop() to ensure the strings get recorded in the
708 * message dictionary.
712 * translator: last %s is a phrase such as "while storing call
713 * arguments into local variables"
715 errcontext("PL/pgSQL function \"%s\" %s",
716 estate->err_func->fn_name,
717 gettext(estate->err_text));
720 errcontext("PL/pgSQL function \"%s\"",
721 estate->err_func->fn_name);
726 * Support function for initializing local execution variables
729 static PLpgSQL_datum *
730 copy_plpgsql_datum(PLpgSQL_datum *datum)
732 PLpgSQL_datum *result;
734 switch (datum->dtype)
736 case PLPGSQL_DTYPE_VAR:
738 PLpgSQL_var *new = palloc(sizeof(PLpgSQL_var));
740 memcpy(new, datum, sizeof(PLpgSQL_var));
741 /* Ensure the value is null (possibly not needed?) */
744 new->freeval = false;
746 result = (PLpgSQL_datum *) new;
750 case PLPGSQL_DTYPE_REC:
752 PLpgSQL_rec *new = palloc(sizeof(PLpgSQL_rec));
754 memcpy(new, datum, sizeof(PLpgSQL_rec));
755 /* Ensure the value is null (possibly not needed?) */
758 new->freetup = false;
759 new->freetupdesc = false;
761 result = (PLpgSQL_datum *) new;
765 case PLPGSQL_DTYPE_ROW:
766 case PLPGSQL_DTYPE_RECFIELD:
767 case PLPGSQL_DTYPE_ARRAYELEM:
768 case PLPGSQL_DTYPE_TRIGARG:
771 * These datum records are read-only at runtime, so no need to
778 elog(ERROR, "unrecognized dtype: %d", datum->dtype);
779 result = NULL; /* keep compiler quiet */
788 exception_matches_conditions(ErrorData *edata, PLpgSQL_condition *cond)
790 for (; cond != NULL; cond = cond->next)
792 int sqlerrstate = cond->sqlerrstate;
795 * OTHERS matches everything *except* query-canceled; if you're
796 * foolish enough, you can match that explicitly.
798 if (sqlerrstate == 0)
800 if (edata->sqlerrcode != ERRCODE_QUERY_CANCELED)
804 else if (edata->sqlerrcode == sqlerrstate)
806 /* Category match? */
807 else if (ERRCODE_IS_CATEGORY(sqlerrstate) &&
808 ERRCODE_TO_CATEGORY(edata->sqlerrcode) == sqlerrstate)
816 * exec_stmt_block Execute a block of statements
820 exec_stmt_block(PLpgSQL_execstate *estate, PLpgSQL_stmt_block *block)
822 volatile int rc = -1;
827 * First initialize all variables declared in this block
829 for (i = 0; i < block->n_initvars; i++)
831 n = block->initvarnos[i];
833 switch (estate->datums[n]->dtype)
835 case PLPGSQL_DTYPE_VAR:
837 PLpgSQL_var *var = (PLpgSQL_var *) (estate->datums[n]);
840 if (!var->isconst || var->isnull)
842 if (var->default_val == NULL)
844 var->value = (Datum) 0;
848 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
849 errmsg("variable \"%s\" declared NOT NULL cannot default to NULL",
854 exec_assign_expr(estate, (PLpgSQL_datum *) var,
861 case PLPGSQL_DTYPE_REC:
863 PLpgSQL_rec *rec = (PLpgSQL_rec *) (estate->datums[n]);
867 heap_freetuple(rec->tup);
868 FreeTupleDesc(rec->tupdesc);
869 rec->freetup = false;
877 case PLPGSQL_DTYPE_RECFIELD:
878 case PLPGSQL_DTYPE_ARRAYELEM:
882 elog(ERROR, "unrecognized dtype: %d",
883 estate->datums[n]->dtype);
887 if (block->exceptions)
890 * Execute the statements in the block's body inside a sub-transaction
892 MemoryContext oldcontext = CurrentMemoryContext;
893 ResourceOwner oldowner = CurrentResourceOwner;
895 BeginInternalSubTransaction(NULL);
896 /* Want to run statements inside function's memory context */
897 MemoryContextSwitchTo(oldcontext);
901 rc = exec_stmts(estate, block->body);
903 /* Commit the inner transaction, return to outer xact context */
904 ReleaseCurrentSubTransaction();
905 MemoryContextSwitchTo(oldcontext);
906 CurrentResourceOwner = oldowner;
909 * AtEOSubXact_SPI() should not have popped any SPI context, but
910 * just in case it did, make sure we remain connected.
912 SPI_restore_connection();
919 /* Save error info */
920 MemoryContextSwitchTo(oldcontext);
921 edata = CopyErrorData();
924 /* Abort the inner transaction */
925 RollbackAndReleaseCurrentSubTransaction();
926 MemoryContextSwitchTo(oldcontext);
927 CurrentResourceOwner = oldowner;
930 * If AtEOSubXact_SPI() popped any SPI context of the subxact, it
931 * will have left us in a disconnected state. We need this hack
932 * to return to connected state.
934 SPI_restore_connection();
936 /* Look for a matching exception handler */
937 foreach(e, block->exceptions->exc_list)
939 PLpgSQL_exception *exception = (PLpgSQL_exception *) lfirst(e);
941 if (exception_matches_conditions(edata, exception->conditions))
944 * Initialize the magic SQLSTATE and SQLERRM variables for
945 * the exception block. We needn't do this until we have
946 * found a matching exception.
948 PLpgSQL_var *state_var;
949 PLpgSQL_var *errm_var;
951 state_var = (PLpgSQL_var *)
952 estate->datums[block->exceptions->sqlstate_varno];
953 state_var->value = DirectFunctionCall1(textin,
954 CStringGetDatum(unpack_sql_state(edata->sqlerrcode)));
955 state_var->freeval = true;
956 state_var->isnull = false;
958 errm_var = (PLpgSQL_var *)
959 estate->datums[block->exceptions->sqlerrm_varno];
960 errm_var->value = DirectFunctionCall1(textin,
961 CStringGetDatum(edata->message));
962 errm_var->freeval = true;
963 errm_var->isnull = false;
965 rc = exec_stmts(estate, exception->action);
973 /* If no match found, re-throw the error */
977 FreeErrorData(edata);
984 * Just execute the statements in the block's body
986 rc = exec_stmts(estate, block->body);
990 * Handle the return code.
995 case PLPGSQL_RC_CONTINUE:
996 case PLPGSQL_RC_RETURN:
999 case PLPGSQL_RC_EXIT:
1000 if (estate->exitlabel == NULL)
1001 return PLPGSQL_RC_OK;
1002 if (block->label == NULL)
1003 return PLPGSQL_RC_EXIT;
1004 if (strcmp(block->label, estate->exitlabel))
1005 return PLPGSQL_RC_EXIT;
1006 estate->exitlabel = NULL;
1007 return PLPGSQL_RC_OK;
1010 elog(ERROR, "unrecognized rc: %d", rc);
1013 return PLPGSQL_RC_OK;
1018 * exec_stmts Iterate over a list of statements
1019 * as long as their return code is OK
1023 exec_stmts(PLpgSQL_execstate *estate, List *stmts)
1030 * Ensure we do a CHECK_FOR_INTERRUPTS() even though there is no
1031 * statement. This prevents hangup in a tight loop if, for instance,
1032 * there is a LOOP construct with an empty body.
1034 CHECK_FOR_INTERRUPTS();
1035 return PLPGSQL_RC_OK;
1040 PLpgSQL_stmt *stmt = (PLpgSQL_stmt *) lfirst(s);
1041 int rc = exec_stmt(estate, stmt);
1043 if (rc != PLPGSQL_RC_OK)
1047 return PLPGSQL_RC_OK;
1052 * exec_stmt Distribute one statement to the statements
1053 * type specific execution function.
1057 exec_stmt(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
1059 PLpgSQL_stmt *save_estmt;
1062 save_estmt = estate->err_stmt;
1063 estate->err_stmt = stmt;
1065 /* Let the plugin know that we are about to execute this statement */
1066 if (*plugin_ptr && (*plugin_ptr)->stmt_beg)
1067 ((*plugin_ptr)->stmt_beg)(estate, stmt);
1069 CHECK_FOR_INTERRUPTS();
1071 switch (stmt->cmd_type)
1073 case PLPGSQL_STMT_BLOCK:
1074 rc = exec_stmt_block(estate, (PLpgSQL_stmt_block *) stmt);
1077 case PLPGSQL_STMT_ASSIGN:
1078 rc = exec_stmt_assign(estate, (PLpgSQL_stmt_assign *) stmt);
1081 case PLPGSQL_STMT_PERFORM:
1082 rc = exec_stmt_perform(estate, (PLpgSQL_stmt_perform *) stmt);
1085 case PLPGSQL_STMT_GETDIAG:
1086 rc = exec_stmt_getdiag(estate, (PLpgSQL_stmt_getdiag *) stmt);
1089 case PLPGSQL_STMT_IF:
1090 rc = exec_stmt_if(estate, (PLpgSQL_stmt_if *) stmt);
1093 case PLPGSQL_STMT_LOOP:
1094 rc = exec_stmt_loop(estate, (PLpgSQL_stmt_loop *) stmt);
1097 case PLPGSQL_STMT_WHILE:
1098 rc = exec_stmt_while(estate, (PLpgSQL_stmt_while *) stmt);
1101 case PLPGSQL_STMT_FORI:
1102 rc = exec_stmt_fori(estate, (PLpgSQL_stmt_fori *) stmt);
1105 case PLPGSQL_STMT_FORS:
1106 rc = exec_stmt_fors(estate, (PLpgSQL_stmt_fors *) stmt);
1109 case PLPGSQL_STMT_EXIT:
1110 rc = exec_stmt_exit(estate, (PLpgSQL_stmt_exit *) stmt);
1113 case PLPGSQL_STMT_RETURN:
1114 rc = exec_stmt_return(estate, (PLpgSQL_stmt_return *) stmt);
1117 case PLPGSQL_STMT_RETURN_NEXT:
1118 rc = exec_stmt_return_next(estate, (PLpgSQL_stmt_return_next *) stmt);
1121 case PLPGSQL_STMT_RAISE:
1122 rc = exec_stmt_raise(estate, (PLpgSQL_stmt_raise *) stmt);
1125 case PLPGSQL_STMT_EXECSQL:
1126 rc = exec_stmt_execsql(estate, (PLpgSQL_stmt_execsql *) stmt);
1129 case PLPGSQL_STMT_DYNEXECUTE:
1130 rc = exec_stmt_dynexecute(estate, (PLpgSQL_stmt_dynexecute *) stmt);
1133 case PLPGSQL_STMT_DYNFORS:
1134 rc = exec_stmt_dynfors(estate, (PLpgSQL_stmt_dynfors *) stmt);
1137 case PLPGSQL_STMT_OPEN:
1138 rc = exec_stmt_open(estate, (PLpgSQL_stmt_open *) stmt);
1141 case PLPGSQL_STMT_FETCH:
1142 rc = exec_stmt_fetch(estate, (PLpgSQL_stmt_fetch *) stmt);
1145 case PLPGSQL_STMT_CLOSE:
1146 rc = exec_stmt_close(estate, (PLpgSQL_stmt_close *) stmt);
1150 estate->err_stmt = save_estmt;
1151 elog(ERROR, "unrecognized cmdtype: %d", stmt->cmd_type);
1154 /* Let the plugin know that we have finished executing this statement */
1155 if (*plugin_ptr && (*plugin_ptr)->stmt_end)
1156 ((*plugin_ptr)->stmt_end)(estate, stmt);
1158 estate->err_stmt = save_estmt;
1165 * exec_stmt_assign Evaluate an expression and
1166 * put the result into a variable.
1170 exec_stmt_assign(PLpgSQL_execstate *estate, PLpgSQL_stmt_assign *stmt)
1172 Assert(stmt->varno >= 0);
1174 exec_assign_expr(estate, estate->datums[stmt->varno], stmt->expr);
1176 return PLPGSQL_RC_OK;
1180 * exec_stmt_perform Evaluate query and discard result (but set
1181 * FOUND depending on whether at least one row
1186 exec_stmt_perform(PLpgSQL_execstate *estate, PLpgSQL_stmt_perform *stmt)
1188 PLpgSQL_expr *expr = stmt->expr;
1190 (void) exec_run_select(estate, expr, 0, NULL);
1191 exec_set_found(estate, (estate->eval_processed != 0));
1192 exec_eval_cleanup(estate);
1194 return PLPGSQL_RC_OK;
1198 * exec_stmt_getdiag Put internal PG information into
1199 * specified variables.
1203 exec_stmt_getdiag(PLpgSQL_execstate *estate, PLpgSQL_stmt_getdiag *stmt)
1207 foreach(lc, stmt->diag_items)
1209 PLpgSQL_diag_item *diag_item = (PLpgSQL_diag_item *) lfirst(lc);
1211 bool isnull = false;
1213 if (diag_item->target <= 0)
1216 var = estate->datums[diag_item->target];
1221 switch (diag_item->kind)
1223 case PLPGSQL_GETDIAG_ROW_COUNT:
1225 exec_assign_value(estate, var,
1226 UInt32GetDatum(estate->eval_processed),
1230 case PLPGSQL_GETDIAG_RESULT_OID:
1232 exec_assign_value(estate, var,
1233 ObjectIdGetDatum(estate->eval_lastoid),
1238 elog(ERROR, "unrecognized attribute request: %d",
1243 return PLPGSQL_RC_OK;
1247 * exec_stmt_if Evaluate a bool expression and
1248 * execute the true or false body
1253 exec_stmt_if(PLpgSQL_execstate *estate, PLpgSQL_stmt_if *stmt)
1258 value = exec_eval_boolean(estate, stmt->cond, &isnull);
1259 exec_eval_cleanup(estate);
1261 if (!isnull && value)
1263 if (stmt->true_body != NIL)
1264 return exec_stmts(estate, stmt->true_body);
1268 if (stmt->false_body != NIL)
1269 return exec_stmts(estate, stmt->false_body);
1272 return PLPGSQL_RC_OK;
1277 * exec_stmt_loop Loop over statements until
1282 exec_stmt_loop(PLpgSQL_execstate *estate, PLpgSQL_stmt_loop *stmt)
1286 int rc = exec_stmts(estate, stmt->body);
1293 case PLPGSQL_RC_EXIT:
1294 if (estate->exitlabel == NULL)
1295 return PLPGSQL_RC_OK;
1296 if (stmt->label == NULL)
1297 return PLPGSQL_RC_EXIT;
1298 if (strcmp(stmt->label, estate->exitlabel) != 0)
1299 return PLPGSQL_RC_EXIT;
1300 estate->exitlabel = NULL;
1301 return PLPGSQL_RC_OK;
1303 case PLPGSQL_RC_CONTINUE:
1304 if (estate->exitlabel == NULL)
1305 /* anonymous continue, so re-run the loop */
1307 else if (stmt->label != NULL &&
1308 strcmp(stmt->label, estate->exitlabel) == 0)
1309 /* label matches named continue, so re-run loop */
1310 estate->exitlabel = NULL;
1312 /* label doesn't match named continue, so propagate upward */
1313 return PLPGSQL_RC_CONTINUE;
1316 case PLPGSQL_RC_RETURN:
1317 return PLPGSQL_RC_RETURN;
1320 elog(ERROR, "unrecognized rc: %d", rc);
1324 return PLPGSQL_RC_OK;
1329 * exec_stmt_while Loop over statements as long
1330 * as an expression evaluates to
1331 * true or an exit occurs.
1335 exec_stmt_while(PLpgSQL_execstate *estate, PLpgSQL_stmt_while *stmt)
1343 value = exec_eval_boolean(estate, stmt->cond, &isnull);
1344 exec_eval_cleanup(estate);
1346 if (isnull || !value)
1349 rc = exec_stmts(estate, stmt->body);
1356 case PLPGSQL_RC_EXIT:
1357 if (estate->exitlabel == NULL)
1358 return PLPGSQL_RC_OK;
1359 if (stmt->label == NULL)
1360 return PLPGSQL_RC_EXIT;
1361 if (strcmp(stmt->label, estate->exitlabel))
1362 return PLPGSQL_RC_EXIT;
1363 estate->exitlabel = NULL;
1364 return PLPGSQL_RC_OK;
1366 case PLPGSQL_RC_CONTINUE:
1367 if (estate->exitlabel == NULL)
1368 /* anonymous continue, so re-run loop */
1370 else if (stmt->label != NULL &&
1371 strcmp(stmt->label, estate->exitlabel) == 0)
1372 /* label matches named continue, so re-run loop */
1373 estate->exitlabel = NULL;
1375 /* label doesn't match named continue, propagate upward */
1376 return PLPGSQL_RC_CONTINUE;
1379 case PLPGSQL_RC_RETURN:
1380 return PLPGSQL_RC_RETURN;
1383 elog(ERROR, "unrecognized rc: %d", rc);
1387 return PLPGSQL_RC_OK;
1392 * exec_stmt_fori Iterate an integer variable
1393 * from a lower to an upper value
1394 * incrementing or decrementing in BY value
1395 * Loop can be left with exit.
1399 exec_stmt_fori(PLpgSQL_execstate *estate, PLpgSQL_stmt_fori *stmt)
1407 int rc = PLPGSQL_RC_OK;
1409 var = (PLpgSQL_var *) (estate->datums[stmt->var->varno]);
1412 * Get the value of the lower bound into the loop var
1414 value = exec_eval_expr(estate, stmt->lower, &isnull, &valtype);
1415 value = exec_cast_value(value, valtype, var->datatype->typoid,
1416 &(var->datatype->typinput),
1417 var->datatype->typioparam,
1418 var->datatype->atttypmod, isnull);
1421 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1422 errmsg("lower bound of FOR loop cannot be NULL")));
1424 var->isnull = false;
1425 exec_eval_cleanup(estate);
1428 * Get the value of the upper bound
1430 value = exec_eval_expr(estate, stmt->upper, &isnull, &valtype);
1431 value = exec_cast_value(value, valtype, var->datatype->typoid,
1432 &(var->datatype->typinput),
1433 var->datatype->typioparam,
1434 var->datatype->atttypmod, isnull);
1437 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1438 errmsg("upper bound of FOR loop cannot be NULL")));
1439 exec_eval_cleanup(estate);
1444 by_value = exec_eval_expr(estate, stmt->by, &isnull, &valtype);
1445 by_value = exec_cast_value(by_value, valtype, var->datatype->typoid,
1446 &(var->datatype->typinput),
1447 var->datatype->typioparam,
1448 var->datatype->atttypmod, isnull);
1452 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1453 errmsg("by value of FOR loop cannot be NULL")));
1454 exec_eval_cleanup(estate);
1466 if ((int4) (var->value) < (int4) value)
1471 if ((int4) (var->value) > (int4) value)
1475 found = true; /* looped at least once */
1478 * Execute the statements
1480 rc = exec_stmts(estate, stmt->body);
1482 if (rc == PLPGSQL_RC_RETURN)
1483 break; /* return from function */
1484 else if (rc == PLPGSQL_RC_EXIT)
1486 if (estate->exitlabel == NULL)
1487 /* unlabelled exit, finish the current loop */
1489 else if (stmt->label != NULL &&
1490 strcmp(stmt->label, estate->exitlabel) == 0)
1492 /* labelled exit, matches the current stmt's label */
1493 estate->exitlabel = NULL;
1498 * otherwise, this is a labelled exit that does not match the
1499 * current statement's label, if any: return RC_EXIT so that the
1500 * EXIT continues to propagate up the stack.
1505 else if (rc == PLPGSQL_RC_CONTINUE)
1507 if (estate->exitlabel == NULL)
1508 /* anonymous continue, so re-run the current loop */
1510 else if (stmt->label != NULL &&
1511 strcmp(stmt->label, estate->exitlabel) == 0)
1513 /* label matches named continue, so re-run loop */
1514 estate->exitlabel = NULL;
1520 * otherwise, this is a named continue that does not match the
1521 * current statement's label, if any: return RC_CONTINUE so
1522 * that the CONTINUE will propagate up the stack.
1529 * Increase/decrease loop var
1532 var->value -= by_value;
1534 var->value += by_value;
1538 * Set the FOUND variable to indicate the result of executing the loop
1539 * (namely, whether we looped one or more times). This must be set here so
1540 * that it does not interfere with the value of the FOUND variable inside
1541 * the loop processing itself.
1543 exec_set_found(estate, found);
1550 * exec_stmt_fors Execute a query, assign each
1551 * tuple to a record or row and
1552 * execute a group of statements
1557 exec_stmt_fors(PLpgSQL_execstate *estate, PLpgSQL_stmt_fors *stmt)
1559 PLpgSQL_rec *rec = NULL;
1560 PLpgSQL_row *row = NULL;
1561 SPITupleTable *tuptab;
1564 int rc = PLPGSQL_RC_OK;
1569 * Determine if we assign to a record or a row
1571 if (stmt->rec != NULL)
1572 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
1573 else if (stmt->row != NULL)
1574 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
1576 elog(ERROR, "unsupported target");
1579 * Open the implicit cursor for the statement and fetch the initial 10
1582 exec_run_select(estate, stmt->query, 0, &portal);
1584 SPI_cursor_fetch(portal, true, 10);
1585 tuptab = SPI_tuptable;
1589 * If the query didn't return any rows, set the target to NULL and return
1590 * with FOUND = false.
1593 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
1595 found = true; /* processed at least one tuple */
1602 for (i = 0; i < n; i++)
1605 * Assign the tuple to the target
1607 exec_move_row(estate, rec, row, tuptab->vals[i], tuptab->tupdesc);
1610 * Execute the statements
1612 rc = exec_stmts(estate, stmt->body);
1613 if (rc != PLPGSQL_RC_OK)
1615 if (rc == PLPGSQL_RC_EXIT)
1617 if (estate->exitlabel == NULL)
1618 /* unlabelled exit, finish the current loop */
1620 else if (stmt->label != NULL &&
1621 strcmp(stmt->label, estate->exitlabel) == 0)
1623 /* labelled exit, matches the current stmt's label */
1624 estate->exitlabel = NULL;
1629 * otherwise, we processed a labelled exit that does not
1630 * match the current statement's label, if any: return
1631 * RC_EXIT so that the EXIT continues to recurse upward.
1634 else if (rc == PLPGSQL_RC_CONTINUE)
1636 if (estate->exitlabel == NULL)
1638 /* anonymous continue, so re-run the current loop */
1642 else if (stmt->label != NULL &&
1643 strcmp(stmt->label, estate->exitlabel) == 0)
1645 /* label matches named continue, so re-run loop */
1647 estate->exitlabel = NULL;
1652 * otherwise, we processed a named continue that does not
1653 * match the current statement's label, if any: return
1654 * RC_CONTINUE so that the CONTINUE will propagate up the
1660 * We're aborting the loop, so cleanup and set FOUND. (This
1661 * code should match the code after the loop.)
1663 SPI_freetuptable(tuptab);
1664 SPI_cursor_close(portal);
1665 exec_set_found(estate, found);
1671 SPI_freetuptable(tuptab);
1674 * Fetch the next 50 tuples
1676 SPI_cursor_fetch(portal, true, 50);
1678 tuptab = SPI_tuptable;
1682 * Release last group of tuples
1684 SPI_freetuptable(tuptab);
1687 * Close the implicit cursor
1689 SPI_cursor_close(portal);
1692 * Set the FOUND variable to indicate the result of executing the loop
1693 * (namely, whether we looped one or more times). This must be set here so
1694 * that it does not interfere with the value of the FOUND variable inside
1695 * the loop processing itself.
1697 exec_set_found(estate, found);
1704 * exec_stmt_exit Implements EXIT and CONTINUE
1706 * This begins the process of exiting / restarting a loop.
1710 exec_stmt_exit(PLpgSQL_execstate *estate, PLpgSQL_stmt_exit *stmt)
1713 * If the exit / continue has a condition, evaluate it
1715 if (stmt->cond != NULL)
1720 value = exec_eval_boolean(estate, stmt->cond, &isnull);
1721 exec_eval_cleanup(estate);
1722 if (isnull || value == false)
1723 return PLPGSQL_RC_OK;
1726 estate->exitlabel = stmt->label;
1728 return PLPGSQL_RC_EXIT;
1730 return PLPGSQL_RC_CONTINUE;
1735 * exec_stmt_return Evaluate an expression and start
1736 * returning from the function.
1740 exec_stmt_return(PLpgSQL_execstate *estate, PLpgSQL_stmt_return *stmt)
1743 * If processing a set-returning PL/PgSQL function, the final RETURN
1744 * indicates that the function is finished producing tuples. The rest of
1745 * the work will be done at the top level.
1747 if (estate->retisset)
1748 return PLPGSQL_RC_RETURN;
1750 /* initialize for null result (possibly a tuple) */
1751 estate->retval = (Datum) 0;
1752 estate->rettupdesc = NULL;
1753 estate->retisnull = true;
1755 if (stmt->retvarno >= 0)
1757 PLpgSQL_datum *retvar = estate->datums[stmt->retvarno];
1759 switch (retvar->dtype)
1761 case PLPGSQL_DTYPE_VAR:
1763 PLpgSQL_var *var = (PLpgSQL_var *) retvar;
1765 estate->retval = var->value;
1766 estate->retisnull = var->isnull;
1767 estate->rettype = var->datatype->typoid;
1771 case PLPGSQL_DTYPE_REC:
1773 PLpgSQL_rec *rec = (PLpgSQL_rec *) retvar;
1775 if (HeapTupleIsValid(rec->tup))
1777 estate->retval = (Datum) rec->tup;
1778 estate->rettupdesc = rec->tupdesc;
1779 estate->retisnull = false;
1784 case PLPGSQL_DTYPE_ROW:
1786 PLpgSQL_row *row = (PLpgSQL_row *) retvar;
1788 Assert(row->rowtupdesc);
1789 estate->retval = (Datum) make_tuple_from_row(estate, row,
1791 if (estate->retval == (Datum) NULL) /* should not happen */
1792 elog(ERROR, "row not compatible with its own tupdesc");
1793 estate->rettupdesc = row->rowtupdesc;
1794 estate->retisnull = false;
1799 elog(ERROR, "unrecognized dtype: %d", retvar->dtype);
1802 return PLPGSQL_RC_RETURN;
1805 if (stmt->expr != NULL)
1807 if (estate->retistuple)
1809 exec_run_select(estate, stmt->expr, 1, NULL);
1810 if (estate->eval_processed > 0)
1812 estate->retval = (Datum) estate->eval_tuptable->vals[0];
1813 estate->rettupdesc = estate->eval_tuptable->tupdesc;
1814 estate->retisnull = false;
1819 /* Normal case for scalar results */
1820 estate->retval = exec_eval_expr(estate, stmt->expr,
1821 &(estate->retisnull),
1822 &(estate->rettype));
1825 return PLPGSQL_RC_RETURN;
1829 * Special hack for function returning VOID: instead of NULL, return a
1830 * non-null VOID value. This is of dubious importance but is kept for
1831 * backwards compatibility. Note that the only other way to get here is
1832 * to have written "RETURN NULL" in a function returning tuple.
1834 if (estate->fn_rettype == VOIDOID)
1836 estate->retval = (Datum) 0;
1837 estate->retisnull = false;
1838 estate->rettype = VOIDOID;
1841 return PLPGSQL_RC_RETURN;
1845 * exec_stmt_return_next Evaluate an expression and add it to the
1846 * list of tuples returned by the current
1851 exec_stmt_return_next(PLpgSQL_execstate *estate,
1852 PLpgSQL_stmt_return_next *stmt)
1857 bool free_tuple = false;
1859 if (!estate->retisset)
1861 (errcode(ERRCODE_SYNTAX_ERROR),
1862 errmsg("cannot use RETURN NEXT in a non-SETOF function")));
1864 if (estate->tuple_store == NULL)
1865 exec_init_tuple_store(estate);
1867 /* rettupdesc will be filled by exec_init_tuple_store */
1868 tupdesc = estate->rettupdesc;
1869 natts = tupdesc->natts;
1871 if (stmt->retvarno >= 0)
1873 PLpgSQL_datum *retvar = estate->datums[stmt->retvarno];
1875 switch (retvar->dtype)
1877 case PLPGSQL_DTYPE_VAR:
1879 PLpgSQL_var *var = (PLpgSQL_var *) retvar;
1880 Datum retval = var->value;
1881 bool isNull = var->isnull;
1885 (errcode(ERRCODE_DATATYPE_MISMATCH),
1886 errmsg("wrong result type supplied in RETURN NEXT")));
1888 /* coerce type if needed */
1889 retval = exec_simple_cast_value(retval,
1890 var->datatype->typoid,
1891 tupdesc->attrs[0]->atttypid,
1892 tupdesc->attrs[0]->atttypmod,
1895 tuple = heap_form_tuple(tupdesc, &retval, &isNull);
1901 case PLPGSQL_DTYPE_REC:
1903 PLpgSQL_rec *rec = (PLpgSQL_rec *) retvar;
1905 if (!HeapTupleIsValid(rec->tup))
1907 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1908 errmsg("record \"%s\" is not assigned yet",
1910 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
1911 if (!compatible_tupdesc(tupdesc, rec->tupdesc))
1913 (errcode(ERRCODE_DATATYPE_MISMATCH),
1914 errmsg("wrong record type supplied in RETURN NEXT")));
1919 case PLPGSQL_DTYPE_ROW:
1921 PLpgSQL_row *row = (PLpgSQL_row *) retvar;
1923 tuple = make_tuple_from_row(estate, row, tupdesc);
1926 (errcode(ERRCODE_DATATYPE_MISMATCH),
1927 errmsg("wrong record type supplied in RETURN NEXT")));
1933 elog(ERROR, "unrecognized dtype: %d", retvar->dtype);
1934 tuple = NULL; /* keep compiler quiet */
1938 else if (stmt->expr)
1946 (errcode(ERRCODE_DATATYPE_MISMATCH),
1947 errmsg("wrong result type supplied in RETURN NEXT")));
1949 retval = exec_eval_expr(estate,
1954 /* coerce type if needed */
1955 retval = exec_simple_cast_value(retval,
1957 tupdesc->attrs[0]->atttypid,
1958 tupdesc->attrs[0]->atttypmod,
1961 tuple = heap_form_tuple(tupdesc, &retval, &isNull);
1965 exec_eval_cleanup(estate);
1970 (errcode(ERRCODE_SYNTAX_ERROR),
1971 errmsg("RETURN NEXT must have a parameter")));
1972 tuple = NULL; /* keep compiler quiet */
1975 if (HeapTupleIsValid(tuple))
1977 MemoryContext oldcxt;
1979 oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
1980 tuplestore_puttuple(estate->tuple_store, tuple);
1981 MemoryContextSwitchTo(oldcxt);
1984 heap_freetuple(tuple);
1987 return PLPGSQL_RC_OK;
1991 exec_init_tuple_store(PLpgSQL_execstate *estate)
1993 ReturnSetInfo *rsi = estate->rsi;
1994 MemoryContext oldcxt;
1997 * Check caller can handle a set result in the way we want
1999 if (!rsi || !IsA(rsi, ReturnSetInfo) ||
2000 (rsi->allowedModes & SFRM_Materialize) == 0 ||
2001 rsi->expectedDesc == NULL)
2003 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2004 errmsg("set-valued function called in context that cannot accept a set")));
2006 estate->tuple_store_cxt = rsi->econtext->ecxt_per_query_memory;
2008 oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
2009 estate->tuple_store = tuplestore_begin_heap(true, false, work_mem);
2010 MemoryContextSwitchTo(oldcxt);
2012 estate->rettupdesc = rsi->expectedDesc;
2016 * exec_stmt_raise Build a message and throw it with elog()
2020 exec_stmt_raise(PLpgSQL_execstate *estate, PLpgSQL_stmt_raise *stmt)
2024 ListCell *current_param;
2026 plpgsql_dstring_init(&ds);
2027 current_param = list_head(stmt->params);
2029 for (cp = stmt->message; *cp; cp++)
2032 * Occurrences of a single % are replaced by the next parameter's
2033 * external representation. Double %'s are converted to one %.
2044 plpgsql_dstring_append_char(&ds, cp[1]);
2049 if (current_param == NULL)
2051 (errcode(ERRCODE_SYNTAX_ERROR),
2052 errmsg("too few parameters specified for RAISE")));
2054 paramvalue = exec_eval_expr(estate,
2055 (PLpgSQL_expr *) lfirst(current_param),
2062 extval = convert_value_to_string(paramvalue, paramtypeid);
2063 plpgsql_dstring_append(&ds, extval);
2064 current_param = lnext(current_param);
2065 exec_eval_cleanup(estate);
2069 plpgsql_dstring_append_char(&ds, cp[0]);
2073 * If more parameters were specified than were required to process the
2074 * format string, throw an error
2076 if (current_param != NULL)
2078 (errcode(ERRCODE_SYNTAX_ERROR),
2079 errmsg("too many parameters specified for RAISE")));
2082 * Throw the error (may or may not come back)
2084 estate->err_text = raise_skip_msg; /* suppress traceback of raise */
2086 ereport(stmt->elog_level,
2087 ((stmt->elog_level >= ERROR) ? errcode(ERRCODE_RAISE_EXCEPTION) : 0,
2088 errmsg_internal("%s", plpgsql_dstring_get(&ds))));
2090 estate->err_text = NULL; /* un-suppress... */
2092 plpgsql_dstring_free(&ds);
2094 return PLPGSQL_RC_OK;
2099 * Initialize a mostly empty execution state
2103 plpgsql_estate_setup(PLpgSQL_execstate *estate,
2104 PLpgSQL_function *func,
2107 estate->retval = (Datum) 0;
2108 estate->retisnull = true;
2109 estate->rettype = InvalidOid;
2111 estate->fn_rettype = func->fn_rettype;
2112 estate->retistuple = func->fn_retistuple;
2113 estate->retisset = func->fn_retset;
2115 estate->readonly_func = func->fn_readonly;
2117 estate->rettupdesc = NULL;
2118 estate->exitlabel = NULL;
2120 estate->tuple_store = NULL;
2121 estate->tuple_store_cxt = NULL;
2124 estate->trig_nargs = 0;
2125 estate->trig_argv = NULL;
2127 estate->found_varno = func->found_varno;
2128 estate->ndatums = func->ndatums;
2129 estate->datums = palloc(sizeof(PLpgSQL_datum *) * estate->ndatums);
2130 /* caller is expected to fill the datums array */
2132 estate->eval_tuptable = NULL;
2133 estate->eval_processed = 0;
2134 estate->eval_lastoid = InvalidOid;
2136 estate->err_func = func;
2137 estate->err_stmt = NULL;
2138 estate->err_text = NULL;
2141 * Create an EState for evaluation of simple expressions, if there's not
2142 * one already in the current transaction. The EState is made a child of
2143 * TopTransactionContext so it will have the right lifespan.
2145 if (simple_eval_estate == NULL)
2147 MemoryContext oldcontext;
2149 oldcontext = MemoryContextSwitchTo(TopTransactionContext);
2150 simple_eval_estate = CreateExecutorState();
2151 MemoryContextSwitchTo(oldcontext);
2155 * Create an expression context for simple expressions. This must be a
2156 * child of simple_eval_estate.
2158 estate->eval_econtext = CreateExprContext(simple_eval_estate);
2161 * Let the plugin see this function before we initialize any
2162 * local PL/pgSQL variables - note that we also give the plugin
2163 * a few function pointers so it can call back into PL/pgSQL
2164 * for doing things like variable assignments and stack traces
2168 (*plugin_ptr)->error_callback = plpgsql_exec_error_callback;
2169 (*plugin_ptr)->assign_expr = exec_assign_expr;
2171 if ((*plugin_ptr)->func_setup)
2172 ((*plugin_ptr)->func_setup)(estate, func);
2177 * Release temporary memory used by expression/subselect evaluation
2179 * NB: the result of the evaluation is no longer valid after this is done,
2180 * unless it is a pass-by-value datatype.
2184 exec_eval_cleanup(PLpgSQL_execstate *estate)
2186 /* Clear result of a full SPI_execute */
2187 if (estate->eval_tuptable != NULL)
2188 SPI_freetuptable(estate->eval_tuptable);
2189 estate->eval_tuptable = NULL;
2191 /* Clear result of exec_eval_simple_expr (but keep the econtext) */
2192 if (estate->eval_econtext != NULL)
2193 ResetExprContext(estate->eval_econtext);
2198 * Generate a prepared plan
2202 exec_prepare_plan(PLpgSQL_execstate *estate,
2206 _SPI_plan *spi_plan;
2211 * We need a temporary argtypes array to load with data. (The finished
2212 * plan structure will contain a copy of it.)
2214 argtypes = (Oid *) palloc(expr->nparams * sizeof(Oid));
2216 for (i = 0; i < expr->nparams; i++)
2221 exec_eval_datum(estate, estate->datums[expr->params[i]],
2223 &argtypes[i], ¶mval, ¶misnull);
2227 * Generate and save the plan
2229 plan = SPI_prepare(expr->query, expr->nparams, argtypes);
2232 /* Some SPI errors deserve specific error messages */
2235 case SPI_ERROR_COPY:
2237 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2238 errmsg("cannot COPY to/from client in PL/pgSQL")));
2239 case SPI_ERROR_CURSOR:
2241 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2242 errmsg("cannot manipulate cursors directly in PL/pgSQL"),
2243 errhint("Use PL/pgSQL's cursor features instead.")));
2244 case SPI_ERROR_TRANSACTION:
2246 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2247 errmsg("cannot begin/end transactions in PL/pgSQL"),
2248 errhint("Use a BEGIN block with an EXCEPTION clause instead.")));
2250 elog(ERROR, "SPI_prepare failed for \"%s\": %s",
2251 expr->query, SPI_result_code_string(SPI_result));
2254 expr->plan = SPI_saveplan(plan);
2255 spi_plan = (_SPI_plan *) expr->plan;
2256 expr->plan_argtypes = spi_plan->argtypes;
2257 expr->expr_simple_expr = NULL;
2258 exec_simple_check_plan(expr);
2266 * exec_stmt_execsql Execute an SQL statement (possibly with INTO).
2270 exec_stmt_execsql(PLpgSQL_execstate *estate,
2271 PLpgSQL_stmt_execsql *stmt)
2278 PLpgSQL_expr *expr = stmt->sqlstmt;
2281 * On the first call for this statement generate the plan, and
2282 * detect whether the statement is INSERT/UPDATE/DELETE
2284 if (expr->plan == NULL)
2286 _SPI_plan *spi_plan;
2289 exec_prepare_plan(estate, expr);
2290 stmt->mod_stmt = false;
2291 spi_plan = (_SPI_plan *) expr->plan;
2292 foreach(l, spi_plan->qtlist)
2296 foreach(l2, (List *) lfirst(l))
2298 Query *q = (Query *) lfirst(l2);
2300 Assert(IsA(q, Query));
2303 if (q->commandType == CMD_INSERT ||
2304 q->commandType == CMD_UPDATE ||
2305 q->commandType == CMD_DELETE)
2306 stmt->mod_stmt = true;
2313 * Now build up the values and nulls arguments for SPI_execute_plan()
2315 values = (Datum *) palloc(expr->nparams * sizeof(Datum));
2316 nulls = (char *) palloc(expr->nparams * sizeof(char));
2318 for (i = 0; i < expr->nparams; i++)
2320 PLpgSQL_datum *datum = estate->datums[expr->params[i]];
2324 exec_eval_datum(estate, datum, expr->plan_argtypes[i],
2325 ¶mtypeid, &values[i], ¶misnull);
2333 * If we have INTO, then we only need one row back ... but if we have
2334 * INTO STRICT, ask for two rows, so that we can verify the statement
2335 * returns only one. INSERT/UPDATE/DELETE are always treated strictly.
2336 * Without INTO, just run the statement to completion (tcount = 0).
2338 * We could just ask for two rows always when using INTO, but there
2339 * are some cases where demanding the extra row costs significant time,
2340 * eg by forcing completion of a sequential scan. So don't do it unless
2341 * we need to enforce strictness.
2345 if (stmt->strict || stmt->mod_stmt)
2356 rc = SPI_execute_plan(expr->plan, values, nulls,
2357 estate->readonly_func, tcount);
2360 * Check for error, and set FOUND if appropriate (for historical reasons
2361 * we set FOUND only for certain query types). Also Assert that we
2362 * identified the statement type the same as SPI did.
2367 Assert(!stmt->mod_stmt);
2368 exec_set_found(estate, (SPI_processed != 0));
2374 case SPI_OK_INSERT_RETURNING:
2375 case SPI_OK_UPDATE_RETURNING:
2376 case SPI_OK_DELETE_RETURNING:
2377 Assert(stmt->mod_stmt);
2378 exec_set_found(estate, (SPI_processed != 0));
2381 case SPI_OK_SELINTO:
2382 case SPI_OK_UTILITY:
2383 Assert(!stmt->mod_stmt);
2387 elog(ERROR, "SPI_execute_plan failed executing query \"%s\": %s",
2388 expr->query, SPI_result_code_string(rc));
2391 /* All variants should save result info for GET DIAGNOSTICS */
2392 estate->eval_processed = SPI_processed;
2393 estate->eval_lastoid = SPI_lastoid;
2395 /* Process INTO if present */
2398 SPITupleTable *tuptab = SPI_tuptable;
2399 uint32 n = SPI_processed;
2400 PLpgSQL_rec *rec = NULL;
2401 PLpgSQL_row *row = NULL;
2403 /* If the statement did not return a tuple table, complain */
2406 (errcode(ERRCODE_SYNTAX_ERROR),
2407 errmsg("INTO used with a command that cannot return data")));
2409 /* Determine if we assign to a record or a row */
2410 if (stmt->rec != NULL)
2411 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
2412 else if (stmt->row != NULL)
2413 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
2415 elog(ERROR, "unsupported target");
2418 * If SELECT ... INTO specified STRICT, and the query didn't
2419 * find exactly one row, throw an error. If STRICT was not specified,
2420 * then allow the query to find any number of rows.
2426 (errcode(ERRCODE_NO_DATA_FOUND),
2427 errmsg("query returned no rows")));
2428 /* set the target to NULL(s) */
2429 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
2433 if (n > 1 && (stmt->strict || stmt->mod_stmt))
2435 (errcode(ERRCODE_TOO_MANY_ROWS),
2436 errmsg("query returned more than one row")));
2437 /* Put the first result row into the target */
2438 exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
2442 SPI_freetuptable(SPI_tuptable);
2446 /* If the statement returned a tuple table, complain */
2447 if (SPI_tuptable != NULL)
2449 (errcode(ERRCODE_SYNTAX_ERROR),
2450 errmsg("query has no destination for result data"),
2451 (rc == SPI_OK_SELECT) ? errhint("If you want to discard the results of a SELECT, use PERFORM instead.") : 0));
2457 return PLPGSQL_RC_OK;
2462 * exec_stmt_dynexecute Execute a dynamic SQL query
2463 * (possibly with INTO).
2467 exec_stmt_dynexecute(PLpgSQL_execstate *estate,
2468 PLpgSQL_stmt_dynexecute *stmt)
2471 bool isnull = false;
2477 * First we evaluate the string expression after the EXECUTE keyword.
2478 * Its result is the querystring we have to execute.
2480 query = exec_eval_expr(estate, stmt->query, &isnull, &restype);
2483 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2484 errmsg("cannot EXECUTE a null querystring")));
2486 /* Get the C-String representation */
2487 querystr = convert_value_to_string(query, restype);
2489 exec_eval_cleanup(estate);
2492 * Call SPI_execute() without preparing a saved plan.
2494 exec_res = SPI_execute(querystr, estate->readonly_func, 0);
2502 case SPI_OK_INSERT_RETURNING:
2503 case SPI_OK_UPDATE_RETURNING:
2504 case SPI_OK_DELETE_RETURNING:
2505 case SPI_OK_UTILITY:
2511 * Also allow a zero return, which implies the querystring
2512 * contained no commands.
2516 case SPI_OK_SELINTO:
2519 * We want to disallow SELECT INTO for now, because its behavior
2520 * is not consistent with SELECT INTO in a normal plpgsql context.
2521 * (We need to reimplement EXECUTE to parse the string as a
2522 * plpgsql command, not just feed it to SPI_execute.) However,
2523 * CREATE AS should be allowed ... and since it produces the same
2524 * parsetree as SELECT INTO, there's no way to tell the difference
2525 * except to look at the source text. Wotta kluge!
2530 for (ptr = querystr; *ptr; ptr++)
2531 if (!scanner_isspace(*ptr))
2533 if (*ptr == 'S' || *ptr == 's')
2535 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2536 errmsg("EXECUTE of SELECT ... INTO is not implemented yet")));
2540 /* Some SPI errors deserve specific error messages */
2541 case SPI_ERROR_COPY:
2543 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2544 errmsg("cannot COPY to/from client in PL/pgSQL")));
2545 case SPI_ERROR_CURSOR:
2547 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2548 errmsg("cannot manipulate cursors directly in PL/pgSQL"),
2549 errhint("Use PL/pgSQL's cursor features instead.")));
2550 case SPI_ERROR_TRANSACTION:
2552 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2553 errmsg("cannot begin/end transactions in PL/pgSQL"),
2554 errhint("Use a BEGIN block with an EXCEPTION clause instead.")));
2557 elog(ERROR, "SPI_execute failed executing query \"%s\": %s",
2558 querystr, SPI_result_code_string(exec_res));
2562 /* Save result info for GET DIAGNOSTICS */
2563 estate->eval_processed = SPI_processed;
2564 estate->eval_lastoid = SPI_lastoid;
2566 /* Process INTO if present */
2569 SPITupleTable *tuptab = SPI_tuptable;
2570 uint32 n = SPI_processed;
2571 PLpgSQL_rec *rec = NULL;
2572 PLpgSQL_row *row = NULL;
2574 /* If the statement did not return a tuple table, complain */
2577 (errcode(ERRCODE_SYNTAX_ERROR),
2578 errmsg("INTO used with a command that cannot return data")));
2580 /* Determine if we assign to a record or a row */
2581 if (stmt->rec != NULL)
2582 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
2583 else if (stmt->row != NULL)
2584 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
2586 elog(ERROR, "unsupported target");
2589 * If SELECT ... INTO specified STRICT, and the query didn't
2590 * find exactly one row, throw an error. If STRICT was not specified,
2591 * then allow the query to find any number of rows.
2597 (errcode(ERRCODE_NO_DATA_FOUND),
2598 errmsg("query returned no rows")));
2599 /* set the target to NULL(s) */
2600 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
2604 if (n > 1 && stmt->strict)
2606 (errcode(ERRCODE_TOO_MANY_ROWS),
2607 errmsg("query returned more than one row")));
2608 /* Put the first result row into the target */
2609 exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
2615 * It might be a good idea to raise an error if the query returned
2616 * tuples that are being ignored, but historically we have not done
2621 /* Release any result from SPI_execute, as well as the querystring */
2622 SPI_freetuptable(SPI_tuptable);
2625 return PLPGSQL_RC_OK;
2630 * exec_stmt_dynfors Execute a dynamic query, assign each
2631 * tuple to a record or row and
2632 * execute a group of statements
2637 exec_stmt_dynfors(PLpgSQL_execstate *estate, PLpgSQL_stmt_dynfors *stmt)
2643 PLpgSQL_rec *rec = NULL;
2644 PLpgSQL_row *row = NULL;
2645 SPITupleTable *tuptab;
2652 * Determine if we assign to a record or a row
2654 if (stmt->rec != NULL)
2655 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
2656 else if (stmt->row != NULL)
2657 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
2659 elog(ERROR, "unsupported target");
2662 * Evaluate the string expression after the EXECUTE keyword. It's result
2663 * is the querystring we have to execute.
2665 query = exec_eval_expr(estate, stmt->query, &isnull, &restype);
2668 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2669 errmsg("cannot EXECUTE a null querystring")));
2671 /* Get the C-String representation */
2672 querystr = convert_value_to_string(query, restype);
2674 exec_eval_cleanup(estate);
2677 * Prepare a plan and open an implicit cursor for the query
2679 plan = SPI_prepare(querystr, 0, NULL);
2681 elog(ERROR, "SPI_prepare failed for \"%s\": %s",
2682 querystr, SPI_result_code_string(SPI_result));
2683 portal = SPI_cursor_open(NULL, plan, NULL, NULL,
2684 estate->readonly_func);
2686 elog(ERROR, "could not open implicit cursor for query \"%s\": %s",
2687 querystr, SPI_result_code_string(SPI_result));
2692 * Fetch the initial 10 tuples
2694 SPI_cursor_fetch(portal, true, 10);
2695 tuptab = SPI_tuptable;
2699 * If the query didn't return any rows, set the target to NULL and return
2700 * with FOUND = false.
2703 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
2705 found = true; /* processed at least one tuple */
2714 for (i = 0; i < n; i++)
2719 * Assign the tuple to the target
2721 exec_move_row(estate, rec, row, tuptab->vals[i], tuptab->tupdesc);
2724 * Execute the statements
2726 rc = exec_stmts(estate, stmt->body);
2728 if (rc != PLPGSQL_RC_OK)
2730 if (rc == PLPGSQL_RC_EXIT)
2732 if (estate->exitlabel == NULL)
2733 /* unlabelled exit, finish the current loop */
2735 else if (stmt->label != NULL &&
2736 strcmp(stmt->label, estate->exitlabel) == 0)
2738 /* labelled exit, matches the current stmt's label */
2739 estate->exitlabel = NULL;
2744 * otherwise, we processed a labelled exit that does not
2745 * match the current statement's label, if any: return
2746 * RC_EXIT so that the EXIT continues to recurse upward.
2749 else if (rc == PLPGSQL_RC_CONTINUE)
2751 if (estate->exitlabel == NULL)
2752 /* unlabelled continue, continue the current loop */
2754 else if (stmt->label != NULL &&
2755 strcmp(stmt->label, estate->exitlabel) == 0)
2757 /* labelled continue, matches the current stmt's label */
2758 estate->exitlabel = NULL;
2763 * otherwise, we process a labelled continue that does not
2764 * match the current statement's label, so propagate
2765 * RC_CONTINUE upward in the stack.
2770 * We're aborting the loop, so cleanup and set FOUND. (This
2771 * code should match the code after the loop.)
2773 SPI_freetuptable(tuptab);
2774 SPI_cursor_close(portal);
2775 exec_set_found(estate, found);
2781 SPI_freetuptable(tuptab);
2784 * Fetch the next 50 tuples
2786 SPI_cursor_fetch(portal, true, 50);
2788 tuptab = SPI_tuptable;
2792 * Release last group of tuples
2794 SPI_freetuptable(tuptab);
2797 * Close the implicit cursor
2799 SPI_cursor_close(portal);
2802 * Set the FOUND variable to indicate the result of executing the loop
2803 * (namely, whether we looped one or more times). This must be set here so
2804 * that it does not interfere with the value of the FOUND variable inside
2805 * the loop processing itself.
2807 exec_set_found(estate, found);
2809 return PLPGSQL_RC_OK;
2814 * exec_stmt_open Execute an OPEN cursor statement
2818 exec_stmt_open(PLpgSQL_execstate *estate, PLpgSQL_stmt_open *stmt)
2820 PLpgSQL_var *curvar = NULL;
2821 char *curname = NULL;
2822 PLpgSQL_expr *query = NULL;
2831 * Get the cursor variable and if it has an assigned name, check
2832 * that it's not in use currently.
2835 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
2836 if (!curvar->isnull)
2838 curname = DatumGetCString(DirectFunctionCall1(textout, curvar->value));
2839 if (SPI_cursor_find(curname) != NULL)
2841 (errcode(ERRCODE_DUPLICATE_CURSOR),
2842 errmsg("cursor \"%s\" already in use", curname)));
2846 * Process the OPEN according to it's type.
2849 if (stmt->query != NULL)
2852 * This is an OPEN refcursor FOR SELECT ...
2854 * We just make sure the query is planned. The real work is
2858 query = stmt->query;
2859 if (query->plan == NULL)
2860 exec_prepare_plan(estate, query);
2862 else if (stmt->dynquery != NULL)
2865 * This is an OPEN refcursor FOR EXECUTE ...
2874 * We evaluate the string expression after the
2875 * EXECUTE keyword. It's result is the querystring we have
2879 queryD = exec_eval_expr(estate, stmt->dynquery, &isnull, &restype);
2882 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2883 errmsg("cannot EXECUTE a null querystring")));
2885 /* Get the C-String representation */
2886 querystr = convert_value_to_string(queryD, restype);
2888 exec_eval_cleanup(estate);
2891 * Now we prepare a query plan for it and open a cursor
2894 curplan = SPI_prepare(querystr, 0, NULL);
2895 if (curplan == NULL)
2896 elog(ERROR, "SPI_prepare failed for \"%s\": %s",
2897 querystr, SPI_result_code_string(SPI_result));
2898 portal = SPI_cursor_open(curname, curplan, NULL, NULL,
2899 estate->readonly_func);
2901 elog(ERROR, "could not open cursor for query \"%s\": %s",
2902 querystr, SPI_result_code_string(SPI_result));
2904 SPI_freeplan(curplan);
2907 * Store the eventually assigned cursor name in the cursor variable
2911 curvar->value = DirectFunctionCall1(textin, CStringGetDatum(portal->name));
2912 curvar->isnull = false;
2913 curvar->freeval = true;
2915 return PLPGSQL_RC_OK;
2920 * This is an OPEN cursor
2922 * Note: parser should already have checked that statement supplies
2923 * args iff cursor needs them, but we check again to be safe.
2926 if (stmt->argquery != NULL)
2929 * OPEN CURSOR with args. We fake a SELECT ... INTO ...
2930 * statement to evaluate the args and put 'em into the
2934 PLpgSQL_stmt_execsql set_args;
2936 if (curvar->cursor_explicit_argrow < 0)
2938 (errcode(ERRCODE_SYNTAX_ERROR),
2939 errmsg("arguments given for cursor without arguments")));
2941 memset(&set_args, 0, sizeof(set_args));
2942 set_args.cmd_type = PLPGSQL_STMT_EXECSQL;
2943 set_args.lineno = stmt->lineno;
2944 set_args.sqlstmt = stmt->argquery;
2945 set_args.into = true;
2946 /* XXX historically this has not been STRICT */
2947 set_args.row = (PLpgSQL_row *)
2948 (estate->datums[curvar->cursor_explicit_argrow]);
2950 if (exec_stmt_execsql(estate, &set_args) != PLPGSQL_RC_OK)
2951 elog(ERROR, "open cursor failed during argument processing");
2955 if (curvar->cursor_explicit_argrow >= 0)
2957 (errcode(ERRCODE_SYNTAX_ERROR),
2958 errmsg("arguments required for cursor")));
2961 query = curvar->cursor_explicit_expr;
2962 if (query->plan == NULL)
2963 exec_prepare_plan(estate, query);
2967 * Here we go if we have a saved plan where we have to put
2968 * values into, either from an explicit cursor or from a
2969 * refcursor opened with OPEN ... FOR SELECT ...;
2972 values = (Datum *) palloc(query->nparams * sizeof(Datum));
2973 nulls = (char *) palloc(query->nparams * sizeof(char));
2975 for (i = 0; i < query->nparams; i++)
2977 PLpgSQL_datum *datum = estate->datums[query->params[i]];
2981 exec_eval_datum(estate, datum, query->plan_argtypes[i],
2982 ¶mtypeid, &values[i], ¶misnull);
2993 portal = SPI_cursor_open(curname, query->plan, values, nulls,
2994 estate->readonly_func);
2996 elog(ERROR, "could not open cursor: %s",
2997 SPI_result_code_string(SPI_result));
3005 * Store the eventually assigned portal name in the cursor variable
3009 curvar->value = DirectFunctionCall1(textin, CStringGetDatum(portal->name));
3010 curvar->isnull = false;
3011 curvar->freeval = true;
3013 return PLPGSQL_RC_OK;
3018 * exec_stmt_fetch Fetch from a cursor into a target
3022 exec_stmt_fetch(PLpgSQL_execstate *estate, PLpgSQL_stmt_fetch *stmt)
3024 PLpgSQL_var *curvar = NULL;
3025 PLpgSQL_rec *rec = NULL;
3026 PLpgSQL_row *row = NULL;
3027 SPITupleTable *tuptab;
3033 * Get the portal of the cursor by name
3036 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
3039 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3040 errmsg("cursor variable \"%s\" is NULL", curvar->refname)));
3041 curname = DatumGetCString(DirectFunctionCall1(textout, curvar->value));
3043 portal = SPI_cursor_find(curname);
3046 (errcode(ERRCODE_UNDEFINED_CURSOR),
3047 errmsg("cursor \"%s\" does not exist", curname)));
3051 * Determine if we fetch into a record or a row
3054 if (stmt->rec != NULL)
3055 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
3056 else if (stmt->row != NULL)
3057 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
3059 elog(ERROR, "unsupported target");
3062 * Fetch 1 tuple from the cursor
3065 SPI_cursor_fetch(portal, true, 1);
3066 tuptab = SPI_tuptable;
3070 * Set the target and the global FOUND variable appropriately.
3075 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
3076 exec_set_found(estate, false);
3080 exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
3081 exec_set_found(estate, true);
3084 SPI_freetuptable(tuptab);
3086 return PLPGSQL_RC_OK;
3091 * exec_stmt_close Close a cursor
3095 exec_stmt_close(PLpgSQL_execstate *estate, PLpgSQL_stmt_close *stmt)
3097 PLpgSQL_var *curvar = NULL;
3102 * Get the portal of the cursor by name
3105 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
3108 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3109 errmsg("cursor variable \"%s\" is NULL", curvar->refname)));
3110 curname = DatumGetCString(DirectFunctionCall1(textout, curvar->value));
3112 portal = SPI_cursor_find(curname);
3115 (errcode(ERRCODE_UNDEFINED_CURSOR),
3116 errmsg("cursor \"%s\" does not exist", curname)));
3123 SPI_cursor_close(portal);
3125 return PLPGSQL_RC_OK;
3130 * exec_assign_expr Put an expression's result into
3135 exec_assign_expr(PLpgSQL_execstate *estate, PLpgSQL_datum *target,
3140 bool isnull = false;
3142 value = exec_eval_expr(estate, expr, &isnull, &valtype);
3143 exec_assign_value(estate, target, value, valtype, &isnull);
3144 exec_eval_cleanup(estate);
3149 * exec_assign_value Put a value into a target field
3153 exec_assign_value(PLpgSQL_execstate *estate,
3154 PLpgSQL_datum *target,
3155 Datum value, Oid valtype, bool *isNull)
3157 switch (target->dtype)
3159 case PLPGSQL_DTYPE_VAR:
3162 * Target is a variable
3164 PLpgSQL_var *var = (PLpgSQL_var *) target;
3167 newvalue = exec_cast_value(value, valtype, var->datatype->typoid,
3168 &(var->datatype->typinput),
3169 var->datatype->typioparam,
3170 var->datatype->atttypmod,
3173 if (*isNull && var->notnull)
3175 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3176 errmsg("NULL cannot be assigned to variable \"%s\" declared NOT NULL",
3180 * If type is by-reference, make sure we have a freshly
3181 * palloc'd copy; the originally passed value may not live as
3182 * long as the variable! But we don't need to re-copy if
3183 * exec_cast_value performed a conversion; its output must
3184 * already be palloc'd.
3186 if (!var->datatype->typbyval && !*isNull)
3188 if (newvalue == value)
3189 newvalue = datumCopy(newvalue,
3191 var->datatype->typlen);
3195 * Now free the old value. (We can't do this any earlier
3196 * because of the possibility that we are assigning the var's
3197 * old value to it, eg "foo := foo". We could optimize out
3198 * the assignment altogether in such cases, but it's too
3199 * infrequent to be worth testing for.)
3203 var->value = newvalue;
3204 var->isnull = *isNull;
3205 if (!var->datatype->typbyval && !*isNull)
3206 var->freeval = true;
3210 case PLPGSQL_DTYPE_ROW:
3213 * Target is a row variable
3215 PLpgSQL_row *row = (PLpgSQL_row *) target;
3217 /* Source must be of RECORD or composite type */
3218 if (!(valtype == RECORDOID ||
3219 get_typtype(valtype) == 'c'))
3221 (errcode(ERRCODE_DATATYPE_MISMATCH),
3222 errmsg("cannot assign non-composite value to a row variable")));
3225 /* If source is null, just assign nulls to the row */
3226 exec_move_row(estate, NULL, row, NULL, NULL);
3234 HeapTupleData tmptup;
3236 /* Else source is a tuple Datum, safe to do this: */
3237 td = DatumGetHeapTupleHeader(value);
3238 /* Extract rowtype info and find a tupdesc */
3239 tupType = HeapTupleHeaderGetTypeId(td);
3240 tupTypmod = HeapTupleHeaderGetTypMod(td);
3241 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
3242 /* Build a temporary HeapTuple control structure */
3243 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
3244 ItemPointerSetInvalid(&(tmptup.t_self));
3245 tmptup.t_tableOid = InvalidOid;
3247 exec_move_row(estate, NULL, row, &tmptup, tupdesc);
3248 ReleaseTupleDesc(tupdesc);
3253 case PLPGSQL_DTYPE_REC:
3256 * Target is a record variable
3258 PLpgSQL_rec *rec = (PLpgSQL_rec *) target;
3260 /* Source must be of RECORD or composite type */
3261 if (!(valtype == RECORDOID ||
3262 get_typtype(valtype) == 'c'))
3264 (errcode(ERRCODE_DATATYPE_MISMATCH),
3265 errmsg("cannot assign non-composite value to a record variable")));
3268 /* If source is null, just assign nulls to the record */
3269 exec_move_row(estate, rec, NULL, NULL, NULL);
3277 HeapTupleData tmptup;
3279 /* Else source is a tuple Datum, safe to do this: */
3280 td = DatumGetHeapTupleHeader(value);
3281 /* Extract rowtype info and find a tupdesc */
3282 tupType = HeapTupleHeaderGetTypeId(td);
3283 tupTypmod = HeapTupleHeaderGetTypMod(td);
3284 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
3285 /* Build a temporary HeapTuple control structure */
3286 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
3287 ItemPointerSetInvalid(&(tmptup.t_self));
3288 tmptup.t_tableOid = InvalidOid;
3290 exec_move_row(estate, rec, NULL, &tmptup, tupdesc);
3291 ReleaseTupleDesc(tupdesc);
3296 case PLPGSQL_DTYPE_RECFIELD:
3299 * Target is a field of a record
3301 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) target;
3314 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
3317 * Check that there is already a tuple in the record. We need
3318 * that because records don't have any predefined field
3321 if (!HeapTupleIsValid(rec->tup))
3323 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3324 errmsg("record \"%s\" is not assigned yet",
3326 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
3329 * Get the number of the records field to change and the
3330 * number of attributes in the tuple.
3332 fno = SPI_fnumber(rec->tupdesc, recfield->fieldname);
3333 if (fno == SPI_ERROR_NOATTRIBUTE)
3335 (errcode(ERRCODE_UNDEFINED_COLUMN),
3336 errmsg("record \"%s\" has no field \"%s\"",
3337 rec->refname, recfield->fieldname)));
3339 natts = rec->tupdesc->natts;
3342 * Set up values/datums arrays for heap_formtuple. For all
3343 * the attributes except the one we want to replace, use the
3344 * value that's in the old tuple.
3346 values = palloc(sizeof(Datum) * natts);
3347 nulls = palloc(natts);
3349 for (i = 0; i < natts; i++)
3353 values[i] = SPI_getbinval(rec->tup, rec->tupdesc,
3362 * Now insert the new value, being careful to cast it to the
3365 atttype = SPI_gettypeid(rec->tupdesc, fno + 1);
3366 atttypmod = rec->tupdesc->attrs[fno]->atttypmod;
3367 attisnull = *isNull;
3368 values[fno] = exec_simple_cast_value(value,
3379 * Avoid leaking the result of exec_simple_cast_value, if it
3380 * performed a conversion to a pass-by-ref type.
3382 if (!attisnull && values[fno] != value && !get_typbyval(atttype))
3383 mustfree = DatumGetPointer(values[fno]);
3388 * Now call heap_formtuple() to create a new tuple that
3389 * replaces the old one in the record.
3391 newtup = heap_formtuple(rec->tupdesc, values, nulls);
3394 heap_freetuple(rec->tup);
3397 rec->freetup = true;
3407 case PLPGSQL_DTYPE_ARRAYELEM:
3411 PLpgSQL_expr *subscripts[MAXDIM];
3412 int subscriptvals[MAXDIM];
3413 bool oldarrayisnull;
3420 Datum oldarraydatum,
3422 ArrayType *oldarrayval;
3423 ArrayType *newarrayval;
3426 * Target is an element of an array
3428 * To handle constructs like x[1][2] := something, we have to
3429 * be prepared to deal with a chain of arrayelem datums. Chase
3430 * back to find the base array datum, and save the subscript
3431 * expressions as we go. (We are scanning right to left here,
3432 * but want to evaluate the subscripts left-to-right to
3433 * minimize surprises.)
3438 PLpgSQL_arrayelem *arrayelem = (PLpgSQL_arrayelem *) target;
3440 if (nsubscripts >= MAXDIM)
3442 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
3443 errmsg("number of array dimensions exceeds the maximum allowed, %d",
3445 subscripts[nsubscripts++] = arrayelem->subscript;
3446 target = estate->datums[arrayelem->arrayparentno];
3447 } while (target->dtype == PLPGSQL_DTYPE_ARRAYELEM);
3449 /* Fetch current value of array datum */
3450 exec_eval_datum(estate, target, InvalidOid,
3451 &arraytypeid, &oldarraydatum, &oldarrayisnull);
3453 arrayelemtypeid = get_element_type(arraytypeid);
3454 if (!OidIsValid(arrayelemtypeid))
3456 (errcode(ERRCODE_DATATYPE_MISMATCH),
3457 errmsg("subscripted object is not an array")));
3459 get_typlenbyvalalign(arrayelemtypeid,
3463 arraytyplen = get_typlen(arraytypeid);
3466 * Evaluate the subscripts, switch into left-to-right order.
3467 * Like ExecEvalArrayRef(), complain if any subscript is null.
3469 for (i = 0; i < nsubscripts; i++)
3474 exec_eval_integer(estate,
3475 subscripts[nsubscripts - 1 - i],
3479 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3480 errmsg("array subscript in assignment must not be NULL")));
3483 /* Coerce source value to match array element type. */
3484 coerced_value = exec_simple_cast_value(value,
3491 * If the original array is null, cons up an empty array so
3492 * that the assignment can proceed; we'll end with a
3493 * one-element array containing just the assigned-to
3494 * subscript. This only works for varlena arrays, though; for
3495 * fixed-length array types we skip the assignment. We can't
3496 * support assignment of a null entry into a fixed-length
3497 * array, either, so that's a no-op too. This is all ugly but
3498 * corresponds to the current behavior of ExecEvalArrayRef().
3500 if (arraytyplen > 0 && /* fixed-length array? */
3501 (oldarrayisnull || *isNull))
3505 oldarrayval = construct_empty_array(arrayelemtypeid);
3507 oldarrayval = (ArrayType *) DatumGetPointer(oldarraydatum);
3510 * Build the modified array value.
3512 newarrayval = array_set(oldarrayval,
3523 * Avoid leaking the result of exec_simple_cast_value, if it
3524 * performed a conversion to a pass-by-ref type.
3526 if (!*isNull && coerced_value != value && !elemtypbyval)
3527 pfree(DatumGetPointer(coerced_value));
3530 * Assign the new array to the base variable. It's never NULL
3534 exec_assign_value(estate, target,
3535 PointerGetDatum(newarrayval),
3536 arraytypeid, isNull);
3539 * Avoid leaking the modified array value, too.
3546 elog(ERROR, "unrecognized dtype: %d", target->dtype);
3551 * exec_eval_datum Get current value of a PLpgSQL_datum
3553 * The type oid, value in Datum format, and null flag are returned.
3555 * If expectedtypeid isn't InvalidOid, it is checked against the actual type.
3557 * At present this doesn't handle PLpgSQL_expr or PLpgSQL_arrayelem datums.
3559 * NOTE: caller must not modify the returned value, since it points right
3560 * at the stored value in the case of pass-by-reference datatypes. In some
3561 * cases we have to palloc a return value, and in such cases we put it into
3562 * the estate's short-term memory context.
3565 exec_eval_datum(PLpgSQL_execstate *estate,
3566 PLpgSQL_datum *datum,
3572 MemoryContext oldcontext;
3574 switch (datum->dtype)
3576 case PLPGSQL_DTYPE_VAR:
3578 PLpgSQL_var *var = (PLpgSQL_var *) datum;
3580 *typeid = var->datatype->typoid;
3581 *value = var->value;
3582 *isnull = var->isnull;
3583 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3585 (errcode(ERRCODE_DATATYPE_MISMATCH),
3586 errmsg("type of \"%s\" does not match that when preparing the plan",
3591 case PLPGSQL_DTYPE_ROW:
3593 PLpgSQL_row *row = (PLpgSQL_row *) datum;
3596 if (!row->rowtupdesc) /* should not happen */
3597 elog(ERROR, "row variable has no tupdesc");
3598 /* Make sure we have a valid type/typmod setting */
3599 BlessTupleDesc(row->rowtupdesc);
3600 oldcontext = MemoryContextSwitchTo(estate->eval_econtext->ecxt_per_tuple_memory);
3601 tup = make_tuple_from_row(estate, row, row->rowtupdesc);
3602 if (tup == NULL) /* should not happen */
3603 elog(ERROR, "row not compatible with its own tupdesc");
3604 MemoryContextSwitchTo(oldcontext);
3605 *typeid = row->rowtupdesc->tdtypeid;
3606 *value = HeapTupleGetDatum(tup);
3608 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3610 (errcode(ERRCODE_DATATYPE_MISMATCH),
3611 errmsg("type of \"%s\" does not match that when preparing the plan",
3616 case PLPGSQL_DTYPE_REC:
3618 PLpgSQL_rec *rec = (PLpgSQL_rec *) datum;
3619 HeapTupleData worktup;
3621 if (!HeapTupleIsValid(rec->tup))
3623 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3624 errmsg("record \"%s\" is not assigned yet",
3626 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
3627 Assert(rec->tupdesc != NULL);
3628 /* Make sure we have a valid type/typmod setting */
3629 BlessTupleDesc(rec->tupdesc);
3632 * In a trigger, the NEW and OLD parameters are likely to be
3633 * on-disk tuples that don't have the desired Datum fields.
3634 * Copy the tuple body and insert the right values.
3636 oldcontext = MemoryContextSwitchTo(estate->eval_econtext->ecxt_per_tuple_memory);
3637 heap_copytuple_with_tuple(rec->tup, &worktup);
3638 HeapTupleHeaderSetDatumLength(worktup.t_data, worktup.t_len);
3639 HeapTupleHeaderSetTypeId(worktup.t_data, rec->tupdesc->tdtypeid);
3640 HeapTupleHeaderSetTypMod(worktup.t_data, rec->tupdesc->tdtypmod);
3641 MemoryContextSwitchTo(oldcontext);
3642 *typeid = rec->tupdesc->tdtypeid;
3643 *value = HeapTupleGetDatum(&worktup);
3645 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3647 (errcode(ERRCODE_DATATYPE_MISMATCH),
3648 errmsg("type of \"%s\" does not match that when preparing the plan",
3653 case PLPGSQL_DTYPE_RECFIELD:
3655 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) datum;
3659 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
3660 if (!HeapTupleIsValid(rec->tup))
3662 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3663 errmsg("record \"%s\" is not assigned yet",
3665 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
3666 fno = SPI_fnumber(rec->tupdesc, recfield->fieldname);
3667 if (fno == SPI_ERROR_NOATTRIBUTE)
3669 (errcode(ERRCODE_UNDEFINED_COLUMN),
3670 errmsg("record \"%s\" has no field \"%s\"",
3671 rec->refname, recfield->fieldname)));
3672 *typeid = SPI_gettypeid(rec->tupdesc, fno);
3673 *value = SPI_getbinval(rec->tup, rec->tupdesc, fno, isnull);
3674 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3676 (errcode(ERRCODE_DATATYPE_MISMATCH),
3677 errmsg("type of \"%s.%s\" does not match that when preparing the plan",
3678 rec->refname, recfield->fieldname)));
3682 case PLPGSQL_DTYPE_TRIGARG:
3684 PLpgSQL_trigarg *trigarg = (PLpgSQL_trigarg *) datum;
3688 tgargno = exec_eval_integer(estate, trigarg->argnum, isnull);
3689 if (*isnull || tgargno < 0 || tgargno >= estate->trig_nargs)
3696 *value = estate->trig_argv[tgargno];
3699 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3701 (errcode(ERRCODE_DATATYPE_MISMATCH),
3702 errmsg("type of tgargv[%d] does not match that when preparing the plan",
3708 elog(ERROR, "unrecognized dtype: %d", datum->dtype);
3713 * exec_eval_integer Evaluate an expression, coerce result to int4
3715 * Note we do not do exec_eval_cleanup here; the caller must do it at
3716 * some later point. (We do this because the caller may be holding the
3717 * results of other, pass-by-reference, expression evaluations, such as
3718 * an array value to be subscripted. Also see notes in exec_eval_simple_expr
3719 * about allocation of the parameter array.)
3723 exec_eval_integer(PLpgSQL_execstate *estate,
3730 exprdatum = exec_eval_expr(estate, expr, isNull, &exprtypeid);
3731 exprdatum = exec_simple_cast_value(exprdatum, exprtypeid,
3734 return DatumGetInt32(exprdatum);
3738 * exec_eval_boolean Evaluate an expression, coerce result to bool
3740 * Note we do not do exec_eval_cleanup here; the caller must do it at
3745 exec_eval_boolean(PLpgSQL_execstate *estate,
3752 exprdatum = exec_eval_expr(estate, expr, isNull, &exprtypeid);
3753 exprdatum = exec_simple_cast_value(exprdatum, exprtypeid,
3756 return DatumGetBool(exprdatum);
3760 * exec_eval_expr Evaluate an expression and return
3763 * NOTE: caller must do exec_eval_cleanup when done with the Datum.
3767 exec_eval_expr(PLpgSQL_execstate *estate,
3775 * If not already done create a plan for this expression
3777 if (expr->plan == NULL)
3778 exec_prepare_plan(estate, expr);
3781 * If this is a simple expression, bypass SPI and use the executor
3784 if (expr->expr_simple_expr != NULL)
3785 return exec_eval_simple_expr(estate, expr, isNull, rettype);
3787 rc = exec_run_select(estate, expr, 2, NULL);
3788 if (rc != SPI_OK_SELECT)
3790 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3791 errmsg("query \"%s\" did not return data", expr->query)));
3794 * If there are no rows selected, the result is NULL.
3796 if (estate->eval_processed == 0)
3803 * Check that the expression returned one single Datum
3805 if (estate->eval_processed > 1)
3807 (errcode(ERRCODE_CARDINALITY_VIOLATION),
3808 errmsg("query \"%s\" returned more than one row",
3810 if (estate->eval_tuptable->tupdesc->natts != 1)
3812 (errcode(ERRCODE_SYNTAX_ERROR),
3813 errmsg("query \"%s\" returned %d columns", expr->query,
3814 estate->eval_tuptable->tupdesc->natts)));
3817 * Return the result and its type
3819 *rettype = SPI_gettypeid(estate->eval_tuptable->tupdesc, 1);
3820 return SPI_getbinval(estate->eval_tuptable->vals[0],
3821 estate->eval_tuptable->tupdesc, 1, isNull);
3826 * exec_run_select Execute a select query
3830 exec_run_select(PLpgSQL_execstate *estate,
3831 PLpgSQL_expr *expr, long maxtuples, Portal *portalP)
3839 * On the first call for this expression generate the plan
3841 if (expr->plan == NULL)
3842 exec_prepare_plan(estate, expr);
3845 * Now build up the values and nulls arguments for SPI_execute_plan()
3847 values = (Datum *) palloc(expr->nparams * sizeof(Datum));
3848 nulls = (char *) palloc(expr->nparams * sizeof(char));
3850 for (i = 0; i < expr->nparams; i++)
3852 PLpgSQL_datum *datum = estate->datums[expr->params[i]];
3856 exec_eval_datum(estate, datum, expr->plan_argtypes[i],
3857 ¶mtypeid, &values[i], ¶misnull);
3865 * If a portal was requested, put the query into the portal
3867 if (portalP != NULL)
3869 *portalP = SPI_cursor_open(NULL, expr->plan, values, nulls,
3870 estate->readonly_func);
3871 if (*portalP == NULL)
3872 elog(ERROR, "could not open implicit cursor for query \"%s\": %s",
3873 expr->query, SPI_result_code_string(SPI_result));
3876 return SPI_OK_CURSOR;
3882 rc = SPI_execute_plan(expr->plan, values, nulls,
3883 estate->readonly_func, maxtuples);
3884 if (rc != SPI_OK_SELECT)
3886 (errcode(ERRCODE_SYNTAX_ERROR),
3887 errmsg("query \"%s\" is not a SELECT", expr->query)));
3889 /* Save query results for eventual cleanup */
3890 Assert(estate->eval_tuptable == NULL);
3891 estate->eval_tuptable = SPI_tuptable;
3892 estate->eval_processed = SPI_processed;
3893 estate->eval_lastoid = SPI_lastoid;
3903 * exec_eval_simple_expr - Evaluate a simple expression returning
3904 * a Datum by directly calling ExecEvalExpr().
3906 * Note: if pass-by-reference, the result is in the eval_econtext's
3907 * temporary memory context. It will be freed when exec_eval_cleanup
3912 exec_eval_simple_expr(PLpgSQL_execstate *estate,
3918 ExprContext *econtext = estate->eval_econtext;
3919 TransactionId curxid = GetTopTransactionId();
3920 ParamListInfo paramLI;
3922 Snapshot saveActiveSnapshot;
3925 * Pass back previously-determined result type.
3927 *rettype = expr->expr_simple_type;
3930 * Prepare the expression for execution, if it's not been done already in
3931 * the current transaction.
3933 if (expr->expr_simple_xid != curxid)
3935 expr->expr_simple_state = ExecPrepareExpr(expr->expr_simple_expr,
3936 simple_eval_estate);
3937 expr->expr_simple_xid = curxid;
3941 * Param list can live in econtext's temporary memory context.
3943 * XXX think about avoiding repeated palloc's for param lists? Beware
3944 * however that this routine is re-entrant: exec_eval_datum() can call it
3945 * back for subscript evaluation, and so there can be a need to have more
3946 * than one active param list.
3948 if (expr->nparams > 0)
3950 /* sizeof(ParamListInfoData) includes the first array element */
3951 paramLI = (ParamListInfo)
3952 MemoryContextAlloc(econtext->ecxt_per_tuple_memory,
3953 sizeof(ParamListInfoData) +
3954 (expr->nparams - 1) * sizeof(ParamExternData));
3955 paramLI->numParams = expr->nparams;
3957 for (i = 0; i < expr->nparams; i++)
3959 ParamExternData *prm = ¶mLI->params[i];
3960 PLpgSQL_datum *datum = estate->datums[expr->params[i]];
3963 exec_eval_datum(estate, datum, expr->plan_argtypes[i],
3965 &prm->value, &prm->isnull);
3972 * Now we can safely make the econtext point to the param list.
3974 econtext->ecxt_param_list_info = paramLI;
3977 * We have to do some of the things SPI_execute_plan would do, in
3978 * particular advance the snapshot if we are in a non-read-only function.
3979 * Without this, stable functions within the expression would fail to see
3980 * updates made so far by our own function.
3983 saveActiveSnapshot = ActiveSnapshot;
3987 MemoryContext oldcontext;
3989 oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
3990 if (!estate->readonly_func)
3992 CommandCounterIncrement();
3993 ActiveSnapshot = CopySnapshot(GetTransactionSnapshot());
3997 * Finally we can call the executor to evaluate the expression
3999 retval = ExecEvalExpr(expr->expr_simple_state,
4003 MemoryContextSwitchTo(oldcontext);
4007 /* Restore global vars and propagate error */
4008 ActiveSnapshot = saveActiveSnapshot;
4013 ActiveSnapshot = saveActiveSnapshot;
4024 * exec_move_row Move one tuple's values into a record or row
4028 exec_move_row(PLpgSQL_execstate *estate,
4031 HeapTuple tup, TupleDesc tupdesc)
4034 * Record is simple - just copy the tuple and its descriptor into the
4040 * copy input first, just in case it is pointing at variable's value
4042 if (HeapTupleIsValid(tup))
4043 tup = heap_copytuple(tup);
4045 tupdesc = CreateTupleDescCopy(tupdesc);
4049 heap_freetuple(rec->tup);
4050 rec->freetup = false;
4052 if (rec->freetupdesc)
4054 FreeTupleDesc(rec->tupdesc);
4055 rec->freetupdesc = false;
4058 if (HeapTupleIsValid(tup))
4061 rec->freetup = true;
4065 /* If we have a tupdesc but no data, form an all-nulls tuple */
4068 nulls = (char *) palloc(tupdesc->natts * sizeof(char));
4069 memset(nulls, 'n', tupdesc->natts * sizeof(char));
4071 rec->tup = heap_formtuple(tupdesc, NULL, nulls);
4072 rec->freetup = true;
4081 rec->tupdesc = tupdesc;
4082 rec->freetupdesc = true;
4085 rec->tupdesc = NULL;
4091 * Row is a bit more complicated in that we assign the individual
4092 * attributes of the tuple to the variables the row points to.
4094 * NOTE: this code used to demand row->nfields == tup->t_data->t_natts,
4095 * but that's wrong. The tuple might have more fields than we expected if
4096 * it's from an inheritance-child table of the current table, or it might
4097 * have fewer if the table has had columns added by ALTER TABLE. Ignore
4098 * extra columns and assume NULL for missing columns, the same as
4099 * heap_getattr would do. We also have to skip over dropped columns in
4100 * either the source or destination.
4102 * If we have no tuple data at all, we'll assign NULL to all columns of
4111 if (HeapTupleIsValid(tup))
4112 t_natts = tup->t_data->t_natts;
4117 for (fnum = 0; fnum < row->nfields; fnum++)
4124 if (row->varnos[fnum] < 0)
4125 continue; /* skip dropped column in row struct */
4127 var = (PLpgSQL_var *) (estate->datums[row->varnos[fnum]]);
4129 while (anum < t_natts && tupdesc->attrs[anum]->attisdropped)
4130 anum++; /* skip dropped column in tuple */
4134 value = SPI_getbinval(tup, tupdesc, anum + 1, &isnull);
4135 valtype = SPI_gettypeid(tupdesc, anum + 1);
4142 valtype = InvalidOid;
4145 exec_assign_value(estate, (PLpgSQL_datum *) var,
4146 value, valtype, &isnull);
4152 elog(ERROR, "unsupported target");
4156 * make_tuple_from_row Make a tuple from the values of a row object
4158 * A NULL return indicates rowtype mismatch; caller must raise suitable error
4162 make_tuple_from_row(PLpgSQL_execstate *estate,
4166 int natts = tupdesc->natts;
4172 if (natts != row->nfields)
4175 dvalues = (Datum *) palloc0(natts * sizeof(Datum));
4176 nulls = (bool *) palloc(natts * sizeof(bool));
4178 for (i = 0; i < natts; i++)
4182 if (tupdesc->attrs[i]->attisdropped)
4184 nulls[i] = true; /* leave the column as null */
4187 if (row->varnos[i] < 0) /* should not happen */
4188 elog(ERROR, "dropped rowtype entry for non-dropped column");
4190 exec_eval_datum(estate, estate->datums[row->varnos[i]],
4191 InvalidOid, &fieldtypeid, &dvalues[i], &nulls[i]);
4192 if (fieldtypeid != tupdesc->attrs[i]->atttypid)
4196 tuple = heap_form_tuple(tupdesc, dvalues, nulls);
4205 * convert_value_to_string Convert a non-null Datum to C string
4207 * Note: callers generally assume that the result is a palloc'd string and
4208 * should be pfree'd. This is not all that safe an assumption ...
4210 * Note: not caching the conversion function lookup is bad for performance.
4214 convert_value_to_string(Datum value, Oid valtype)
4219 getTypeOutputInfo(valtype, &typoutput, &typIsVarlena);
4221 return OidOutputFunctionCall(typoutput, value);
4225 * exec_cast_value Cast a value if required
4229 exec_cast_value(Datum value, Oid valtype,
4237 * If the type of the queries return value isn't that of the variable,
4240 if (valtype != reqtype || reqtypmod != -1)
4246 extval = convert_value_to_string(value, valtype);
4247 value = InputFunctionCall(reqinput, extval,
4248 reqtypioparam, reqtypmod);
4253 value = InputFunctionCall(reqinput, NULL,
4254 reqtypioparam, reqtypmod);
4262 * exec_simple_cast_value Cast a value if required
4264 * As above, but need not supply details about target type. Note that this
4265 * is slower than exec_cast_value with cached type info, and so should be
4266 * avoided in heavily used code paths.
4270 exec_simple_cast_value(Datum value, Oid valtype,
4271 Oid reqtype, int32 reqtypmod,
4276 if (valtype != reqtype || reqtypmod != -1)
4280 FmgrInfo finfo_input;
4282 getTypeInputInfo(reqtype, &typinput, &typioparam);
4284 fmgr_info(typinput, &finfo_input);
4286 value = exec_cast_value(value,
4301 * exec_simple_check_node - Recursively check if an expression
4302 * is made only of simple things we can
4303 * hand out directly to ExecEvalExpr()
4304 * instead of calling SPI.
4308 exec_simple_check_node(Node *node)
4313 switch (nodeTag(node))
4323 ArrayRef *expr = (ArrayRef *) node;
4325 if (!exec_simple_check_node((Node *) expr->refupperindexpr))
4327 if (!exec_simple_check_node((Node *) expr->reflowerindexpr))
4329 if (!exec_simple_check_node((Node *) expr->refexpr))
4331 if (!exec_simple_check_node((Node *) expr->refassgnexpr))
4339 FuncExpr *expr = (FuncExpr *) node;
4341 if (expr->funcretset)
4343 if (!exec_simple_check_node((Node *) expr->args))
4351 OpExpr *expr = (OpExpr *) node;
4355 if (!exec_simple_check_node((Node *) expr->args))
4361 case T_DistinctExpr:
4363 DistinctExpr *expr = (DistinctExpr *) node;
4367 if (!exec_simple_check_node((Node *) expr->args))
4373 case T_ScalarArrayOpExpr:
4375 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
4377 if (!exec_simple_check_node((Node *) expr->args))
4385 BoolExpr *expr = (BoolExpr *) node;
4387 if (!exec_simple_check_node((Node *) expr->args))
4394 return exec_simple_check_node((Node *) ((FieldSelect *) node)->arg);
4398 FieldStore *expr = (FieldStore *) node;
4400 if (!exec_simple_check_node((Node *) expr->arg))
4402 if (!exec_simple_check_node((Node *) expr->newvals))
4409 return exec_simple_check_node((Node *) ((RelabelType *) node)->arg);
4411 case T_ConvertRowtypeExpr:
4412 return exec_simple_check_node((Node *) ((ConvertRowtypeExpr *) node)->arg);
4416 CaseExpr *expr = (CaseExpr *) node;
4418 if (!exec_simple_check_node((Node *) expr->arg))
4420 if (!exec_simple_check_node((Node *) expr->args))
4422 if (!exec_simple_check_node((Node *) expr->defresult))
4430 CaseWhen *when = (CaseWhen *) node;
4432 if (!exec_simple_check_node((Node *) when->expr))
4434 if (!exec_simple_check_node((Node *) when->result))
4440 case T_CaseTestExpr:
4445 ArrayExpr *expr = (ArrayExpr *) node;
4447 if (!exec_simple_check_node((Node *) expr->elements))
4455 RowExpr *expr = (RowExpr *) node;
4457 if (!exec_simple_check_node((Node *) expr->args))
4463 case T_RowCompareExpr:
4465 RowCompareExpr *expr = (RowCompareExpr *) node;
4467 if (!exec_simple_check_node((Node *) expr->largs))
4469 if (!exec_simple_check_node((Node *) expr->rargs))
4475 case T_CoalesceExpr:
4477 CoalesceExpr *expr = (CoalesceExpr *) node;
4479 if (!exec_simple_check_node((Node *) expr->args))
4487 MinMaxExpr *expr = (MinMaxExpr *) node;
4489 if (!exec_simple_check_node((Node *) expr->args))
4497 NullIfExpr *expr = (NullIfExpr *) node;
4501 if (!exec_simple_check_node((Node *) expr->args))
4508 return exec_simple_check_node((Node *) ((NullTest *) node)->arg);
4511 return exec_simple_check_node((Node *) ((BooleanTest *) node)->arg);
4513 case T_CoerceToDomain:
4514 return exec_simple_check_node((Node *) ((CoerceToDomain *) node)->arg);
4516 case T_CoerceToDomainValue:
4521 List *expr = (List *) node;
4526 if (!exec_simple_check_node(lfirst(l)))
4540 * exec_simple_check_plan - Check if a plan is simple enough to
4541 * be evaluated by ExecEvalExpr() instead
4546 exec_simple_check_plan(PLpgSQL_expr *expr)
4548 _SPI_plan *spi_plan = (_SPI_plan *) expr->plan;
4552 expr->expr_simple_expr = NULL;
4555 * 1. We can only evaluate queries that resulted in one single execution
4558 if (list_length(spi_plan->ptlist) != 1)
4561 plan = (Plan *) linitial(spi_plan->ptlist);
4564 * 2. It must be a RESULT plan --> no scan's required
4566 if (plan == NULL) /* utility statement produces this */
4569 if (!IsA(plan, Result))
4573 * 3. Can't have any subplan or qual clause, either
4575 if (plan->lefttree != NULL ||
4576 plan->righttree != NULL ||
4577 plan->initPlan != NULL ||
4578 plan->qual != NULL ||
4579 ((Result *) plan)->resconstantqual != NULL)
4583 * 4. The plan must have a single attribute as result
4585 if (list_length(plan->targetlist) != 1)
4588 tle = (TargetEntry *) linitial(plan->targetlist);
4591 * 5. Check that all the nodes in the expression are non-scary.
4593 if (!exec_simple_check_node((Node *) tle->expr))
4597 * Yes - this is a simple expression. Mark it as such, and initialize
4598 * state to "not valid in current transaction".
4600 expr->expr_simple_expr = tle->expr;
4601 expr->expr_simple_state = NULL;
4602 expr->expr_simple_xid = InvalidTransactionId;
4603 /* Also stash away the expression result type */
4604 expr->expr_simple_type = exprType((Node *) tle->expr);
4608 * Check two tupledescs have matching number and types of attributes
4611 compatible_tupdesc(TupleDesc td1, TupleDesc td2)
4615 if (td1->natts != td2->natts)
4618 for (i = 0; i < td1->natts; i++)
4620 if (td1->attrs[i]->atttypid != td2->attrs[i]->atttypid)
4628 * exec_set_found Set the global found variable
4633 exec_set_found(PLpgSQL_execstate *estate, bool state)
4637 var = (PLpgSQL_var *) (estate->datums[estate->found_varno]);
4638 var->value = (Datum) state;
4639 var->isnull = false;
4643 * plpgsql_xact_cb --- post-transaction-commit-or-abort cleanup
4645 * If a simple_eval_estate was created in the current transaction,
4646 * it has to be cleaned up.
4648 * XXX Do we need to do anything at subtransaction events?
4649 * Maybe subtransactions need to have their own simple_eval_estate?
4650 * It would get a lot messier, so for now let's assume we don't need that.
4653 plpgsql_xact_cb(XactEvent event, void *arg)
4656 * If we are doing a clean transaction shutdown, free the EState (so that
4657 * any remaining resources will be released correctly). In an abort, we
4658 * expect the regular abort recovery procedures to release everything of
4661 if (event == XACT_EVENT_COMMIT && simple_eval_estate)
4662 FreeExecutorState(simple_eval_estate);
4663 simple_eval_estate = NULL;
4667 free_var(PLpgSQL_var *var)
4671 pfree(DatumGetPointer(var->value));
4672 var->freeval = false;