1 /*-------------------------------------------------------------------------
3 * pl_exec.c - Executor for the PL/pgSQL
6 * Portions Copyright (c) 1996-2009, 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.247 2009/08/04 21:22:46 alvherre Exp $
13 *-------------------------------------------------------------------------
20 #include "access/transam.h"
21 #include "catalog/pg_proc.h"
22 #include "catalog/pg_type.h"
23 #include "executor/spi_priv.h"
25 #include "lib/stringinfo.h"
26 #include "miscadmin.h"
27 #include "nodes/nodeFuncs.h"
28 #include "parser/scansup.h"
29 #include "storage/proc.h"
30 #include "tcop/tcopprot.h"
31 #include "utils/array.h"
32 #include "utils/builtins.h"
33 #include "utils/datum.h"
34 #include "utils/lsyscache.h"
35 #include "utils/memutils.h"
36 #include "utils/snapmgr.h"
37 #include "utils/typcache.h"
40 static const char *const raise_skip_msg = "RAISE";
44 int nargs; /* number of arguments */
45 Oid *types; /* types of arguments */
46 Datum *values; /* evaluated argument values */
47 char *nulls; /* null markers (' '/'n' style) */
48 bool *freevals; /* which arguments are pfree-able */
52 * All plpgsql function executions within a single transaction share the same
53 * executor EState for evaluating "simple" expressions. Each function call
54 * creates its own "eval_econtext" ExprContext within this estate for
55 * per-evaluation workspace. eval_econtext is freed at normal function exit,
56 * and the EState is freed at transaction end (in case of error, we assume
57 * that the abort mechanisms clean it all up). Furthermore, any exception
58 * block within a function has to have its own eval_econtext separate from
59 * the containing function's, so that we can clean up ExprContext callbacks
60 * properly at subtransaction exit. We maintain a stack that tracks the
61 * individual econtexts so that we can clean up correctly at subxact exit.
63 * This arrangement is a bit tedious to maintain, but it's worth the trouble
64 * so that we don't have to re-prepare simple expressions on each trip through
65 * a function. (We assume the case to optimize is many repetitions of a
66 * function within a transaction.)
68 typedef struct SimpleEcontextStackEntry
70 ExprContext *stack_econtext; /* a stacked econtext */
71 SubTransactionId xact_subxid; /* ID for current subxact */
72 struct SimpleEcontextStackEntry *next; /* next stack entry up */
73 } SimpleEcontextStackEntry;
75 static EState *simple_eval_estate = NULL;
76 static SimpleEcontextStackEntry *simple_econtext_stack = NULL;
78 /************************************************************
79 * Local function forward declarations
80 ************************************************************/
81 static void plpgsql_exec_error_callback(void *arg);
82 static PLpgSQL_datum *copy_plpgsql_datum(PLpgSQL_datum *datum);
84 static int exec_stmt_block(PLpgSQL_execstate *estate,
85 PLpgSQL_stmt_block *block);
86 static int exec_stmts(PLpgSQL_execstate *estate,
88 static int exec_stmt(PLpgSQL_execstate *estate,
90 static int exec_stmt_assign(PLpgSQL_execstate *estate,
91 PLpgSQL_stmt_assign *stmt);
92 static int exec_stmt_perform(PLpgSQL_execstate *estate,
93 PLpgSQL_stmt_perform *stmt);
94 static int exec_stmt_getdiag(PLpgSQL_execstate *estate,
95 PLpgSQL_stmt_getdiag *stmt);
96 static int exec_stmt_if(PLpgSQL_execstate *estate,
97 PLpgSQL_stmt_if *stmt);
98 static int exec_stmt_case(PLpgSQL_execstate *estate,
99 PLpgSQL_stmt_case *stmt);
100 static int exec_stmt_loop(PLpgSQL_execstate *estate,
101 PLpgSQL_stmt_loop *stmt);
102 static int exec_stmt_while(PLpgSQL_execstate *estate,
103 PLpgSQL_stmt_while *stmt);
104 static int exec_stmt_fori(PLpgSQL_execstate *estate,
105 PLpgSQL_stmt_fori *stmt);
106 static int exec_stmt_fors(PLpgSQL_execstate *estate,
107 PLpgSQL_stmt_fors *stmt);
108 static int exec_stmt_forc(PLpgSQL_execstate *estate,
109 PLpgSQL_stmt_forc *stmt);
110 static int exec_stmt_open(PLpgSQL_execstate *estate,
111 PLpgSQL_stmt_open *stmt);
112 static int exec_stmt_fetch(PLpgSQL_execstate *estate,
113 PLpgSQL_stmt_fetch *stmt);
114 static int exec_stmt_close(PLpgSQL_execstate *estate,
115 PLpgSQL_stmt_close *stmt);
116 static int exec_stmt_exit(PLpgSQL_execstate *estate,
117 PLpgSQL_stmt_exit *stmt);
118 static int exec_stmt_return(PLpgSQL_execstate *estate,
119 PLpgSQL_stmt_return *stmt);
120 static int exec_stmt_return_next(PLpgSQL_execstate *estate,
121 PLpgSQL_stmt_return_next *stmt);
122 static int exec_stmt_return_query(PLpgSQL_execstate *estate,
123 PLpgSQL_stmt_return_query *stmt);
124 static int exec_stmt_raise(PLpgSQL_execstate *estate,
125 PLpgSQL_stmt_raise *stmt);
126 static int exec_stmt_execsql(PLpgSQL_execstate *estate,
127 PLpgSQL_stmt_execsql *stmt);
128 static int exec_stmt_dynexecute(PLpgSQL_execstate *estate,
129 PLpgSQL_stmt_dynexecute *stmt);
130 static int exec_stmt_dynfors(PLpgSQL_execstate *estate,
131 PLpgSQL_stmt_dynfors *stmt);
133 static void plpgsql_estate_setup(PLpgSQL_execstate *estate,
134 PLpgSQL_function *func,
136 static void exec_eval_cleanup(PLpgSQL_execstate *estate);
138 static void exec_prepare_plan(PLpgSQL_execstate *estate,
139 PLpgSQL_expr *expr, int cursorOptions);
140 static bool exec_simple_check_node(Node *node);
141 static void exec_simple_check_plan(PLpgSQL_expr *expr);
142 static bool exec_eval_simple_expr(PLpgSQL_execstate *estate,
148 static void exec_assign_expr(PLpgSQL_execstate *estate,
149 PLpgSQL_datum *target,
151 static void exec_assign_value(PLpgSQL_execstate *estate,
152 PLpgSQL_datum *target,
153 Datum value, Oid valtype, bool *isNull);
154 static void exec_eval_datum(PLpgSQL_execstate *estate,
155 PLpgSQL_datum *datum,
160 static int exec_eval_integer(PLpgSQL_execstate *estate,
163 static bool exec_eval_boolean(PLpgSQL_execstate *estate,
166 static Datum exec_eval_expr(PLpgSQL_execstate *estate,
170 static int exec_run_select(PLpgSQL_execstate *estate,
171 PLpgSQL_expr *expr, long maxtuples, Portal *portalP);
172 static int exec_for_query(PLpgSQL_execstate *estate, PLpgSQL_stmt_forq *stmt,
173 Portal portal, bool prefetch_ok);
174 static void eval_expr_params(PLpgSQL_execstate *estate,
175 PLpgSQL_expr *expr, Datum **p_values, char **p_nulls);
176 static void exec_move_row(PLpgSQL_execstate *estate,
179 HeapTuple tup, TupleDesc tupdesc);
180 static HeapTuple make_tuple_from_row(PLpgSQL_execstate *estate,
183 static char *convert_value_to_string(Datum value, Oid valtype);
184 static Datum exec_cast_value(Datum value, Oid valtype,
190 static Datum exec_simple_cast_value(Datum value, Oid valtype,
191 Oid reqtype, int32 reqtypmod,
193 static void exec_init_tuple_store(PLpgSQL_execstate *estate);
194 static void validate_tupdesc_compat(TupleDesc expected, TupleDesc returned,
196 static void exec_set_found(PLpgSQL_execstate *estate, bool state);
197 static void plpgsql_create_econtext(PLpgSQL_execstate *estate);
198 static void plpgsql_destroy_econtext(PLpgSQL_execstate *estate);
199 static void free_var(PLpgSQL_var *var);
200 static void assign_text_var(PLpgSQL_var *var, const char *str);
201 static PreparedParamsData *exec_eval_using_params(PLpgSQL_execstate *estate,
203 static void free_params_data(PreparedParamsData *ppd);
204 static Portal exec_dynquery_with_params(PLpgSQL_execstate *estate,
205 PLpgSQL_expr *query, List *params);
209 * plpgsql_exec_function Called by the call handler for
210 * function execution.
214 plpgsql_exec_function(PLpgSQL_function *func, FunctionCallInfo fcinfo)
216 PLpgSQL_execstate estate;
217 ErrorContextCallback plerrcontext;
222 * Setup the execution state
224 plpgsql_estate_setup(&estate, func, (ReturnSetInfo *) fcinfo->resultinfo);
227 * Setup error traceback support for ereport()
229 plerrcontext.callback = plpgsql_exec_error_callback;
230 plerrcontext.arg = &estate;
231 plerrcontext.previous = error_context_stack;
232 error_context_stack = &plerrcontext;
235 * Make local execution copies of all the datums
237 estate.err_text = gettext_noop("during initialization of execution state");
238 for (i = 0; i < estate.ndatums; i++)
239 estate.datums[i] = copy_plpgsql_datum(func->datums[i]);
242 * Store the actual call argument values into the appropriate variables
244 estate.err_text = gettext_noop("while storing call arguments into local variables");
245 for (i = 0; i < func->fn_nargs; i++)
247 int n = func->fn_argvarnos[i];
249 switch (estate.datums[n]->dtype)
251 case PLPGSQL_DTYPE_VAR:
253 PLpgSQL_var *var = (PLpgSQL_var *) estate.datums[n];
255 var->value = fcinfo->arg[i];
256 var->isnull = fcinfo->argnull[i];
257 var->freeval = false;
261 case PLPGSQL_DTYPE_ROW:
263 PLpgSQL_row *row = (PLpgSQL_row *) estate.datums[n];
265 if (!fcinfo->argnull[i])
271 HeapTupleData tmptup;
273 td = DatumGetHeapTupleHeader(fcinfo->arg[i]);
274 /* Extract rowtype info and find a tupdesc */
275 tupType = HeapTupleHeaderGetTypeId(td);
276 tupTypmod = HeapTupleHeaderGetTypMod(td);
277 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
278 /* Build a temporary HeapTuple control structure */
279 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
280 ItemPointerSetInvalid(&(tmptup.t_self));
281 tmptup.t_tableOid = InvalidOid;
283 exec_move_row(&estate, NULL, row, &tmptup, tupdesc);
284 ReleaseTupleDesc(tupdesc);
288 /* If arg is null, treat it as an empty row */
289 exec_move_row(&estate, NULL, row, NULL, NULL);
295 elog(ERROR, "unrecognized dtype: %d", func->datums[i]->dtype);
299 estate.err_text = gettext_noop("during function entry");
302 * Set the magic variable FOUND to false
304 exec_set_found(&estate, false);
307 * Let the instrumentation plugin peek at this function
309 if (*plugin_ptr && (*plugin_ptr)->func_beg)
310 ((*plugin_ptr)->func_beg) (&estate, func);
313 * Now call the toplevel block of statements
315 estate.err_text = NULL;
316 estate.err_stmt = (PLpgSQL_stmt *) (func->action);
317 rc = exec_stmt_block(&estate, func->action);
318 if (rc != PLPGSQL_RC_RETURN)
320 estate.err_stmt = NULL;
321 estate.err_text = NULL;
324 * Provide a more helpful message if a CONTINUE or RAISE has been used
325 * outside the context it can work in.
327 if (rc == PLPGSQL_RC_CONTINUE)
329 (errcode(ERRCODE_SYNTAX_ERROR),
330 errmsg("CONTINUE cannot be used outside a loop")));
331 else if (rc == PLPGSQL_RC_RERAISE)
333 (errcode(ERRCODE_SYNTAX_ERROR),
334 errmsg("RAISE without parameters cannot be used outside an exception handler")));
337 (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
338 errmsg("control reached end of function without RETURN")));
342 * We got a return value - process it
344 estate.err_stmt = NULL;
345 estate.err_text = gettext_noop("while casting return value to function's return type");
347 fcinfo->isnull = estate.retisnull;
351 ReturnSetInfo *rsi = estate.rsi;
353 /* Check caller can handle a set result */
354 if (!rsi || !IsA(rsi, ReturnSetInfo) ||
355 (rsi->allowedModes & SFRM_Materialize) == 0)
357 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
358 errmsg("set-valued function called in context that cannot accept a set")));
359 rsi->returnMode = SFRM_Materialize;
361 /* If we produced any tuples, send back the result */
362 if (estate.tuple_store)
364 rsi->setResult = estate.tuple_store;
365 if (estate.rettupdesc)
367 MemoryContext oldcxt;
369 oldcxt = MemoryContextSwitchTo(estate.tuple_store_cxt);
370 rsi->setDesc = CreateTupleDescCopy(estate.rettupdesc);
371 MemoryContextSwitchTo(oldcxt);
374 estate.retval = (Datum) 0;
375 fcinfo->isnull = true;
377 else if (!estate.retisnull)
379 if (estate.retistuple)
382 * We have to check that the returned tuple actually matches the
383 * expected result type. XXX would be better to cache the tupdesc
384 * instead of repeating get_call_result_type()
388 switch (get_call_result_type(fcinfo, NULL, &tupdesc))
390 case TYPEFUNC_COMPOSITE:
391 /* got the expected result rowtype, now check it */
392 validate_tupdesc_compat(tupdesc, estate.rettupdesc,
393 "returned record type does not match expected record type");
395 case TYPEFUNC_RECORD:
398 * Failed to determine actual type of RECORD. We could
399 * raise an error here, but what this means in practice is
400 * that the caller is expecting any old generic rowtype,
401 * so we don't really need to be restrictive. Pass back
402 * the generated result type, instead.
404 tupdesc = estate.rettupdesc;
405 if (tupdesc == NULL) /* shouldn't happen */
406 elog(ERROR, "return type must be a row type");
409 /* shouldn't get here if retistuple is true ... */
410 elog(ERROR, "return type must be a row type");
415 * Copy tuple to upper executor memory, as a tuple Datum. Make
416 * sure it is labeled with the caller-supplied tuple type.
419 PointerGetDatum(SPI_returntuple((HeapTuple) DatumGetPointer(estate.retval),
424 /* Cast value to proper type */
425 estate.retval = exec_cast_value(estate.retval, estate.rettype,
427 &(func->fn_retinput),
428 func->fn_rettypioparam,
433 * If the function's return type isn't by value, copy the value
434 * into upper executor memory context.
436 if (!fcinfo->isnull && !func->fn_retbyval)
441 len = datumGetSize(estate.retval, false, func->fn_rettyplen);
442 tmp = SPI_palloc(len);
443 memcpy(tmp, DatumGetPointer(estate.retval), len);
444 estate.retval = PointerGetDatum(tmp);
449 estate.err_text = gettext_noop("during function exit");
452 * Let the instrumentation plugin peek at this function
454 if (*plugin_ptr && (*plugin_ptr)->func_end)
455 ((*plugin_ptr)->func_end) (&estate, func);
457 /* Clean up any leftover temporary memory */
458 plpgsql_destroy_econtext(&estate);
459 exec_eval_cleanup(&estate);
462 * Pop the error context stack
464 error_context_stack = plerrcontext.previous;
467 * Return the function's result
469 return estate.retval;
474 * plpgsql_exec_trigger Called by the call handler for
479 plpgsql_exec_trigger(PLpgSQL_function *func,
480 TriggerData *trigdata)
482 PLpgSQL_execstate estate;
483 ErrorContextCallback plerrcontext;
487 PLpgSQL_rec *rec_new,
492 * Setup the execution state
494 plpgsql_estate_setup(&estate, func, NULL);
497 * Setup error traceback support for ereport()
499 plerrcontext.callback = plpgsql_exec_error_callback;
500 plerrcontext.arg = &estate;
501 plerrcontext.previous = error_context_stack;
502 error_context_stack = &plerrcontext;
505 * Make local execution copies of all the datums
507 estate.err_text = gettext_noop("during initialization of execution state");
508 for (i = 0; i < estate.ndatums; i++)
509 estate.datums[i] = copy_plpgsql_datum(func->datums[i]);
512 * Put the OLD and NEW tuples into record variables
514 rec_new = (PLpgSQL_rec *) (estate.datums[func->new_varno]);
515 rec_new->freetup = false;
516 rec_new->freetupdesc = false;
517 rec_old = (PLpgSQL_rec *) (estate.datums[func->old_varno]);
518 rec_old->freetup = false;
519 rec_old->freetupdesc = false;
521 if (TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
524 * Per-statement triggers don't use OLD/NEW variables
527 rec_new->tupdesc = NULL;
529 rec_old->tupdesc = NULL;
531 else if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
533 rec_new->tup = trigdata->tg_trigtuple;
534 rec_new->tupdesc = trigdata->tg_relation->rd_att;
536 rec_old->tupdesc = NULL;
538 else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
540 rec_new->tup = trigdata->tg_newtuple;
541 rec_new->tupdesc = trigdata->tg_relation->rd_att;
542 rec_old->tup = trigdata->tg_trigtuple;
543 rec_old->tupdesc = trigdata->tg_relation->rd_att;
545 else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
548 rec_new->tupdesc = NULL;
549 rec_old->tup = trigdata->tg_trigtuple;
550 rec_old->tupdesc = trigdata->tg_relation->rd_att;
553 elog(ERROR, "unrecognized trigger action: not INSERT, DELETE, or UPDATE");
556 * Assign the special tg_ variables
559 var = (PLpgSQL_var *) (estate.datums[func->tg_op_varno]);
560 if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
561 var->value = CStringGetTextDatum("INSERT");
562 else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
563 var->value = CStringGetTextDatum("UPDATE");
564 else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
565 var->value = CStringGetTextDatum("DELETE");
566 else if (TRIGGER_FIRED_BY_TRUNCATE(trigdata->tg_event))
567 var->value = CStringGetTextDatum("TRUNCATE");
569 elog(ERROR, "unrecognized trigger action: not INSERT, DELETE, UPDATE, or TRUNCATE");
573 var = (PLpgSQL_var *) (estate.datums[func->tg_name_varno]);
574 var->value = DirectFunctionCall1(namein,
575 CStringGetDatum(trigdata->tg_trigger->tgname));
579 var = (PLpgSQL_var *) (estate.datums[func->tg_when_varno]);
580 if (TRIGGER_FIRED_BEFORE(trigdata->tg_event))
581 var->value = CStringGetTextDatum("BEFORE");
582 else if (TRIGGER_FIRED_AFTER(trigdata->tg_event))
583 var->value = CStringGetTextDatum("AFTER");
585 elog(ERROR, "unrecognized trigger execution time: not BEFORE or AFTER");
589 var = (PLpgSQL_var *) (estate.datums[func->tg_level_varno]);
590 if (TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
591 var->value = CStringGetTextDatum("ROW");
592 else if (TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
593 var->value = CStringGetTextDatum("STATEMENT");
595 elog(ERROR, "unrecognized trigger event type: not ROW or STATEMENT");
599 var = (PLpgSQL_var *) (estate.datums[func->tg_relid_varno]);
600 var->value = ObjectIdGetDatum(trigdata->tg_relation->rd_id);
602 var->freeval = false;
604 var = (PLpgSQL_var *) (estate.datums[func->tg_relname_varno]);
605 var->value = DirectFunctionCall1(namein,
606 CStringGetDatum(RelationGetRelationName(trigdata->tg_relation)));
610 var = (PLpgSQL_var *) (estate.datums[func->tg_table_name_varno]);
611 var->value = DirectFunctionCall1(namein,
612 CStringGetDatum(RelationGetRelationName(trigdata->tg_relation)));
616 var = (PLpgSQL_var *) (estate.datums[func->tg_table_schema_varno]);
617 var->value = DirectFunctionCall1(namein,
620 RelationGetNamespace(
621 trigdata->tg_relation))));
625 var = (PLpgSQL_var *) (estate.datums[func->tg_nargs_varno]);
626 var->value = Int16GetDatum(trigdata->tg_trigger->tgnargs);
628 var->freeval = false;
631 * Store the trigger argument values into the special execution state
634 estate.err_text = gettext_noop("while storing call arguments into local variables");
635 estate.trig_nargs = trigdata->tg_trigger->tgnargs;
636 if (estate.trig_nargs == 0)
637 estate.trig_argv = NULL;
640 estate.trig_argv = palloc(sizeof(Datum) * estate.trig_nargs);
641 for (i = 0; i < trigdata->tg_trigger->tgnargs; i++)
642 estate.trig_argv[i] = CStringGetTextDatum(trigdata->tg_trigger->tgargs[i]);
645 estate.err_text = gettext_noop("during function entry");
648 * Set the magic variable FOUND to false
650 exec_set_found(&estate, false);
653 * Let the instrumentation plugin peek at this function
655 if (*plugin_ptr && (*plugin_ptr)->func_beg)
656 ((*plugin_ptr)->func_beg) (&estate, func);
659 * Now call the toplevel block of statements
661 estate.err_text = NULL;
662 estate.err_stmt = (PLpgSQL_stmt *) (func->action);
663 rc = exec_stmt_block(&estate, func->action);
664 if (rc != PLPGSQL_RC_RETURN)
666 estate.err_stmt = NULL;
667 estate.err_text = NULL;
670 * Provide a more helpful message if a CONTINUE or RAISE has been used
671 * outside the context it can work in.
673 if (rc == PLPGSQL_RC_CONTINUE)
675 (errcode(ERRCODE_SYNTAX_ERROR),
676 errmsg("CONTINUE cannot be used outside a loop")));
677 else if (rc == PLPGSQL_RC_RERAISE)
679 (errcode(ERRCODE_SYNTAX_ERROR),
680 errmsg("RAISE without parameters cannot be used outside an exception handler")));
683 (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
684 errmsg("control reached end of trigger procedure without RETURN")));
687 estate.err_stmt = NULL;
688 estate.err_text = gettext_noop("during function exit");
692 (errcode(ERRCODE_DATATYPE_MISMATCH),
693 errmsg("trigger procedure cannot return a set")));
696 * Check that the returned tuple structure has the same attributes, the
697 * relation that fired the trigger has. A per-statement trigger always
698 * needs to return NULL, so we ignore any return value the function itself
699 * produces (XXX: is this a good idea?)
701 * XXX This way it is possible, that the trigger returns a tuple where
702 * attributes don't have the correct atttypmod's length. It's up to the
703 * trigger's programmer to ensure that this doesn't happen. Jan
705 if (estate.retisnull || TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
709 validate_tupdesc_compat(trigdata->tg_relation->rd_att,
711 "returned row structure does not match the structure of the triggering table");
712 /* Copy tuple to upper executor memory */
713 rettup = SPI_copytuple((HeapTuple) DatumGetPointer(estate.retval));
717 * Let the instrumentation plugin peek at this function
719 if (*plugin_ptr && (*plugin_ptr)->func_end)
720 ((*plugin_ptr)->func_end) (&estate, func);
722 /* Clean up any leftover temporary memory */
723 plpgsql_destroy_econtext(&estate);
724 exec_eval_cleanup(&estate);
727 * Pop the error context stack
729 error_context_stack = plerrcontext.previous;
732 * Return the trigger's result
739 * error context callback to let us supply a call-stack traceback
742 plpgsql_exec_error_callback(void *arg)
744 PLpgSQL_execstate *estate = (PLpgSQL_execstate *) arg;
746 /* safety check, shouldn't happen */
747 if (estate->err_func == NULL)
750 /* if we are doing RAISE, don't report its location */
751 if (estate->err_text == raise_skip_msg)
754 if (estate->err_text != NULL)
757 * We don't expend the cycles to run gettext() on err_text unless we
758 * actually need it. Therefore, places that set up err_text should
759 * use gettext_noop() to ensure the strings get recorded in the
760 * message dictionary.
762 * If both err_text and err_stmt are set, use the err_text as
763 * description, but report the err_stmt's line number. When err_stmt
764 * is not set, we're in function entry/exit, or some such place not
765 * attached to a specific line number.
767 if (estate->err_stmt != NULL)
770 * translator: last %s is a phrase such as "during statement block
771 * local variable initialization"
773 errcontext("PL/pgSQL function \"%s\" line %d %s",
774 estate->err_func->fn_name,
775 estate->err_stmt->lineno,
776 _(estate->err_text));
781 * translator: last %s is a phrase such as "while storing call
782 * arguments into local variables"
784 errcontext("PL/pgSQL function \"%s\" %s",
785 estate->err_func->fn_name,
786 _(estate->err_text));
789 else if (estate->err_stmt != NULL)
791 /* translator: last %s is a plpgsql statement type name */
792 errcontext("PL/pgSQL function \"%s\" line %d at %s",
793 estate->err_func->fn_name,
794 estate->err_stmt->lineno,
795 plpgsql_stmt_typename(estate->err_stmt));
798 errcontext("PL/pgSQL function \"%s\"",
799 estate->err_func->fn_name);
804 * Support function for initializing local execution variables
807 static PLpgSQL_datum *
808 copy_plpgsql_datum(PLpgSQL_datum *datum)
810 PLpgSQL_datum *result;
812 switch (datum->dtype)
814 case PLPGSQL_DTYPE_VAR:
816 PLpgSQL_var *new = palloc(sizeof(PLpgSQL_var));
818 memcpy(new, datum, sizeof(PLpgSQL_var));
819 /* Ensure the value is null (possibly not needed?) */
822 new->freeval = false;
824 result = (PLpgSQL_datum *) new;
828 case PLPGSQL_DTYPE_REC:
830 PLpgSQL_rec *new = palloc(sizeof(PLpgSQL_rec));
832 memcpy(new, datum, sizeof(PLpgSQL_rec));
833 /* Ensure the value is null (possibly not needed?) */
836 new->freetup = false;
837 new->freetupdesc = false;
839 result = (PLpgSQL_datum *) new;
843 case PLPGSQL_DTYPE_ROW:
844 case PLPGSQL_DTYPE_RECFIELD:
845 case PLPGSQL_DTYPE_ARRAYELEM:
846 case PLPGSQL_DTYPE_TRIGARG:
849 * These datum records are read-only at runtime, so no need to
856 elog(ERROR, "unrecognized dtype: %d", datum->dtype);
857 result = NULL; /* keep compiler quiet */
866 exception_matches_conditions(ErrorData *edata, PLpgSQL_condition *cond)
868 for (; cond != NULL; cond = cond->next)
870 int sqlerrstate = cond->sqlerrstate;
873 * OTHERS matches everything *except* query-canceled; if you're
874 * foolish enough, you can match that explicitly.
876 if (sqlerrstate == 0)
878 if (edata->sqlerrcode != ERRCODE_QUERY_CANCELED)
882 else if (edata->sqlerrcode == sqlerrstate)
884 /* Category match? */
885 else if (ERRCODE_IS_CATEGORY(sqlerrstate) &&
886 ERRCODE_TO_CATEGORY(edata->sqlerrcode) == sqlerrstate)
894 * exec_stmt_block Execute a block of statements
898 exec_stmt_block(PLpgSQL_execstate *estate, PLpgSQL_stmt_block *block)
900 volatile int rc = -1;
905 * First initialize all variables declared in this block
907 estate->err_text = gettext_noop("during statement block local variable initialization");
909 for (i = 0; i < block->n_initvars; i++)
911 n = block->initvarnos[i];
913 switch (estate->datums[n]->dtype)
915 case PLPGSQL_DTYPE_VAR:
917 PLpgSQL_var *var = (PLpgSQL_var *) (estate->datums[n]);
919 /* free any old value, in case re-entering block */
922 /* Initially it contains a NULL */
923 var->value = (Datum) 0;
926 if (var->default_val == NULL)
929 * If needed, give the datatype a chance to reject
930 * NULLs, by assigning a NULL to the variable. We
931 * claim the value is of type UNKNOWN, not the var's
932 * datatype, else coercion will be skipped. (Do this
933 * before the notnull check to be consistent with
934 * exec_assign_value.)
936 if (!var->datatype->typinput.fn_strict)
938 bool valIsNull = true;
940 exec_assign_value(estate,
941 (PLpgSQL_datum *) var,
948 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
949 errmsg("variable \"%s\" declared NOT NULL cannot default to NULL",
954 exec_assign_expr(estate, (PLpgSQL_datum *) var,
960 case PLPGSQL_DTYPE_REC:
962 PLpgSQL_rec *rec = (PLpgSQL_rec *) (estate->datums[n]);
966 heap_freetuple(rec->tup);
967 FreeTupleDesc(rec->tupdesc);
968 rec->freetup = false;
976 case PLPGSQL_DTYPE_RECFIELD:
977 case PLPGSQL_DTYPE_ARRAYELEM:
981 elog(ERROR, "unrecognized dtype: %d",
982 estate->datums[n]->dtype);
986 if (block->exceptions)
989 * Execute the statements in the block's body inside a sub-transaction
991 MemoryContext oldcontext = CurrentMemoryContext;
992 ResourceOwner oldowner = CurrentResourceOwner;
993 ExprContext *old_eval_econtext = estate->eval_econtext;
995 estate->err_text = gettext_noop("during statement block entry");
997 BeginInternalSubTransaction(NULL);
998 /* Want to run statements inside function's memory context */
999 MemoryContextSwitchTo(oldcontext);
1004 * We need to run the block's statements with a new eval_econtext
1005 * that belongs to the current subtransaction; if we try to use
1006 * the outer econtext then ExprContext shutdown callbacks will be
1007 * called at the wrong times.
1009 plpgsql_create_econtext(estate);
1011 estate->err_text = NULL;
1013 /* Run the block's statements */
1014 rc = exec_stmts(estate, block->body);
1016 estate->err_text = gettext_noop("during statement block exit");
1019 * If the block ended with RETURN, we may need to copy the return
1020 * value out of the subtransaction eval_context. This is
1021 * currently only needed for scalar result types --- rowtype
1022 * values will always exist in the function's own memory context.
1024 if (rc == PLPGSQL_RC_RETURN &&
1025 !estate->retisset &&
1026 !estate->retisnull &&
1027 estate->rettupdesc == NULL)
1032 get_typlenbyval(estate->rettype, &resTypLen, &resTypByVal);
1033 estate->retval = datumCopy(estate->retval,
1034 resTypByVal, resTypLen);
1037 /* Commit the inner transaction, return to outer xact context */
1038 ReleaseCurrentSubTransaction();
1039 MemoryContextSwitchTo(oldcontext);
1040 CurrentResourceOwner = oldowner;
1043 * Revert to outer eval_econtext. (The inner one was
1044 * automatically cleaned up during subxact exit.)
1046 estate->eval_econtext = old_eval_econtext;
1049 * AtEOSubXact_SPI() should not have popped any SPI context, but
1050 * just in case it did, make sure we remain connected.
1052 SPI_restore_connection();
1059 estate->err_text = gettext_noop("during exception cleanup");
1061 /* Save error info */
1062 MemoryContextSwitchTo(oldcontext);
1063 edata = CopyErrorData();
1066 /* Abort the inner transaction */
1067 RollbackAndReleaseCurrentSubTransaction();
1068 MemoryContextSwitchTo(oldcontext);
1069 CurrentResourceOwner = oldowner;
1071 /* Revert to outer eval_econtext */
1072 estate->eval_econtext = old_eval_econtext;
1075 * If AtEOSubXact_SPI() popped any SPI context of the subxact, it
1076 * will have left us in a disconnected state. We need this hack
1077 * to return to connected state.
1079 SPI_restore_connection();
1081 /* Look for a matching exception handler */
1082 foreach(e, block->exceptions->exc_list)
1084 PLpgSQL_exception *exception = (PLpgSQL_exception *) lfirst(e);
1086 if (exception_matches_conditions(edata, exception->conditions))
1089 * Initialize the magic SQLSTATE and SQLERRM variables for
1090 * the exception block. We needn't do this until we have
1091 * found a matching exception.
1093 PLpgSQL_var *state_var;
1094 PLpgSQL_var *errm_var;
1096 state_var = (PLpgSQL_var *)
1097 estate->datums[block->exceptions->sqlstate_varno];
1098 errm_var = (PLpgSQL_var *)
1099 estate->datums[block->exceptions->sqlerrm_varno];
1101 assign_text_var(state_var,
1102 unpack_sql_state(edata->sqlerrcode));
1103 assign_text_var(errm_var, edata->message);
1105 estate->err_text = NULL;
1107 rc = exec_stmts(estate, exception->action);
1109 free_var(state_var);
1110 state_var->value = (Datum) 0;
1111 state_var->isnull = true;
1113 errm_var->value = (Datum) 0;
1114 errm_var->isnull = true;
1116 /* re-throw error if requested by handler */
1117 if (rc == PLPGSQL_RC_RERAISE)
1118 ReThrowError(edata);
1124 /* If no match found, re-throw the error */
1126 ReThrowError(edata);
1128 FreeErrorData(edata);
1135 * Just execute the statements in the block's body
1137 estate->err_text = NULL;
1139 rc = exec_stmts(estate, block->body);
1142 estate->err_text = NULL;
1145 * Handle the return code.
1150 case PLPGSQL_RC_RETURN:
1151 case PLPGSQL_RC_CONTINUE:
1152 case PLPGSQL_RC_RERAISE:
1155 case PLPGSQL_RC_EXIT:
1158 * This is intentionally different from the handling of RC_EXIT
1159 * for loops: to match a block, we require a match by label.
1161 if (estate->exitlabel == NULL)
1162 return PLPGSQL_RC_EXIT;
1163 if (block->label == NULL)
1164 return PLPGSQL_RC_EXIT;
1165 if (strcmp(block->label, estate->exitlabel) != 0)
1166 return PLPGSQL_RC_EXIT;
1167 estate->exitlabel = NULL;
1168 return PLPGSQL_RC_OK;
1171 elog(ERROR, "unrecognized rc: %d", rc);
1174 return PLPGSQL_RC_OK;
1179 * exec_stmts Iterate over a list of statements
1180 * as long as their return code is OK
1184 exec_stmts(PLpgSQL_execstate *estate, List *stmts)
1191 * Ensure we do a CHECK_FOR_INTERRUPTS() even though there is no
1192 * statement. This prevents hangup in a tight loop if, for instance,
1193 * there is a LOOP construct with an empty body.
1195 CHECK_FOR_INTERRUPTS();
1196 return PLPGSQL_RC_OK;
1201 PLpgSQL_stmt *stmt = (PLpgSQL_stmt *) lfirst(s);
1202 int rc = exec_stmt(estate, stmt);
1204 if (rc != PLPGSQL_RC_OK)
1208 return PLPGSQL_RC_OK;
1213 * exec_stmt Distribute one statement to the statements
1214 * type specific execution function.
1218 exec_stmt(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
1220 PLpgSQL_stmt *save_estmt;
1223 save_estmt = estate->err_stmt;
1224 estate->err_stmt = stmt;
1226 /* Let the plugin know that we are about to execute this statement */
1227 if (*plugin_ptr && (*plugin_ptr)->stmt_beg)
1228 ((*plugin_ptr)->stmt_beg) (estate, stmt);
1230 CHECK_FOR_INTERRUPTS();
1232 switch ((enum PLpgSQL_stmt_types) stmt->cmd_type)
1234 case PLPGSQL_STMT_BLOCK:
1235 rc = exec_stmt_block(estate, (PLpgSQL_stmt_block *) stmt);
1238 case PLPGSQL_STMT_ASSIGN:
1239 rc = exec_stmt_assign(estate, (PLpgSQL_stmt_assign *) stmt);
1242 case PLPGSQL_STMT_PERFORM:
1243 rc = exec_stmt_perform(estate, (PLpgSQL_stmt_perform *) stmt);
1246 case PLPGSQL_STMT_GETDIAG:
1247 rc = exec_stmt_getdiag(estate, (PLpgSQL_stmt_getdiag *) stmt);
1250 case PLPGSQL_STMT_IF:
1251 rc = exec_stmt_if(estate, (PLpgSQL_stmt_if *) stmt);
1254 case PLPGSQL_STMT_CASE:
1255 rc = exec_stmt_case(estate, (PLpgSQL_stmt_case *) stmt);
1258 case PLPGSQL_STMT_LOOP:
1259 rc = exec_stmt_loop(estate, (PLpgSQL_stmt_loop *) stmt);
1262 case PLPGSQL_STMT_WHILE:
1263 rc = exec_stmt_while(estate, (PLpgSQL_stmt_while *) stmt);
1266 case PLPGSQL_STMT_FORI:
1267 rc = exec_stmt_fori(estate, (PLpgSQL_stmt_fori *) stmt);
1270 case PLPGSQL_STMT_FORS:
1271 rc = exec_stmt_fors(estate, (PLpgSQL_stmt_fors *) stmt);
1274 case PLPGSQL_STMT_FORC:
1275 rc = exec_stmt_forc(estate, (PLpgSQL_stmt_forc *) stmt);
1278 case PLPGSQL_STMT_EXIT:
1279 rc = exec_stmt_exit(estate, (PLpgSQL_stmt_exit *) stmt);
1282 case PLPGSQL_STMT_RETURN:
1283 rc = exec_stmt_return(estate, (PLpgSQL_stmt_return *) stmt);
1286 case PLPGSQL_STMT_RETURN_NEXT:
1287 rc = exec_stmt_return_next(estate, (PLpgSQL_stmt_return_next *) stmt);
1290 case PLPGSQL_STMT_RETURN_QUERY:
1291 rc = exec_stmt_return_query(estate, (PLpgSQL_stmt_return_query *) stmt);
1294 case PLPGSQL_STMT_RAISE:
1295 rc = exec_stmt_raise(estate, (PLpgSQL_stmt_raise *) stmt);
1298 case PLPGSQL_STMT_EXECSQL:
1299 rc = exec_stmt_execsql(estate, (PLpgSQL_stmt_execsql *) stmt);
1302 case PLPGSQL_STMT_DYNEXECUTE:
1303 rc = exec_stmt_dynexecute(estate, (PLpgSQL_stmt_dynexecute *) stmt);
1306 case PLPGSQL_STMT_DYNFORS:
1307 rc = exec_stmt_dynfors(estate, (PLpgSQL_stmt_dynfors *) stmt);
1310 case PLPGSQL_STMT_OPEN:
1311 rc = exec_stmt_open(estate, (PLpgSQL_stmt_open *) stmt);
1314 case PLPGSQL_STMT_FETCH:
1315 rc = exec_stmt_fetch(estate, (PLpgSQL_stmt_fetch *) stmt);
1318 case PLPGSQL_STMT_CLOSE:
1319 rc = exec_stmt_close(estate, (PLpgSQL_stmt_close *) stmt);
1323 estate->err_stmt = save_estmt;
1324 elog(ERROR, "unrecognized cmdtype: %d", stmt->cmd_type);
1327 /* Let the plugin know that we have finished executing this statement */
1328 if (*plugin_ptr && (*plugin_ptr)->stmt_end)
1329 ((*plugin_ptr)->stmt_end) (estate, stmt);
1331 estate->err_stmt = save_estmt;
1338 * exec_stmt_assign Evaluate an expression and
1339 * put the result into a variable.
1343 exec_stmt_assign(PLpgSQL_execstate *estate, PLpgSQL_stmt_assign *stmt)
1345 Assert(stmt->varno >= 0);
1347 exec_assign_expr(estate, estate->datums[stmt->varno], stmt->expr);
1349 return PLPGSQL_RC_OK;
1353 * exec_stmt_perform Evaluate query and discard result (but set
1354 * FOUND depending on whether at least one row
1359 exec_stmt_perform(PLpgSQL_execstate *estate, PLpgSQL_stmt_perform *stmt)
1361 PLpgSQL_expr *expr = stmt->expr;
1363 (void) exec_run_select(estate, expr, 0, NULL);
1364 exec_set_found(estate, (estate->eval_processed != 0));
1365 exec_eval_cleanup(estate);
1367 return PLPGSQL_RC_OK;
1371 * exec_stmt_getdiag Put internal PG information into
1372 * specified variables.
1376 exec_stmt_getdiag(PLpgSQL_execstate *estate, PLpgSQL_stmt_getdiag *stmt)
1380 foreach(lc, stmt->diag_items)
1382 PLpgSQL_diag_item *diag_item = (PLpgSQL_diag_item *) lfirst(lc);
1384 bool isnull = false;
1386 if (diag_item->target <= 0)
1389 var = estate->datums[diag_item->target];
1394 switch (diag_item->kind)
1396 case PLPGSQL_GETDIAG_ROW_COUNT:
1398 exec_assign_value(estate, var,
1399 UInt32GetDatum(estate->eval_processed),
1403 case PLPGSQL_GETDIAG_RESULT_OID:
1405 exec_assign_value(estate, var,
1406 ObjectIdGetDatum(estate->eval_lastoid),
1411 elog(ERROR, "unrecognized attribute request: %d",
1416 return PLPGSQL_RC_OK;
1420 * exec_stmt_if Evaluate a bool expression and
1421 * execute the true or false body
1426 exec_stmt_if(PLpgSQL_execstate *estate, PLpgSQL_stmt_if *stmt)
1431 value = exec_eval_boolean(estate, stmt->cond, &isnull);
1432 exec_eval_cleanup(estate);
1434 if (!isnull && value)
1436 if (stmt->true_body != NIL)
1437 return exec_stmts(estate, stmt->true_body);
1441 if (stmt->false_body != NIL)
1442 return exec_stmts(estate, stmt->false_body);
1445 return PLPGSQL_RC_OK;
1454 exec_stmt_case(PLpgSQL_execstate *estate, PLpgSQL_stmt_case *stmt)
1456 PLpgSQL_var *t_var = NULL;
1460 if (stmt->t_expr != NULL)
1466 t_val = exec_eval_expr(estate, stmt->t_expr, &isnull, &t_oid);
1468 t_var = (PLpgSQL_var *) estate->datums[stmt->t_varno];
1471 * When expected datatype is different from real, change it. Note that
1472 * what we're modifying here is an execution copy of the datum, so
1473 * this doesn't affect the originally stored function parse tree.
1475 if (t_var->datatype->typoid != t_oid)
1476 t_var->datatype = plpgsql_build_datatype(t_oid, -1);
1478 /* now we can assign to the variable */
1479 exec_assign_value(estate,
1480 (PLpgSQL_datum *) t_var,
1485 exec_eval_cleanup(estate);
1488 /* Now search for a successful WHEN clause */
1489 foreach(l, stmt->case_when_list)
1491 PLpgSQL_case_when *cwt = (PLpgSQL_case_when *) lfirst(l);
1494 value = exec_eval_boolean(estate, cwt->expr, &isnull);
1495 exec_eval_cleanup(estate);
1496 if (!isnull && value)
1500 /* We can now discard any value we had for the temp variable */
1504 t_var->value = (Datum) 0;
1505 t_var->isnull = true;
1508 /* Evaluate the statement(s), and we're done */
1509 return exec_stmts(estate, cwt->stmts);
1513 /* We can now discard any value we had for the temp variable */
1517 t_var->value = (Datum) 0;
1518 t_var->isnull = true;
1521 /* SQL2003 mandates this error if there was no ELSE clause */
1522 if (!stmt->have_else)
1524 (errcode(ERRCODE_CASE_NOT_FOUND),
1525 errmsg("case not found"),
1526 errhint("CASE statement is missing ELSE part.")));
1528 /* Evaluate the ELSE statements, and we're done */
1529 return exec_stmts(estate, stmt->else_stmts);
1534 * exec_stmt_loop Loop over statements until
1539 exec_stmt_loop(PLpgSQL_execstate *estate, PLpgSQL_stmt_loop *stmt)
1543 int rc = exec_stmts(estate, stmt->body);
1550 case PLPGSQL_RC_EXIT:
1551 if (estate->exitlabel == NULL)
1552 return PLPGSQL_RC_OK;
1553 if (stmt->label == NULL)
1554 return PLPGSQL_RC_EXIT;
1555 if (strcmp(stmt->label, estate->exitlabel) != 0)
1556 return PLPGSQL_RC_EXIT;
1557 estate->exitlabel = NULL;
1558 return PLPGSQL_RC_OK;
1560 case PLPGSQL_RC_CONTINUE:
1561 if (estate->exitlabel == NULL)
1562 /* anonymous continue, so re-run the loop */
1564 else if (stmt->label != NULL &&
1565 strcmp(stmt->label, estate->exitlabel) == 0)
1566 /* label matches named continue, so re-run loop */
1567 estate->exitlabel = NULL;
1569 /* label doesn't match named continue, so propagate upward */
1570 return PLPGSQL_RC_CONTINUE;
1573 case PLPGSQL_RC_RETURN:
1574 case PLPGSQL_RC_RERAISE:
1578 elog(ERROR, "unrecognized rc: %d", rc);
1582 return PLPGSQL_RC_OK;
1587 * exec_stmt_while Loop over statements as long
1588 * as an expression evaluates to
1589 * true or an exit occurs.
1593 exec_stmt_while(PLpgSQL_execstate *estate, PLpgSQL_stmt_while *stmt)
1601 value = exec_eval_boolean(estate, stmt->cond, &isnull);
1602 exec_eval_cleanup(estate);
1604 if (isnull || !value)
1607 rc = exec_stmts(estate, stmt->body);
1614 case PLPGSQL_RC_EXIT:
1615 if (estate->exitlabel == NULL)
1616 return PLPGSQL_RC_OK;
1617 if (stmt->label == NULL)
1618 return PLPGSQL_RC_EXIT;
1619 if (strcmp(stmt->label, estate->exitlabel) != 0)
1620 return PLPGSQL_RC_EXIT;
1621 estate->exitlabel = NULL;
1622 return PLPGSQL_RC_OK;
1624 case PLPGSQL_RC_CONTINUE:
1625 if (estate->exitlabel == NULL)
1626 /* anonymous continue, so re-run loop */
1628 else if (stmt->label != NULL &&
1629 strcmp(stmt->label, estate->exitlabel) == 0)
1630 /* label matches named continue, so re-run loop */
1631 estate->exitlabel = NULL;
1633 /* label doesn't match named continue, propagate upward */
1634 return PLPGSQL_RC_CONTINUE;
1637 case PLPGSQL_RC_RETURN:
1638 case PLPGSQL_RC_RERAISE:
1642 elog(ERROR, "unrecognized rc: %d", rc);
1646 return PLPGSQL_RC_OK;
1651 * exec_stmt_fori Iterate an integer variable
1652 * from a lower to an upper value
1653 * incrementing or decrementing by the BY value
1657 exec_stmt_fori(PLpgSQL_execstate *estate, PLpgSQL_stmt_fori *stmt)
1667 int rc = PLPGSQL_RC_OK;
1669 var = (PLpgSQL_var *) (estate->datums[stmt->var->dno]);
1672 * Get the value of the lower bound
1674 value = exec_eval_expr(estate, stmt->lower, &isnull, &valtype);
1675 value = exec_cast_value(value, valtype, var->datatype->typoid,
1676 &(var->datatype->typinput),
1677 var->datatype->typioparam,
1678 var->datatype->atttypmod, isnull);
1681 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1682 errmsg("lower bound of FOR loop cannot be null")));
1683 loop_value = DatumGetInt32(value);
1684 exec_eval_cleanup(estate);
1687 * Get the value of the upper bound
1689 value = exec_eval_expr(estate, stmt->upper, &isnull, &valtype);
1690 value = exec_cast_value(value, valtype, var->datatype->typoid,
1691 &(var->datatype->typinput),
1692 var->datatype->typioparam,
1693 var->datatype->atttypmod, isnull);
1696 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1697 errmsg("upper bound of FOR loop cannot be null")));
1698 end_value = DatumGetInt32(value);
1699 exec_eval_cleanup(estate);
1702 * Get the step value
1706 value = exec_eval_expr(estate, stmt->step, &isnull, &valtype);
1707 value = exec_cast_value(value, valtype, var->datatype->typoid,
1708 &(var->datatype->typinput),
1709 var->datatype->typioparam,
1710 var->datatype->atttypmod, isnull);
1713 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1714 errmsg("BY value of FOR loop cannot be null")));
1715 step_value = DatumGetInt32(value);
1716 exec_eval_cleanup(estate);
1717 if (step_value <= 0)
1719 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1720 errmsg("BY value of FOR loop must be greater than zero")));
1731 * Check against upper bound
1735 if (loop_value < end_value)
1740 if (loop_value > end_value)
1744 found = true; /* looped at least once */
1747 * Assign current value to loop var
1749 var->value = Int32GetDatum(loop_value);
1750 var->isnull = false;
1753 * Execute the statements
1755 rc = exec_stmts(estate, stmt->body);
1757 if (rc == PLPGSQL_RC_RETURN ||
1758 rc == PLPGSQL_RC_RERAISE)
1759 break; /* break out of the loop */
1760 else if (rc == PLPGSQL_RC_EXIT)
1762 if (estate->exitlabel == NULL)
1763 /* unlabelled exit, finish the current loop */
1765 else if (stmt->label != NULL &&
1766 strcmp(stmt->label, estate->exitlabel) == 0)
1768 /* labelled exit, matches the current stmt's label */
1769 estate->exitlabel = NULL;
1774 * otherwise, this is a labelled exit that does not match the
1775 * current statement's label, if any: return RC_EXIT so that the
1776 * EXIT continues to propagate up the stack.
1780 else if (rc == PLPGSQL_RC_CONTINUE)
1782 if (estate->exitlabel == NULL)
1783 /* unlabelled continue, so re-run the current loop */
1785 else if (stmt->label != NULL &&
1786 strcmp(stmt->label, estate->exitlabel) == 0)
1788 /* label matches named continue, so re-run loop */
1789 estate->exitlabel = NULL;
1795 * otherwise, this is a named continue that does not match the
1796 * current statement's label, if any: return RC_CONTINUE so
1797 * that the CONTINUE will propagate up the stack.
1804 * Increase/decrease loop value, unless it would overflow, in which
1805 * case exit the loop.
1809 if ((int32) (loop_value - step_value) > loop_value)
1811 loop_value -= step_value;
1815 if ((int32) (loop_value + step_value) < loop_value)
1817 loop_value += step_value;
1822 * Set the FOUND variable to indicate the result of executing the loop
1823 * (namely, whether we looped one or more times). This must be set here so
1824 * that it does not interfere with the value of the FOUND variable inside
1825 * the loop processing itself.
1827 exec_set_found(estate, found);
1834 * exec_stmt_fors Execute a query, assign each
1835 * tuple to a record or row and
1836 * execute a group of statements
1841 exec_stmt_fors(PLpgSQL_execstate *estate, PLpgSQL_stmt_fors *stmt)
1847 * Open the implicit cursor for the statement using exec_run_select
1849 exec_run_select(estate, stmt->query, 0, &portal);
1854 rc = exec_for_query(estate, (PLpgSQL_stmt_forq *) stmt, portal, true);
1857 * Close the implicit cursor
1859 SPI_cursor_close(portal);
1866 * exec_stmt_forc Execute a loop for each row from a cursor.
1870 exec_stmt_forc(PLpgSQL_execstate *estate, PLpgSQL_stmt_forc *stmt)
1872 PLpgSQL_var *curvar;
1873 char *curname = NULL;
1874 PLpgSQL_expr *query;
1881 * Get the cursor variable and if it has an assigned name, check
1882 * that it's not in use currently.
1885 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
1886 if (!curvar->isnull)
1888 curname = TextDatumGetCString(curvar->value);
1889 if (SPI_cursor_find(curname) != NULL)
1891 (errcode(ERRCODE_DUPLICATE_CURSOR),
1892 errmsg("cursor \"%s\" already in use", curname)));
1896 * Open the cursor just like an OPEN command
1898 * Note: parser should already have checked that statement supplies
1899 * args iff cursor needs them, but we check again to be safe.
1902 if (stmt->argquery != NULL)
1905 * OPEN CURSOR with args. We fake a SELECT ... INTO ...
1906 * statement to evaluate the args and put 'em into the
1910 PLpgSQL_stmt_execsql set_args;
1912 if (curvar->cursor_explicit_argrow < 0)
1914 (errcode(ERRCODE_SYNTAX_ERROR),
1915 errmsg("arguments given for cursor without arguments")));
1917 memset(&set_args, 0, sizeof(set_args));
1918 set_args.cmd_type = PLPGSQL_STMT_EXECSQL;
1919 set_args.lineno = stmt->lineno;
1920 set_args.sqlstmt = stmt->argquery;
1921 set_args.into = true;
1922 /* XXX historically this has not been STRICT */
1923 set_args.row = (PLpgSQL_row *)
1924 (estate->datums[curvar->cursor_explicit_argrow]);
1926 if (exec_stmt_execsql(estate, &set_args) != PLPGSQL_RC_OK)
1927 elog(ERROR, "open cursor failed during argument processing");
1931 if (curvar->cursor_explicit_argrow >= 0)
1933 (errcode(ERRCODE_SYNTAX_ERROR),
1934 errmsg("arguments required for cursor")));
1937 query = curvar->cursor_explicit_expr;
1940 if (query->plan == NULL)
1941 exec_prepare_plan(estate, query, curvar->cursor_options);
1944 * Now build up the values and nulls arguments for SPI_execute_plan()
1946 eval_expr_params(estate, query, &values, &nulls);
1951 portal = SPI_cursor_open(curname, query->plan, values, nulls,
1952 estate->readonly_func);
1954 elog(ERROR, "could not open cursor: %s",
1955 SPI_result_code_string(SPI_result));
1958 * If cursor variable was NULL, store the generated portal name in it
1960 if (curname == NULL)
1961 assign_text_var(curvar, portal->name);
1964 * Execute the loop. We can't prefetch because the cursor is accessible
1965 * to the user, for instance via UPDATE WHERE CURRENT OF within the loop.
1967 rc = exec_for_query(estate, (PLpgSQL_stmt_forq *) stmt, portal, false);
1970 * Close portal, and restore cursor variable if it was initially NULL.
1973 SPI_cursor_close(portal);
1975 if (curname == NULL)
1978 curvar->value = (Datum) 0;
1979 curvar->isnull = true;
1992 * exec_stmt_exit Implements EXIT and CONTINUE
1994 * This begins the process of exiting / restarting a loop.
1998 exec_stmt_exit(PLpgSQL_execstate *estate, PLpgSQL_stmt_exit *stmt)
2001 * If the exit / continue has a condition, evaluate it
2003 if (stmt->cond != NULL)
2008 value = exec_eval_boolean(estate, stmt->cond, &isnull);
2009 exec_eval_cleanup(estate);
2010 if (isnull || value == false)
2011 return PLPGSQL_RC_OK;
2014 estate->exitlabel = stmt->label;
2016 return PLPGSQL_RC_EXIT;
2018 return PLPGSQL_RC_CONTINUE;
2023 * exec_stmt_return Evaluate an expression and start
2024 * returning from the function.
2028 exec_stmt_return(PLpgSQL_execstate *estate, PLpgSQL_stmt_return *stmt)
2031 * If processing a set-returning PL/PgSQL function, the final RETURN
2032 * indicates that the function is finished producing tuples. The rest of
2033 * the work will be done at the top level.
2035 if (estate->retisset)
2036 return PLPGSQL_RC_RETURN;
2038 /* initialize for null result (possibly a tuple) */
2039 estate->retval = (Datum) 0;
2040 estate->rettupdesc = NULL;
2041 estate->retisnull = true;
2043 if (stmt->retvarno >= 0)
2045 PLpgSQL_datum *retvar = estate->datums[stmt->retvarno];
2047 switch (retvar->dtype)
2049 case PLPGSQL_DTYPE_VAR:
2051 PLpgSQL_var *var = (PLpgSQL_var *) retvar;
2053 estate->retval = var->value;
2054 estate->retisnull = var->isnull;
2055 estate->rettype = var->datatype->typoid;
2059 case PLPGSQL_DTYPE_REC:
2061 PLpgSQL_rec *rec = (PLpgSQL_rec *) retvar;
2063 if (HeapTupleIsValid(rec->tup))
2065 estate->retval = PointerGetDatum(rec->tup);
2066 estate->rettupdesc = rec->tupdesc;
2067 estate->retisnull = false;
2072 case PLPGSQL_DTYPE_ROW:
2074 PLpgSQL_row *row = (PLpgSQL_row *) retvar;
2076 Assert(row->rowtupdesc);
2078 PointerGetDatum(make_tuple_from_row(estate, row,
2080 if (DatumGetPointer(estate->retval) == NULL) /* should not happen */
2081 elog(ERROR, "row not compatible with its own tupdesc");
2082 estate->rettupdesc = row->rowtupdesc;
2083 estate->retisnull = false;
2088 elog(ERROR, "unrecognized dtype: %d", retvar->dtype);
2091 return PLPGSQL_RC_RETURN;
2094 if (stmt->expr != NULL)
2096 if (estate->retistuple)
2098 exec_run_select(estate, stmt->expr, 1, NULL);
2099 if (estate->eval_processed > 0)
2101 estate->retval = PointerGetDatum(estate->eval_tuptable->vals[0]);
2102 estate->rettupdesc = estate->eval_tuptable->tupdesc;
2103 estate->retisnull = false;
2108 /* Normal case for scalar results */
2109 estate->retval = exec_eval_expr(estate, stmt->expr,
2110 &(estate->retisnull),
2111 &(estate->rettype));
2114 return PLPGSQL_RC_RETURN;
2118 * Special hack for function returning VOID: instead of NULL, return a
2119 * non-null VOID value. This is of dubious importance but is kept for
2120 * backwards compatibility. Note that the only other way to get here is
2121 * to have written "RETURN NULL" in a function returning tuple.
2123 if (estate->fn_rettype == VOIDOID)
2125 estate->retval = (Datum) 0;
2126 estate->retisnull = false;
2127 estate->rettype = VOIDOID;
2130 return PLPGSQL_RC_RETURN;
2134 * exec_stmt_return_next Evaluate an expression and add it to the
2135 * list of tuples returned by the current
2140 exec_stmt_return_next(PLpgSQL_execstate *estate,
2141 PLpgSQL_stmt_return_next *stmt)
2145 MemoryContext oldcxt;
2146 HeapTuple tuple = NULL;
2147 bool free_tuple = false;
2149 if (!estate->retisset)
2151 (errcode(ERRCODE_SYNTAX_ERROR),
2152 errmsg("cannot use RETURN NEXT in a non-SETOF function")));
2154 if (estate->tuple_store == NULL)
2155 exec_init_tuple_store(estate);
2157 /* rettupdesc will be filled by exec_init_tuple_store */
2158 tupdesc = estate->rettupdesc;
2159 natts = tupdesc->natts;
2161 if (stmt->retvarno >= 0)
2163 PLpgSQL_datum *retvar = estate->datums[stmt->retvarno];
2165 switch (retvar->dtype)
2167 case PLPGSQL_DTYPE_VAR:
2169 PLpgSQL_var *var = (PLpgSQL_var *) retvar;
2170 Datum retval = var->value;
2171 bool isNull = var->isnull;
2175 (errcode(ERRCODE_DATATYPE_MISMATCH),
2176 errmsg("wrong result type supplied in RETURN NEXT")));
2178 /* coerce type if needed */
2179 retval = exec_simple_cast_value(retval,
2180 var->datatype->typoid,
2181 tupdesc->attrs[0]->atttypid,
2182 tupdesc->attrs[0]->atttypmod,
2185 oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
2186 tuplestore_putvalues(estate->tuple_store, tupdesc,
2188 MemoryContextSwitchTo(oldcxt);
2192 case PLPGSQL_DTYPE_REC:
2194 PLpgSQL_rec *rec = (PLpgSQL_rec *) retvar;
2196 if (!HeapTupleIsValid(rec->tup))
2198 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2199 errmsg("record \"%s\" is not assigned yet",
2201 errdetail("The tuple structure of a not-yet-assigned"
2202 " record is indeterminate.")));
2203 validate_tupdesc_compat(tupdesc, rec->tupdesc,
2204 "wrong record type supplied in RETURN NEXT");
2209 case PLPGSQL_DTYPE_ROW:
2211 PLpgSQL_row *row = (PLpgSQL_row *) retvar;
2213 tuple = make_tuple_from_row(estate, row, tupdesc);
2216 (errcode(ERRCODE_DATATYPE_MISMATCH),
2217 errmsg("wrong record type supplied in RETURN NEXT")));
2223 elog(ERROR, "unrecognized dtype: %d", retvar->dtype);
2227 else if (stmt->expr)
2235 (errcode(ERRCODE_DATATYPE_MISMATCH),
2236 errmsg("wrong result type supplied in RETURN NEXT")));
2238 retval = exec_eval_expr(estate,
2243 /* coerce type if needed */
2244 retval = exec_simple_cast_value(retval,
2246 tupdesc->attrs[0]->atttypid,
2247 tupdesc->attrs[0]->atttypmod,
2250 oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
2251 tuplestore_putvalues(estate->tuple_store, tupdesc,
2253 MemoryContextSwitchTo(oldcxt);
2255 exec_eval_cleanup(estate);
2260 (errcode(ERRCODE_SYNTAX_ERROR),
2261 errmsg("RETURN NEXT must have a parameter")));
2264 if (HeapTupleIsValid(tuple))
2266 oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
2267 tuplestore_puttuple(estate->tuple_store, tuple);
2268 MemoryContextSwitchTo(oldcxt);
2271 heap_freetuple(tuple);
2274 return PLPGSQL_RC_OK;
2278 * exec_stmt_return_query Evaluate a query and add it to the
2279 * list of tuples returned by the current
2284 exec_stmt_return_query(PLpgSQL_execstate *estate,
2285 PLpgSQL_stmt_return_query *stmt)
2288 uint32 processed = 0;
2290 if (!estate->retisset)
2292 (errcode(ERRCODE_SYNTAX_ERROR),
2293 errmsg("cannot use RETURN QUERY in a non-SETOF function")));
2295 if (estate->tuple_store == NULL)
2296 exec_init_tuple_store(estate);
2298 if (stmt->query != NULL)
2301 exec_run_select(estate, stmt->query, 0, &portal);
2305 /* RETURN QUERY EXECUTE */
2306 Assert(stmt->dynquery != NULL);
2307 portal = exec_dynquery_with_params(estate, stmt->dynquery,
2311 validate_tupdesc_compat(estate->rettupdesc, portal->tupDesc,
2312 "structure of query does not match function result type");
2316 MemoryContext old_cxt;
2319 SPI_cursor_fetch(portal, true, 50);
2320 if (SPI_processed == 0)
2323 old_cxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
2324 for (i = 0; i < SPI_processed; i++)
2326 HeapTuple tuple = SPI_tuptable->vals[i];
2328 tuplestore_puttuple(estate->tuple_store, tuple);
2331 MemoryContextSwitchTo(old_cxt);
2333 SPI_freetuptable(SPI_tuptable);
2336 SPI_freetuptable(SPI_tuptable);
2337 SPI_cursor_close(portal);
2339 estate->eval_processed = processed;
2340 exec_set_found(estate, processed != 0);
2342 return PLPGSQL_RC_OK;
2346 exec_init_tuple_store(PLpgSQL_execstate *estate)
2348 ReturnSetInfo *rsi = estate->rsi;
2349 MemoryContext oldcxt;
2352 * Check caller can handle a set result in the way we want
2354 if (!rsi || !IsA(rsi, ReturnSetInfo) ||
2355 (rsi->allowedModes & SFRM_Materialize) == 0 ||
2356 rsi->expectedDesc == NULL)
2358 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2359 errmsg("set-valued function called in context that cannot accept a set")));
2361 estate->tuple_store_cxt = rsi->econtext->ecxt_per_query_memory;
2363 oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
2364 estate->tuple_store =
2365 tuplestore_begin_heap(rsi->allowedModes & SFRM_Materialize_Random,
2367 MemoryContextSwitchTo(oldcxt);
2369 estate->rettupdesc = rsi->expectedDesc;
2373 * exec_stmt_raise Build a message and throw it with elog()
2377 exec_stmt_raise(PLpgSQL_execstate *estate, PLpgSQL_stmt_raise *stmt)
2380 char *condname = NULL;
2381 char *err_message = NULL;
2382 char *err_detail = NULL;
2383 char *err_hint = NULL;
2386 /* RAISE with no parameters: re-throw current exception */
2387 if (stmt->condname == NULL && stmt->message == NULL &&
2388 stmt->options == NIL)
2389 return PLPGSQL_RC_RERAISE;
2393 err_code = plpgsql_recognize_err_condition(stmt->condname, true);
2394 condname = pstrdup(stmt->condname);
2400 ListCell *current_param;
2403 initStringInfo(&ds);
2404 current_param = list_head(stmt->params);
2406 for (cp = stmt->message; *cp; cp++)
2409 * Occurrences of a single % are replaced by the next parameter's
2410 * external representation. Double %'s are converted to one %.
2421 appendStringInfoChar(&ds, '%');
2426 if (current_param == NULL)
2428 (errcode(ERRCODE_SYNTAX_ERROR),
2429 errmsg("too few parameters specified for RAISE")));
2431 paramvalue = exec_eval_expr(estate,
2432 (PLpgSQL_expr *) lfirst(current_param),
2439 extval = convert_value_to_string(paramvalue, paramtypeid);
2440 appendStringInfoString(&ds, extval);
2441 current_param = lnext(current_param);
2442 exec_eval_cleanup(estate);
2445 appendStringInfoChar(&ds, cp[0]);
2449 * If more parameters were specified than were required to process the
2450 * format string, throw an error
2452 if (current_param != NULL)
2454 (errcode(ERRCODE_SYNTAX_ERROR),
2455 errmsg("too many parameters specified for RAISE")));
2457 err_message = ds.data;
2458 /* No pfree(ds.data), the pfree(err_message) does it */
2461 foreach(lc, stmt->options)
2463 PLpgSQL_raise_option *opt = (PLpgSQL_raise_option *) lfirst(lc);
2469 optionvalue = exec_eval_expr(estate, opt->expr,
2474 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2475 errmsg("RAISE statement option cannot be null")));
2477 extval = convert_value_to_string(optionvalue, optiontypeid);
2479 switch (opt->opt_type)
2481 case PLPGSQL_RAISEOPTION_ERRCODE:
2484 (errcode(ERRCODE_SYNTAX_ERROR),
2485 errmsg("RAISE option already specified: %s",
2487 err_code = plpgsql_recognize_err_condition(extval, true);
2488 condname = pstrdup(extval);
2490 case PLPGSQL_RAISEOPTION_MESSAGE:
2493 (errcode(ERRCODE_SYNTAX_ERROR),
2494 errmsg("RAISE option already specified: %s",
2496 err_message = pstrdup(extval);
2498 case PLPGSQL_RAISEOPTION_DETAIL:
2501 (errcode(ERRCODE_SYNTAX_ERROR),
2502 errmsg("RAISE option already specified: %s",
2504 err_detail = pstrdup(extval);
2506 case PLPGSQL_RAISEOPTION_HINT:
2509 (errcode(ERRCODE_SYNTAX_ERROR),
2510 errmsg("RAISE option already specified: %s",
2512 err_hint = pstrdup(extval);
2515 elog(ERROR, "unrecognized raise option: %d", opt->opt_type);
2518 exec_eval_cleanup(estate);
2521 /* Default code if nothing specified */
2522 if (err_code == 0 && stmt->elog_level >= ERROR)
2523 err_code = ERRCODE_RAISE_EXCEPTION;
2525 /* Default error message if nothing specified */
2526 if (err_message == NULL)
2530 err_message = condname;
2534 err_message = pstrdup(unpack_sql_state(err_code));
2538 * Throw the error (may or may not come back)
2540 estate->err_text = raise_skip_msg; /* suppress traceback of raise */
2542 ereport(stmt->elog_level,
2543 (err_code ? errcode(err_code) : 0,
2544 errmsg_internal("%s", err_message),
2545 (err_detail != NULL) ? errdetail("%s", err_detail) : 0,
2546 (err_hint != NULL) ? errhint("%s", err_hint) : 0));
2548 estate->err_text = NULL; /* un-suppress... */
2550 if (condname != NULL)
2552 if (err_message != NULL)
2554 if (err_detail != NULL)
2556 if (err_hint != NULL)
2559 return PLPGSQL_RC_OK;
2564 * Initialize a mostly empty execution state
2568 plpgsql_estate_setup(PLpgSQL_execstate *estate,
2569 PLpgSQL_function *func,
2572 estate->retval = (Datum) 0;
2573 estate->retisnull = true;
2574 estate->rettype = InvalidOid;
2576 estate->fn_rettype = func->fn_rettype;
2577 estate->retistuple = func->fn_retistuple;
2578 estate->retisset = func->fn_retset;
2580 estate->readonly_func = func->fn_readonly;
2582 estate->rettupdesc = NULL;
2583 estate->exitlabel = NULL;
2585 estate->tuple_store = NULL;
2586 estate->tuple_store_cxt = NULL;
2589 estate->trig_nargs = 0;
2590 estate->trig_argv = NULL;
2592 estate->found_varno = func->found_varno;
2593 estate->ndatums = func->ndatums;
2594 estate->datums = palloc(sizeof(PLpgSQL_datum *) * estate->ndatums);
2595 /* caller is expected to fill the datums array */
2597 estate->eval_tuptable = NULL;
2598 estate->eval_processed = 0;
2599 estate->eval_lastoid = InvalidOid;
2601 estate->err_func = func;
2602 estate->err_stmt = NULL;
2603 estate->err_text = NULL;
2606 * Create an EState and ExprContext for evaluation of simple expressions.
2608 plpgsql_create_econtext(estate);
2611 * Let the plugin see this function before we initialize any local
2612 * PL/pgSQL variables - note that we also give the plugin a few function
2613 * pointers so it can call back into PL/pgSQL for doing things like
2614 * variable assignments and stack traces
2618 (*plugin_ptr)->error_callback = plpgsql_exec_error_callback;
2619 (*plugin_ptr)->assign_expr = exec_assign_expr;
2621 if ((*plugin_ptr)->func_setup)
2622 ((*plugin_ptr)->func_setup) (estate, func);
2627 * Release temporary memory used by expression/subselect evaluation
2629 * NB: the result of the evaluation is no longer valid after this is done,
2630 * unless it is a pass-by-value datatype.
2634 exec_eval_cleanup(PLpgSQL_execstate *estate)
2636 /* Clear result of a full SPI_execute */
2637 if (estate->eval_tuptable != NULL)
2638 SPI_freetuptable(estate->eval_tuptable);
2639 estate->eval_tuptable = NULL;
2641 /* Clear result of exec_eval_simple_expr (but keep the econtext) */
2642 if (estate->eval_econtext != NULL)
2643 ResetExprContext(estate->eval_econtext);
2648 * Generate a prepared plan
2652 exec_prepare_plan(PLpgSQL_execstate *estate,
2653 PLpgSQL_expr *expr, int cursorOptions)
2660 * We need a temporary argtypes array to load with data. (The finished
2661 * plan structure will contain a copy of it.)
2663 argtypes = (Oid *) palloc(expr->nparams * sizeof(Oid));
2665 for (i = 0; i < expr->nparams; i++)
2670 exec_eval_datum(estate, estate->datums[expr->params[i]],
2672 &argtypes[i], ¶mval, ¶misnull);
2676 * Generate and save the plan
2678 plan = SPI_prepare_cursor(expr->query, expr->nparams, argtypes,
2682 /* Some SPI errors deserve specific error messages */
2685 case SPI_ERROR_COPY:
2687 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2688 errmsg("cannot COPY to/from client in PL/pgSQL")));
2689 case SPI_ERROR_TRANSACTION:
2691 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2692 errmsg("cannot begin/end transactions in PL/pgSQL"),
2693 errhint("Use a BEGIN block with an EXCEPTION clause instead.")));
2695 elog(ERROR, "SPI_prepare_cursor failed for \"%s\": %s",
2696 expr->query, SPI_result_code_string(SPI_result));
2699 expr->plan = SPI_saveplan(plan);
2702 expr->plan_argtypes = plan->argtypes;
2703 exec_simple_check_plan(expr);
2710 * exec_stmt_execsql Execute an SQL statement (possibly with INTO).
2714 exec_stmt_execsql(PLpgSQL_execstate *estate,
2715 PLpgSQL_stmt_execsql *stmt)
2721 PLpgSQL_expr *expr = stmt->sqlstmt;
2724 * On the first call for this statement generate the plan, and detect
2725 * whether the statement is INSERT/UPDATE/DELETE
2727 if (expr->plan == NULL)
2731 exec_prepare_plan(estate, expr, 0);
2732 stmt->mod_stmt = false;
2733 foreach(l, expr->plan->plancache_list)
2735 CachedPlanSource *plansource = (CachedPlanSource *) lfirst(l);
2738 foreach(l2, plansource->plan->stmt_list)
2740 PlannedStmt *p = (PlannedStmt *) lfirst(l2);
2742 if (IsA(p, PlannedStmt) &&
2745 if (p->commandType == CMD_INSERT ||
2746 p->commandType == CMD_UPDATE ||
2747 p->commandType == CMD_DELETE)
2748 stmt->mod_stmt = true;
2755 * Now build up the values and nulls arguments for SPI_execute_plan()
2757 eval_expr_params(estate, expr, &values, &nulls);
2760 * If we have INTO, then we only need one row back ... but if we have INTO
2761 * STRICT, ask for two rows, so that we can verify the statement returns
2762 * only one. INSERT/UPDATE/DELETE are always treated strictly. Without
2763 * INTO, just run the statement to completion (tcount = 0).
2765 * We could just ask for two rows always when using INTO, but there are
2766 * some cases where demanding the extra row costs significant time, eg by
2767 * forcing completion of a sequential scan. So don't do it unless we need
2768 * to enforce strictness.
2772 if (stmt->strict || stmt->mod_stmt)
2783 rc = SPI_execute_plan(expr->plan, values, nulls,
2784 estate->readonly_func, tcount);
2787 * Check for error, and set FOUND if appropriate (for historical reasons
2788 * we set FOUND only for certain query types). Also Assert that we
2789 * identified the statement type the same as SPI did.
2794 Assert(!stmt->mod_stmt);
2795 exec_set_found(estate, (SPI_processed != 0));
2801 case SPI_OK_INSERT_RETURNING:
2802 case SPI_OK_UPDATE_RETURNING:
2803 case SPI_OK_DELETE_RETURNING:
2804 Assert(stmt->mod_stmt);
2805 exec_set_found(estate, (SPI_processed != 0));
2808 case SPI_OK_SELINTO:
2809 case SPI_OK_UTILITY:
2810 Assert(!stmt->mod_stmt);
2813 case SPI_OK_REWRITTEN:
2814 Assert(!stmt->mod_stmt);
2817 * The command was rewritten into another kind of command. It's
2818 * not clear what FOUND would mean in that case (and SPI doesn't
2819 * return the row count either), so just set it to false.
2821 exec_set_found(estate, false);
2825 elog(ERROR, "SPI_execute_plan failed executing query \"%s\": %s",
2826 expr->query, SPI_result_code_string(rc));
2829 /* All variants should save result info for GET DIAGNOSTICS */
2830 estate->eval_processed = SPI_processed;
2831 estate->eval_lastoid = SPI_lastoid;
2833 /* Process INTO if present */
2836 SPITupleTable *tuptab = SPI_tuptable;
2837 uint32 n = SPI_processed;
2838 PLpgSQL_rec *rec = NULL;
2839 PLpgSQL_row *row = NULL;
2841 /* If the statement did not return a tuple table, complain */
2844 (errcode(ERRCODE_SYNTAX_ERROR),
2845 errmsg("INTO used with a command that cannot return data")));
2847 /* Determine if we assign to a record or a row */
2848 if (stmt->rec != NULL)
2849 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->dno]);
2850 else if (stmt->row != NULL)
2851 row = (PLpgSQL_row *) (estate->datums[stmt->row->dno]);
2853 elog(ERROR, "unsupported target");
2856 * If SELECT ... INTO specified STRICT, and the query didn't find
2857 * exactly one row, throw an error. If STRICT was not specified, then
2858 * allow the query to find any number of rows.
2864 (errcode(ERRCODE_NO_DATA_FOUND),
2865 errmsg("query returned no rows")));
2866 /* set the target to NULL(s) */
2867 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
2871 if (n > 1 && (stmt->strict || stmt->mod_stmt))
2873 (errcode(ERRCODE_TOO_MANY_ROWS),
2874 errmsg("query returned more than one row")));
2875 /* Put the first result row into the target */
2876 exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
2880 SPI_freetuptable(SPI_tuptable);
2884 /* If the statement returned a tuple table, complain */
2885 if (SPI_tuptable != NULL)
2887 (errcode(ERRCODE_SYNTAX_ERROR),
2888 errmsg("query has no destination for result data"),
2889 (rc == SPI_OK_SELECT) ? errhint("If you want to discard the results of a SELECT, use PERFORM instead.") : 0));
2895 return PLPGSQL_RC_OK;
2900 * exec_stmt_dynexecute Execute a dynamic SQL query
2901 * (possibly with INTO).
2905 exec_stmt_dynexecute(PLpgSQL_execstate *estate,
2906 PLpgSQL_stmt_dynexecute *stmt)
2909 bool isnull = false;
2915 * First we evaluate the string expression after the EXECUTE keyword. Its
2916 * result is the querystring we have to execute.
2918 query = exec_eval_expr(estate, stmt->query, &isnull, &restype);
2921 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2922 errmsg("query string argument of EXECUTE is null")));
2924 /* Get the C-String representation */
2925 querystr = convert_value_to_string(query, restype);
2927 exec_eval_cleanup(estate);
2930 * Execute the query without preparing a saved plan.
2934 PreparedParamsData *ppd;
2936 ppd = exec_eval_using_params(estate, stmt->params);
2937 exec_res = SPI_execute_with_args(querystr,
2938 ppd->nargs, ppd->types,
2939 ppd->values, ppd->nulls,
2940 estate->readonly_func, 0);
2941 free_params_data(ppd);
2944 exec_res = SPI_execute(querystr, estate->readonly_func, 0);
2952 case SPI_OK_INSERT_RETURNING:
2953 case SPI_OK_UPDATE_RETURNING:
2954 case SPI_OK_DELETE_RETURNING:
2955 case SPI_OK_UTILITY:
2956 case SPI_OK_REWRITTEN:
2962 * Also allow a zero return, which implies the querystring
2963 * contained no commands.
2967 case SPI_OK_SELINTO:
2970 * We want to disallow SELECT INTO for now, because its behavior
2971 * is not consistent with SELECT INTO in a normal plpgsql context.
2972 * (We need to reimplement EXECUTE to parse the string as a
2973 * plpgsql command, not just feed it to SPI_execute.) However,
2974 * CREATE AS should be allowed ... and since it produces the same
2975 * parsetree as SELECT INTO, there's no way to tell the difference
2976 * except to look at the source text. Wotta kluge!
2981 for (ptr = querystr; *ptr; ptr++)
2982 if (!scanner_isspace(*ptr))
2984 if (*ptr == 'S' || *ptr == 's')
2986 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2987 errmsg("EXECUTE of SELECT ... INTO is not implemented")));
2991 /* Some SPI errors deserve specific error messages */
2992 case SPI_ERROR_COPY:
2994 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2995 errmsg("cannot COPY to/from client in PL/pgSQL")));
2996 case SPI_ERROR_TRANSACTION:
2998 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2999 errmsg("cannot begin/end transactions in PL/pgSQL"),
3000 errhint("Use a BEGIN block with an EXCEPTION clause instead.")));
3003 elog(ERROR, "SPI_execute failed executing query \"%s\": %s",
3004 querystr, SPI_result_code_string(exec_res));
3008 /* Save result info for GET DIAGNOSTICS */
3009 estate->eval_processed = SPI_processed;
3010 estate->eval_lastoid = SPI_lastoid;
3012 /* Process INTO if present */
3015 SPITupleTable *tuptab = SPI_tuptable;
3016 uint32 n = SPI_processed;
3017 PLpgSQL_rec *rec = NULL;
3018 PLpgSQL_row *row = NULL;
3020 /* If the statement did not return a tuple table, complain */
3023 (errcode(ERRCODE_SYNTAX_ERROR),
3024 errmsg("INTO used with a command that cannot return data")));
3026 /* Determine if we assign to a record or a row */
3027 if (stmt->rec != NULL)
3028 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->dno]);
3029 else if (stmt->row != NULL)
3030 row = (PLpgSQL_row *) (estate->datums[stmt->row->dno]);
3032 elog(ERROR, "unsupported target");
3035 * If SELECT ... INTO specified STRICT, and the query didn't find
3036 * exactly one row, throw an error. If STRICT was not specified, then
3037 * allow the query to find any number of rows.
3043 (errcode(ERRCODE_NO_DATA_FOUND),
3044 errmsg("query returned no rows")));
3045 /* set the target to NULL(s) */
3046 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
3050 if (n > 1 && stmt->strict)
3052 (errcode(ERRCODE_TOO_MANY_ROWS),
3053 errmsg("query returned more than one row")));
3054 /* Put the first result row into the target */
3055 exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
3061 * It might be a good idea to raise an error if the query returned
3062 * tuples that are being ignored, but historically we have not done
3067 /* Release any result from SPI_execute, as well as the querystring */
3068 SPI_freetuptable(SPI_tuptable);
3071 return PLPGSQL_RC_OK;
3076 * exec_stmt_dynfors Execute a dynamic query, assign each
3077 * tuple to a record or row and
3078 * execute a group of statements
3083 exec_stmt_dynfors(PLpgSQL_execstate *estate, PLpgSQL_stmt_dynfors *stmt)
3088 portal = exec_dynquery_with_params(estate, stmt->query, stmt->params);
3093 rc = exec_for_query(estate, (PLpgSQL_stmt_forq *) stmt, portal, true);
3096 * Close the implicit cursor
3098 SPI_cursor_close(portal);
3105 * exec_stmt_open Execute an OPEN cursor statement
3109 exec_stmt_open(PLpgSQL_execstate *estate, PLpgSQL_stmt_open *stmt)
3111 PLpgSQL_var *curvar;
3112 char *curname = NULL;
3113 PLpgSQL_expr *query;
3120 * Get the cursor variable and if it has an assigned name, check
3121 * that it's not in use currently.
3124 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
3125 if (!curvar->isnull)
3127 curname = TextDatumGetCString(curvar->value);
3128 if (SPI_cursor_find(curname) != NULL)
3130 (errcode(ERRCODE_DUPLICATE_CURSOR),
3131 errmsg("cursor \"%s\" already in use", curname)));
3135 * Process the OPEN according to it's type.
3138 if (stmt->query != NULL)
3141 * This is an OPEN refcursor FOR SELECT ...
3143 * We just make sure the query is planned. The real work is
3147 query = stmt->query;
3148 if (query->plan == NULL)
3149 exec_prepare_plan(estate, query, stmt->cursor_options);
3151 else if (stmt->dynquery != NULL)
3154 * This is an OPEN refcursor FOR EXECUTE ...
3163 * We evaluate the string expression after the
3164 * EXECUTE keyword. It's result is the querystring we have
3168 queryD = exec_eval_expr(estate, stmt->dynquery, &isnull, &restype);
3171 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3172 errmsg("query string argument of EXECUTE is null")));
3174 /* Get the C-String representation */
3175 querystr = convert_value_to_string(queryD, restype);
3177 exec_eval_cleanup(estate);
3180 * Now we prepare a query plan for it and open a cursor
3183 curplan = SPI_prepare_cursor(querystr, 0, NULL, stmt->cursor_options);
3184 if (curplan == NULL)
3185 elog(ERROR, "SPI_prepare_cursor failed for \"%s\": %s",
3186 querystr, SPI_result_code_string(SPI_result));
3187 portal = SPI_cursor_open(curname, curplan, NULL, NULL,
3188 estate->readonly_func);
3190 elog(ERROR, "could not open cursor for query \"%s\": %s",
3191 querystr, SPI_result_code_string(SPI_result));
3193 SPI_freeplan(curplan);
3196 * If cursor variable was NULL, store the generated portal name in it
3198 if (curname == NULL)
3199 assign_text_var(curvar, portal->name);
3201 return PLPGSQL_RC_OK;
3206 * This is an OPEN cursor
3208 * Note: parser should already have checked that statement supplies
3209 * args iff cursor needs them, but we check again to be safe.
3212 if (stmt->argquery != NULL)
3215 * OPEN CURSOR with args. We fake a SELECT ... INTO ...
3216 * statement to evaluate the args and put 'em into the
3220 PLpgSQL_stmt_execsql set_args;
3222 if (curvar->cursor_explicit_argrow < 0)
3224 (errcode(ERRCODE_SYNTAX_ERROR),
3225 errmsg("arguments given for cursor without arguments")));
3227 memset(&set_args, 0, sizeof(set_args));
3228 set_args.cmd_type = PLPGSQL_STMT_EXECSQL;
3229 set_args.lineno = stmt->lineno;
3230 set_args.sqlstmt = stmt->argquery;
3231 set_args.into = true;
3232 /* XXX historically this has not been STRICT */
3233 set_args.row = (PLpgSQL_row *)
3234 (estate->datums[curvar->cursor_explicit_argrow]);
3236 if (exec_stmt_execsql(estate, &set_args) != PLPGSQL_RC_OK)
3237 elog(ERROR, "open cursor failed during argument processing");
3241 if (curvar->cursor_explicit_argrow >= 0)
3243 (errcode(ERRCODE_SYNTAX_ERROR),
3244 errmsg("arguments required for cursor")));
3247 query = curvar->cursor_explicit_expr;
3248 if (query->plan == NULL)
3249 exec_prepare_plan(estate, query, curvar->cursor_options);
3253 * Now build up the values and nulls arguments for SPI_execute_plan()
3255 eval_expr_params(estate, query, &values, &nulls);
3260 portal = SPI_cursor_open(curname, query->plan, values, nulls,
3261 estate->readonly_func);
3263 elog(ERROR, "could not open cursor: %s",
3264 SPI_result_code_string(SPI_result));
3267 * If cursor variable was NULL, store the generated portal name in it
3269 if (curname == NULL)
3270 assign_text_var(curvar, portal->name);
3277 return PLPGSQL_RC_OK;
3282 * exec_stmt_fetch Fetch from a cursor into a target, or just
3283 * move the current position of the cursor
3287 exec_stmt_fetch(PLpgSQL_execstate *estate, PLpgSQL_stmt_fetch *stmt)
3289 PLpgSQL_var *curvar = NULL;
3290 PLpgSQL_rec *rec = NULL;
3291 PLpgSQL_row *row = NULL;
3292 long how_many = stmt->how_many;
3293 SPITupleTable *tuptab;
3299 * Get the portal of the cursor by name
3302 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
3305 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3306 errmsg("cursor variable \"%s\" is null", curvar->refname)));
3307 curname = TextDatumGetCString(curvar->value);
3309 portal = SPI_cursor_find(curname);
3312 (errcode(ERRCODE_UNDEFINED_CURSOR),
3313 errmsg("cursor \"%s\" does not exist", curname)));
3316 /* Calculate position for FETCH_RELATIVE or FETCH_ABSOLUTE */
3321 /* XXX should be doing this in LONG not INT width */
3322 how_many = exec_eval_integer(estate, stmt->expr, &isnull);
3326 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3327 errmsg("relative or absolute cursor position is null")));
3329 exec_eval_cleanup(estate);
3335 * Determine if we fetch into a record or a row
3338 if (stmt->rec != NULL)
3339 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->dno]);
3340 else if (stmt->row != NULL)
3341 row = (PLpgSQL_row *) (estate->datums[stmt->row->dno]);
3343 elog(ERROR, "unsupported target");
3346 * Fetch 1 tuple from the cursor
3349 SPI_scroll_cursor_fetch(portal, stmt->direction, how_many);
3350 tuptab = SPI_tuptable;
3354 * Set the target appropriately.
3358 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
3360 exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
3362 SPI_freetuptable(tuptab);
3366 /* Move the cursor */
3367 SPI_scroll_cursor_move(portal, stmt->direction, how_many);
3371 /* Set the ROW_COUNT and the global FOUND variable appropriately. */
3372 estate->eval_processed = n;
3373 exec_set_found(estate, n != 0);
3375 return PLPGSQL_RC_OK;
3379 * exec_stmt_close Close a cursor
3383 exec_stmt_close(PLpgSQL_execstate *estate, PLpgSQL_stmt_close *stmt)
3385 PLpgSQL_var *curvar = NULL;
3390 * Get the portal of the cursor by name
3393 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
3396 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3397 errmsg("cursor variable \"%s\" is null", curvar->refname)));
3398 curname = TextDatumGetCString(curvar->value);
3400 portal = SPI_cursor_find(curname);
3403 (errcode(ERRCODE_UNDEFINED_CURSOR),
3404 errmsg("cursor \"%s\" does not exist", curname)));
3411 SPI_cursor_close(portal);
3413 return PLPGSQL_RC_OK;
3418 * exec_assign_expr Put an expression's result into
3423 exec_assign_expr(PLpgSQL_execstate *estate, PLpgSQL_datum *target,
3428 bool isnull = false;
3430 value = exec_eval_expr(estate, expr, &isnull, &valtype);
3431 exec_assign_value(estate, target, value, valtype, &isnull);
3432 exec_eval_cleanup(estate);
3437 * exec_assign_value Put a value into a target field
3441 exec_assign_value(PLpgSQL_execstate *estate,
3442 PLpgSQL_datum *target,
3443 Datum value, Oid valtype, bool *isNull)
3445 switch (target->dtype)
3447 case PLPGSQL_DTYPE_VAR:
3450 * Target is a variable
3452 PLpgSQL_var *var = (PLpgSQL_var *) target;
3455 newvalue = exec_cast_value(value, valtype, var->datatype->typoid,
3456 &(var->datatype->typinput),
3457 var->datatype->typioparam,
3458 var->datatype->atttypmod,
3461 if (*isNull && var->notnull)
3463 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3464 errmsg("null value cannot be assigned to variable \"%s\" declared NOT NULL",
3468 * If type is by-reference, make sure we have a freshly
3469 * palloc'd copy; the originally passed value may not live as
3470 * long as the variable! But we don't need to re-copy if
3471 * exec_cast_value performed a conversion; its output must
3472 * already be palloc'd.
3474 if (!var->datatype->typbyval && !*isNull)
3476 if (newvalue == value)
3477 newvalue = datumCopy(newvalue,
3479 var->datatype->typlen);
3483 * Now free the old value. (We can't do this any earlier
3484 * because of the possibility that we are assigning the var's
3485 * old value to it, eg "foo := foo". We could optimize out
3486 * the assignment altogether in such cases, but it's too
3487 * infrequent to be worth testing for.)
3491 var->value = newvalue;
3492 var->isnull = *isNull;
3493 if (!var->datatype->typbyval && !*isNull)
3494 var->freeval = true;
3498 case PLPGSQL_DTYPE_ROW:
3501 * Target is a row variable
3503 PLpgSQL_row *row = (PLpgSQL_row *) target;
3505 /* Source must be of RECORD or composite type */
3506 if (!type_is_rowtype(valtype))
3508 (errcode(ERRCODE_DATATYPE_MISMATCH),
3509 errmsg("cannot assign non-composite value to a row variable")));
3512 /* If source is null, just assign nulls to the row */
3513 exec_move_row(estate, NULL, row, NULL, NULL);
3521 HeapTupleData tmptup;
3523 /* Else source is a tuple Datum, safe to do this: */
3524 td = DatumGetHeapTupleHeader(value);
3525 /* Extract rowtype info and find a tupdesc */
3526 tupType = HeapTupleHeaderGetTypeId(td);
3527 tupTypmod = HeapTupleHeaderGetTypMod(td);
3528 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
3529 /* Build a temporary HeapTuple control structure */
3530 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
3531 ItemPointerSetInvalid(&(tmptup.t_self));
3532 tmptup.t_tableOid = InvalidOid;
3534 exec_move_row(estate, NULL, row, &tmptup, tupdesc);
3535 ReleaseTupleDesc(tupdesc);
3540 case PLPGSQL_DTYPE_REC:
3543 * Target is a record variable
3545 PLpgSQL_rec *rec = (PLpgSQL_rec *) target;
3547 /* Source must be of RECORD or composite type */
3548 if (!type_is_rowtype(valtype))
3550 (errcode(ERRCODE_DATATYPE_MISMATCH),
3551 errmsg("cannot assign non-composite value to a record variable")));
3554 /* If source is null, just assign nulls to the record */
3555 exec_move_row(estate, rec, NULL, NULL, NULL);
3563 HeapTupleData tmptup;
3565 /* Else source is a tuple Datum, safe to do this: */
3566 td = DatumGetHeapTupleHeader(value);
3567 /* Extract rowtype info and find a tupdesc */
3568 tupType = HeapTupleHeaderGetTypeId(td);
3569 tupTypmod = HeapTupleHeaderGetTypMod(td);
3570 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
3571 /* Build a temporary HeapTuple control structure */
3572 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
3573 ItemPointerSetInvalid(&(tmptup.t_self));
3574 tmptup.t_tableOid = InvalidOid;
3576 exec_move_row(estate, rec, NULL, &tmptup, tupdesc);
3577 ReleaseTupleDesc(tupdesc);
3582 case PLPGSQL_DTYPE_RECFIELD:
3585 * Target is a field of a record
3587 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) target;
3600 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
3603 * Check that there is already a tuple in the record. We need
3604 * that because records don't have any predefined field
3607 if (!HeapTupleIsValid(rec->tup))
3609 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3610 errmsg("record \"%s\" is not assigned yet",
3612 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
3615 * Get the number of the records field to change and the
3616 * number of attributes in the tuple. Note: disallow system
3617 * column names because the code below won't cope.
3619 fno = SPI_fnumber(rec->tupdesc, recfield->fieldname);
3622 (errcode(ERRCODE_UNDEFINED_COLUMN),
3623 errmsg("record \"%s\" has no field \"%s\"",
3624 rec->refname, recfield->fieldname)));
3626 natts = rec->tupdesc->natts;
3629 * Set up values/control arrays for heap_modify_tuple. For all
3630 * the attributes except the one we want to replace, use the
3631 * value that's in the old tuple.
3633 values = palloc(sizeof(Datum) * natts);
3634 nulls = palloc(sizeof(bool) * natts);
3635 replaces = palloc(sizeof(bool) * natts);
3637 memset(replaces, false, sizeof(bool) * natts);
3638 replaces[fno] = true;
3641 * Now insert the new value, being careful to cast it to the
3644 atttype = SPI_gettypeid(rec->tupdesc, fno + 1);
3645 atttypmod = rec->tupdesc->attrs[fno]->atttypmod;
3646 attisnull = *isNull;
3647 values[fno] = exec_simple_cast_value(value,
3652 nulls[fno] = attisnull;
3655 * Avoid leaking the result of exec_simple_cast_value, if it
3656 * performed a conversion to a pass-by-ref type.
3658 if (!attisnull && values[fno] != value && !get_typbyval(atttype))
3659 mustfree = DatumGetPointer(values[fno]);
3664 * Now call heap_modify_tuple() to create a new tuple that
3665 * replaces the old one in the record.
3667 newtup = heap_modify_tuple(rec->tup, rec->tupdesc,
3668 values, nulls, replaces);
3671 heap_freetuple(rec->tup);
3674 rec->freetup = true;
3685 case PLPGSQL_DTYPE_ARRAYELEM:
3689 PLpgSQL_expr *subscripts[MAXDIM];
3690 int subscriptvals[MAXDIM];
3691 bool oldarrayisnull;
3698 Datum oldarraydatum,
3700 ArrayType *oldarrayval;
3701 ArrayType *newarrayval;
3704 * Target is an element of an array
3706 * To handle constructs like x[1][2] := something, we have to
3707 * be prepared to deal with a chain of arrayelem datums. Chase
3708 * back to find the base array datum, and save the subscript
3709 * expressions as we go. (We are scanning right to left here,
3710 * but want to evaluate the subscripts left-to-right to
3711 * minimize surprises.)
3716 PLpgSQL_arrayelem *arrayelem = (PLpgSQL_arrayelem *) target;
3718 if (nsubscripts >= MAXDIM)
3720 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
3721 errmsg("number of array dimensions (%d) exceeds the maximum allowed (%d)",
3722 nsubscripts, MAXDIM)));
3723 subscripts[nsubscripts++] = arrayelem->subscript;
3724 target = estate->datums[arrayelem->arrayparentno];
3725 } while (target->dtype == PLPGSQL_DTYPE_ARRAYELEM);
3727 /* Fetch current value of array datum */
3728 exec_eval_datum(estate, target, InvalidOid,
3729 &arraytypeid, &oldarraydatum, &oldarrayisnull);
3731 arrayelemtypeid = get_element_type(arraytypeid);
3732 if (!OidIsValid(arrayelemtypeid))
3734 (errcode(ERRCODE_DATATYPE_MISMATCH),
3735 errmsg("subscripted object is not an array")));
3737 get_typlenbyvalalign(arrayelemtypeid,
3741 arraytyplen = get_typlen(arraytypeid);
3744 * Evaluate the subscripts, switch into left-to-right order.
3745 * Like ExecEvalArrayRef(), complain if any subscript is null.
3747 for (i = 0; i < nsubscripts; i++)
3752 exec_eval_integer(estate,
3753 subscripts[nsubscripts - 1 - i],
3757 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3758 errmsg("array subscript in assignment must not be null")));
3761 /* Coerce source value to match array element type. */
3762 coerced_value = exec_simple_cast_value(value,
3769 * If the original array is null, cons up an empty array so
3770 * that the assignment can proceed; we'll end with a
3771 * one-element array containing just the assigned-to
3772 * subscript. This only works for varlena arrays, though; for
3773 * fixed-length array types we skip the assignment. We can't
3774 * support assignment of a null entry into a fixed-length
3775 * array, either, so that's a no-op too. This is all ugly but
3776 * corresponds to the current behavior of ExecEvalArrayRef().
3778 if (arraytyplen > 0 && /* fixed-length array? */
3779 (oldarrayisnull || *isNull))
3783 oldarrayval = construct_empty_array(arrayelemtypeid);
3785 oldarrayval = (ArrayType *) DatumGetPointer(oldarraydatum);
3788 * Build the modified array value.
3790 newarrayval = array_set(oldarrayval,
3801 * Avoid leaking the result of exec_simple_cast_value, if it
3802 * performed a conversion to a pass-by-ref type.
3804 if (!*isNull && coerced_value != value && !elemtypbyval)
3805 pfree(DatumGetPointer(coerced_value));
3808 * Assign the new array to the base variable. It's never NULL
3812 exec_assign_value(estate, target,
3813 PointerGetDatum(newarrayval),
3814 arraytypeid, isNull);
3817 * Avoid leaking the modified array value, too.
3824 elog(ERROR, "unrecognized dtype: %d", target->dtype);
3829 * exec_eval_datum Get current value of a PLpgSQL_datum
3831 * The type oid, value in Datum format, and null flag are returned.
3833 * If expectedtypeid isn't InvalidOid, it is checked against the actual type.
3835 * At present this doesn't handle PLpgSQL_expr or PLpgSQL_arrayelem datums.
3837 * NOTE: caller must not modify the returned value, since it points right
3838 * at the stored value in the case of pass-by-reference datatypes. In some
3839 * cases we have to palloc a return value, and in such cases we put it into
3840 * the estate's short-term memory context.
3843 exec_eval_datum(PLpgSQL_execstate *estate,
3844 PLpgSQL_datum *datum,
3850 MemoryContext oldcontext;
3852 switch (datum->dtype)
3854 case PLPGSQL_DTYPE_VAR:
3856 PLpgSQL_var *var = (PLpgSQL_var *) datum;
3858 *typeid = var->datatype->typoid;
3859 *value = var->value;
3860 *isnull = var->isnull;
3861 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3863 (errcode(ERRCODE_DATATYPE_MISMATCH),
3864 errmsg("type of \"%s\" does not match that when preparing the plan",
3869 case PLPGSQL_DTYPE_ROW:
3871 PLpgSQL_row *row = (PLpgSQL_row *) datum;
3874 if (!row->rowtupdesc) /* should not happen */
3875 elog(ERROR, "row variable has no tupdesc");
3876 /* Make sure we have a valid type/typmod setting */
3877 BlessTupleDesc(row->rowtupdesc);
3878 oldcontext = MemoryContextSwitchTo(estate->eval_econtext->ecxt_per_tuple_memory);
3879 tup = make_tuple_from_row(estate, row, row->rowtupdesc);
3880 if (tup == NULL) /* should not happen */
3881 elog(ERROR, "row not compatible with its own tupdesc");
3882 MemoryContextSwitchTo(oldcontext);
3883 *typeid = row->rowtupdesc->tdtypeid;
3884 *value = HeapTupleGetDatum(tup);
3886 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3888 (errcode(ERRCODE_DATATYPE_MISMATCH),
3889 errmsg("type of \"%s\" does not match that when preparing the plan",
3894 case PLPGSQL_DTYPE_REC:
3896 PLpgSQL_rec *rec = (PLpgSQL_rec *) datum;
3897 HeapTupleData worktup;
3899 if (!HeapTupleIsValid(rec->tup))
3901 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3902 errmsg("record \"%s\" is not assigned yet",
3904 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
3905 Assert(rec->tupdesc != NULL);
3906 /* Make sure we have a valid type/typmod setting */
3907 BlessTupleDesc(rec->tupdesc);
3910 * In a trigger, the NEW and OLD parameters are likely to be
3911 * on-disk tuples that don't have the desired Datum fields.
3912 * Copy the tuple body and insert the right values.
3914 oldcontext = MemoryContextSwitchTo(estate->eval_econtext->ecxt_per_tuple_memory);
3915 heap_copytuple_with_tuple(rec->tup, &worktup);
3916 HeapTupleHeaderSetDatumLength(worktup.t_data, worktup.t_len);
3917 HeapTupleHeaderSetTypeId(worktup.t_data, rec->tupdesc->tdtypeid);
3918 HeapTupleHeaderSetTypMod(worktup.t_data, rec->tupdesc->tdtypmod);
3919 MemoryContextSwitchTo(oldcontext);
3920 *typeid = rec->tupdesc->tdtypeid;
3921 *value = HeapTupleGetDatum(&worktup);
3923 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3925 (errcode(ERRCODE_DATATYPE_MISMATCH),
3926 errmsg("type of \"%s\" does not match that when preparing the plan",
3931 case PLPGSQL_DTYPE_RECFIELD:
3933 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) datum;
3937 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
3938 if (!HeapTupleIsValid(rec->tup))
3940 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3941 errmsg("record \"%s\" is not assigned yet",
3943 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
3944 fno = SPI_fnumber(rec->tupdesc, recfield->fieldname);
3945 if (fno == SPI_ERROR_NOATTRIBUTE)
3947 (errcode(ERRCODE_UNDEFINED_COLUMN),
3948 errmsg("record \"%s\" has no field \"%s\"",
3949 rec->refname, recfield->fieldname)));
3950 *typeid = SPI_gettypeid(rec->tupdesc, fno);
3951 *value = SPI_getbinval(rec->tup, rec->tupdesc, fno, isnull);
3952 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3954 (errcode(ERRCODE_DATATYPE_MISMATCH),
3955 errmsg("type of \"%s.%s\" does not match that when preparing the plan",
3956 rec->refname, recfield->fieldname)));
3960 case PLPGSQL_DTYPE_TRIGARG:
3962 PLpgSQL_trigarg *trigarg = (PLpgSQL_trigarg *) datum;
3966 tgargno = exec_eval_integer(estate, trigarg->argnum, isnull);
3967 if (*isnull || tgargno < 0 || tgargno >= estate->trig_nargs)
3974 *value = estate->trig_argv[tgargno];
3977 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3979 (errcode(ERRCODE_DATATYPE_MISMATCH),
3980 errmsg("type of tg_argv[%d] does not match that when preparing the plan",
3986 elog(ERROR, "unrecognized dtype: %d", datum->dtype);
3991 * exec_eval_integer Evaluate an expression, coerce result to int4
3993 * Note we do not do exec_eval_cleanup here; the caller must do it at
3994 * some later point. (We do this because the caller may be holding the
3995 * results of other, pass-by-reference, expression evaluations, such as
3996 * an array value to be subscripted. Also see notes in exec_eval_simple_expr
3997 * about allocation of the parameter array.)
4001 exec_eval_integer(PLpgSQL_execstate *estate,
4008 exprdatum = exec_eval_expr(estate, expr, isNull, &exprtypeid);
4009 exprdatum = exec_simple_cast_value(exprdatum, exprtypeid,
4012 return DatumGetInt32(exprdatum);
4016 * exec_eval_boolean Evaluate an expression, coerce result to bool
4018 * Note we do not do exec_eval_cleanup here; the caller must do it at
4023 exec_eval_boolean(PLpgSQL_execstate *estate,
4030 exprdatum = exec_eval_expr(estate, expr, isNull, &exprtypeid);
4031 exprdatum = exec_simple_cast_value(exprdatum, exprtypeid,
4034 return DatumGetBool(exprdatum);
4038 * exec_eval_expr Evaluate an expression and return
4041 * NOTE: caller must do exec_eval_cleanup when done with the Datum.
4045 exec_eval_expr(PLpgSQL_execstate *estate,
4054 * If first time through, create a plan for this expression.
4056 if (expr->plan == NULL)
4057 exec_prepare_plan(estate, expr, 0);
4060 * If this is a simple expression, bypass SPI and use the executor
4063 if (exec_eval_simple_expr(estate, expr, &result, isNull, rettype))
4067 * Else do it the hard way via exec_run_select
4069 rc = exec_run_select(estate, expr, 2, NULL);
4070 if (rc != SPI_OK_SELECT)
4072 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
4073 errmsg("query \"%s\" did not return data", expr->query)));
4076 * If there are no rows selected, the result is NULL.
4078 if (estate->eval_processed == 0)
4085 * Check that the expression returned one single Datum
4087 if (estate->eval_processed > 1)
4089 (errcode(ERRCODE_CARDINALITY_VIOLATION),
4090 errmsg("query \"%s\" returned more than one row",
4092 if (estate->eval_tuptable->tupdesc->natts != 1)
4094 (errcode(ERRCODE_SYNTAX_ERROR),
4095 errmsg_plural("query \"%s\" returned %d column",
4096 "query \"%s\" returned %d columns",
4097 estate->eval_tuptable->tupdesc->natts,
4099 estate->eval_tuptable->tupdesc->natts)));
4102 * Return the result and its type
4104 *rettype = SPI_gettypeid(estate->eval_tuptable->tupdesc, 1);
4105 return SPI_getbinval(estate->eval_tuptable->vals[0],
4106 estate->eval_tuptable->tupdesc, 1, isNull);
4111 * exec_run_select Execute a select query
4115 exec_run_select(PLpgSQL_execstate *estate,
4116 PLpgSQL_expr *expr, long maxtuples, Portal *portalP)
4123 * On the first call for this expression generate the plan
4125 if (expr->plan == NULL)
4126 exec_prepare_plan(estate, expr, 0);
4129 * Now build up the values and nulls arguments for SPI_execute_plan()
4131 eval_expr_params(estate, expr, &values, &nulls);
4134 * If a portal was requested, put the query into the portal
4136 if (portalP != NULL)
4138 *portalP = SPI_cursor_open(NULL, expr->plan, values, nulls,
4139 estate->readonly_func);
4140 if (*portalP == NULL)
4141 elog(ERROR, "could not open implicit cursor for query \"%s\": %s",
4142 expr->query, SPI_result_code_string(SPI_result));
4145 return SPI_OK_CURSOR;
4151 rc = SPI_execute_plan(expr->plan, values, nulls,
4152 estate->readonly_func, maxtuples);
4153 if (rc != SPI_OK_SELECT)
4155 (errcode(ERRCODE_SYNTAX_ERROR),
4156 errmsg("query \"%s\" is not a SELECT", expr->query)));
4158 /* Save query results for eventual cleanup */
4159 Assert(estate->eval_tuptable == NULL);
4160 estate->eval_tuptable = SPI_tuptable;
4161 estate->eval_processed = SPI_processed;
4162 estate->eval_lastoid = SPI_lastoid;
4172 * exec_for_query --- execute body of FOR loop for each row from a portal
4174 * Used by exec_stmt_fors, exec_stmt_forc and exec_stmt_dynfors
4177 exec_for_query(PLpgSQL_execstate *estate, PLpgSQL_stmt_forq *stmt,
4178 Portal portal, bool prefetch_ok)
4180 PLpgSQL_rec *rec = NULL;
4181 PLpgSQL_row *row = NULL;
4182 SPITupleTable *tuptab;
4184 int rc = PLPGSQL_RC_OK;
4188 * Determine if we assign to a record or a row
4190 if (stmt->rec != NULL)
4191 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->dno]);
4192 else if (stmt->row != NULL)
4193 row = (PLpgSQL_row *) (estate->datums[stmt->row->dno]);
4195 elog(ERROR, "unsupported target");
4198 * Fetch the initial tuple(s). If prefetching is allowed then we grab a
4199 * few more rows to avoid multiple trips through executor startup
4202 SPI_cursor_fetch(portal, true, prefetch_ok ? 10 : 1);
4203 tuptab = SPI_tuptable;
4207 * If the query didn't return any rows, set the target to NULL and fall
4208 * through with found = false.
4211 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
4213 found = true; /* processed at least one tuple */
4222 for (i = 0; i < n; i++)
4225 * Assign the tuple to the target
4227 exec_move_row(estate, rec, row, tuptab->vals[i], tuptab->tupdesc);
4230 * Execute the statements
4232 rc = exec_stmts(estate, stmt->body);
4234 if (rc != PLPGSQL_RC_OK)
4236 if (rc == PLPGSQL_RC_EXIT)
4238 if (estate->exitlabel == NULL)
4240 /* unlabelled exit, so exit the current loop */
4243 else if (stmt->label != NULL &&
4244 strcmp(stmt->label, estate->exitlabel) == 0)
4246 /* label matches this loop, so exit loop */
4247 estate->exitlabel = NULL;
4252 * otherwise, we processed a labelled exit that does not
4253 * match the current statement's label, if any; return
4254 * RC_EXIT so that the EXIT continues to recurse upward.
4257 else if (rc == PLPGSQL_RC_CONTINUE)
4259 if (estate->exitlabel == NULL)
4261 /* unlabelled continue, so re-run the current loop */
4265 else if (stmt->label != NULL &&
4266 strcmp(stmt->label, estate->exitlabel) == 0)
4268 /* label matches this loop, so re-run loop */
4269 estate->exitlabel = NULL;
4275 * otherwise, we process a labelled continue that does not
4276 * match the current statement's label, if any; return
4277 * RC_CONTINUE so that the CONTINUE will propagate up the
4283 * We're aborting the loop. Need a goto to get out of two
4290 SPI_freetuptable(tuptab);
4293 * Fetch more tuples. If prefetching is allowed, grab 50 at a time.
4295 SPI_cursor_fetch(portal, true, prefetch_ok ? 50 : 1);
4296 tuptab = SPI_tuptable;
4303 * Release last group of tuples (if any)
4305 SPI_freetuptable(tuptab);
4308 * Set the FOUND variable to indicate the result of executing the loop
4309 * (namely, whether we looped one or more times). This must be set last so
4310 * that it does not interfere with the value of the FOUND variable inside
4311 * the loop processing itself.
4313 exec_set_found(estate, found);
4320 * exec_eval_simple_expr - Evaluate a simple expression returning
4321 * a Datum by directly calling ExecEvalExpr().
4323 * If successful, store results into *result, *isNull, *rettype and return
4324 * TRUE. If the expression is not simple (any more), return FALSE.
4326 * It is possible though unlikely for a simple expression to become non-simple
4327 * (consider for example redefining a trivial view). We must handle that for
4328 * correctness; fortunately it's normally inexpensive to do
4329 * RevalidateCachedPlan on a simple expression. We do not consider the other
4330 * direction (non-simple expression becoming simple) because we'll still give
4331 * correct results if that happens, and it's unlikely to be worth the cycles
4334 * Note: if pass-by-reference, the result is in the eval_econtext's
4335 * temporary memory context. It will be freed when exec_eval_cleanup
4340 exec_eval_simple_expr(PLpgSQL_execstate *estate,
4346 ExprContext *econtext = estate->eval_econtext;
4347 LocalTransactionId curlxid = MyProc->lxid;
4348 CachedPlanSource *plansource;
4350 ParamListInfo paramLI;
4352 MemoryContext oldcontext;
4355 * Forget it if expression wasn't simple before.
4357 if (expr->expr_simple_expr == NULL)
4361 * Revalidate cached plan, so that we will notice if it became stale. (We
4362 * also need to hold a refcount while using the plan.) Note that even if
4363 * replanning occurs, the length of plancache_list can't change, since it
4364 * is a property of the raw parsetree generated from the query text.
4366 Assert(list_length(expr->plan->plancache_list) == 1);
4367 plansource = (CachedPlanSource *) linitial(expr->plan->plancache_list);
4368 cplan = RevalidateCachedPlan(plansource, true);
4369 if (cplan->generation != expr->expr_simple_generation)
4371 /* It got replanned ... is it still simple? */
4372 exec_simple_check_plan(expr);
4373 if (expr->expr_simple_expr == NULL)
4375 /* Ooops, release refcount and fail */
4376 ReleaseCachedPlan(cplan, true);
4382 * Pass back previously-determined result type.
4384 *rettype = expr->expr_simple_type;
4387 * Prepare the expression for execution, if it's not been done already in
4388 * the current transaction. (This will be forced to happen if we called
4389 * exec_simple_check_plan above.)
4391 if (expr->expr_simple_lxid != curlxid)
4393 expr->expr_simple_state = ExecPrepareExpr(expr->expr_simple_expr,
4394 simple_eval_estate);
4395 expr->expr_simple_lxid = curlxid;
4399 * Param list can live in econtext's temporary memory context.
4401 * XXX think about avoiding repeated palloc's for param lists? Beware
4402 * however that this routine is re-entrant: exec_eval_datum() can call it
4403 * back for subscript evaluation, and so there can be a need to have more
4404 * than one active param list.
4406 if (expr->nparams > 0)
4408 /* sizeof(ParamListInfoData) includes the first array element */
4409 paramLI = (ParamListInfo)
4410 MemoryContextAlloc(econtext->ecxt_per_tuple_memory,
4411 sizeof(ParamListInfoData) +
4412 (expr->nparams - 1) *sizeof(ParamExternData));
4413 paramLI->numParams = expr->nparams;
4415 for (i = 0; i < expr->nparams; i++)
4417 ParamExternData *prm = ¶mLI->params[i];
4418 PLpgSQL_datum *datum = estate->datums[expr->params[i]];
4421 exec_eval_datum(estate, datum, expr->plan_argtypes[i],
4423 &prm->value, &prm->isnull);
4430 * Now we can safely make the econtext point to the param list.
4432 econtext->ecxt_param_list_info = paramLI;
4435 * We have to do some of the things SPI_execute_plan would do, in
4436 * particular advance the snapshot if we are in a non-read-only function.
4437 * Without this, stable functions within the expression would fail to see
4438 * updates made so far by our own function.
4442 oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
4443 if (!estate->readonly_func)
4445 CommandCounterIncrement();
4446 PushActiveSnapshot(GetTransactionSnapshot());
4450 * Finally we can call the executor to evaluate the expression
4452 *result = ExecEvalExpr(expr->expr_simple_state,
4456 MemoryContextSwitchTo(oldcontext);
4458 if (!estate->readonly_func)
4459 PopActiveSnapshot();
4464 * Now we can release our refcount on the cached plan.
4466 ReleaseCachedPlan(cplan, true);
4476 * Build up the values and nulls arguments for SPI_execute_plan()
4479 eval_expr_params(PLpgSQL_execstate *estate,
4480 PLpgSQL_expr *expr, Datum **p_values, char **p_nulls)
4486 *p_values = values = (Datum *) palloc(expr->nparams * sizeof(Datum));
4487 *p_nulls = nulls = (char *) palloc(expr->nparams * sizeof(char));
4489 for (i = 0; i < expr->nparams; i++)
4491 PLpgSQL_datum *datum = estate->datums[expr->params[i]];
4495 exec_eval_datum(estate, datum, expr->plan_argtypes[i],
4496 ¶mtypeid, &values[i], ¶misnull);
4506 * exec_move_row Move one tuple's values into a record or row
4510 exec_move_row(PLpgSQL_execstate *estate,
4513 HeapTuple tup, TupleDesc tupdesc)
4516 * Record is simple - just copy the tuple and its descriptor into the
4522 * Copy input first, just in case it is pointing at variable's value
4524 if (HeapTupleIsValid(tup))
4525 tup = heap_copytuple(tup);
4528 /* If we have a tupdesc but no data, form an all-nulls tuple */
4531 nulls = (bool *) palloc(tupdesc->natts * sizeof(bool));
4532 memset(nulls, true, tupdesc->natts * sizeof(bool));
4534 tup = heap_form_tuple(tupdesc, NULL, nulls);
4540 tupdesc = CreateTupleDescCopy(tupdesc);
4542 /* Free the old value ... */
4545 heap_freetuple(rec->tup);
4546 rec->freetup = false;
4548 if (rec->freetupdesc)
4550 FreeTupleDesc(rec->tupdesc);
4551 rec->freetupdesc = false;
4554 /* ... and install the new */
4555 if (HeapTupleIsValid(tup))
4558 rec->freetup = true;
4565 rec->tupdesc = tupdesc;
4566 rec->freetupdesc = true;
4569 rec->tupdesc = NULL;
4575 * Row is a bit more complicated in that we assign the individual
4576 * attributes of the tuple to the variables the row points to.
4578 * NOTE: this code used to demand row->nfields ==
4579 * HeapTupleHeaderGetNatts(tup->t_data), but that's wrong. The tuple
4580 * might have more fields than we expected if it's from an
4581 * inheritance-child table of the current table, or it might have fewer if
4582 * the table has had columns added by ALTER TABLE. Ignore extra columns
4583 * and assume NULL for missing columns, the same as heap_getattr would do.
4584 * We also have to skip over dropped columns in either the source or
4587 * If we have no tuple data at all, we'll assign NULL to all columns of
4592 int td_natts = tupdesc ? tupdesc->natts : 0;
4597 if (HeapTupleIsValid(tup))
4598 t_natts = HeapTupleHeaderGetNatts(tup->t_data);
4603 for (fnum = 0; fnum < row->nfields; fnum++)
4610 if (row->varnos[fnum] < 0)
4611 continue; /* skip dropped column in row struct */
4613 var = (PLpgSQL_var *) (estate->datums[row->varnos[fnum]]);
4615 while (anum < td_natts && tupdesc->attrs[anum]->attisdropped)
4616 anum++; /* skip dropped column in tuple */
4618 if (anum < td_natts)
4621 value = SPI_getbinval(tup, tupdesc, anum + 1, &isnull);
4627 valtype = SPI_gettypeid(tupdesc, anum + 1);
4634 valtype = InvalidOid;
4637 exec_assign_value(estate, (PLpgSQL_datum *) var,
4638 value, valtype, &isnull);
4644 elog(ERROR, "unsupported target");
4648 * make_tuple_from_row Make a tuple from the values of a row object
4650 * A NULL return indicates rowtype mismatch; caller must raise suitable error
4654 make_tuple_from_row(PLpgSQL_execstate *estate,
4658 int natts = tupdesc->natts;
4664 if (natts != row->nfields)
4667 dvalues = (Datum *) palloc0(natts * sizeof(Datum));
4668 nulls = (bool *) palloc(natts * sizeof(bool));
4670 for (i = 0; i < natts; i++)
4674 if (tupdesc->attrs[i]->attisdropped)
4676 nulls[i] = true; /* leave the column as null */
4679 if (row->varnos[i] < 0) /* should not happen */
4680 elog(ERROR, "dropped rowtype entry for non-dropped column");
4682 exec_eval_datum(estate, estate->datums[row->varnos[i]],
4683 InvalidOid, &fieldtypeid, &dvalues[i], &nulls[i]);
4684 if (fieldtypeid != tupdesc->attrs[i]->atttypid)
4688 tuple = heap_form_tuple(tupdesc, dvalues, nulls);
4697 * convert_value_to_string Convert a non-null Datum to C string
4699 * Note: callers generally assume that the result is a palloc'd string and
4700 * should be pfree'd. This is not all that safe an assumption ...
4702 * Note: not caching the conversion function lookup is bad for performance.
4706 convert_value_to_string(Datum value, Oid valtype)
4711 getTypeOutputInfo(valtype, &typoutput, &typIsVarlena);
4712 return OidOutputFunctionCall(typoutput, value);
4716 * exec_cast_value Cast a value if required
4720 exec_cast_value(Datum value, Oid valtype,
4728 * If the type of the queries return value isn't that of the variable,
4731 if (valtype != reqtype || reqtypmod != -1)
4737 extval = convert_value_to_string(value, valtype);
4738 value = InputFunctionCall(reqinput, extval,
4739 reqtypioparam, reqtypmod);
4744 value = InputFunctionCall(reqinput, NULL,
4745 reqtypioparam, reqtypmod);
4753 * exec_simple_cast_value Cast a value if required
4755 * As above, but need not supply details about target type. Note that this
4756 * is slower than exec_cast_value with cached type info, and so should be
4757 * avoided in heavily used code paths.
4761 exec_simple_cast_value(Datum value, Oid valtype,
4762 Oid reqtype, int32 reqtypmod,
4765 if (valtype != reqtype || reqtypmod != -1)
4769 FmgrInfo finfo_input;
4771 getTypeInputInfo(reqtype, &typinput, &typioparam);
4773 fmgr_info(typinput, &finfo_input);
4775 value = exec_cast_value(value,
4789 * exec_simple_check_node - Recursively check if an expression
4790 * is made only of simple things we can
4791 * hand out directly to ExecEvalExpr()
4792 * instead of calling SPI.
4796 exec_simple_check_node(Node *node)
4801 switch (nodeTag(node))
4811 ArrayRef *expr = (ArrayRef *) node;
4813 if (!exec_simple_check_node((Node *) expr->refupperindexpr))
4815 if (!exec_simple_check_node((Node *) expr->reflowerindexpr))
4817 if (!exec_simple_check_node((Node *) expr->refexpr))
4819 if (!exec_simple_check_node((Node *) expr->refassgnexpr))
4827 FuncExpr *expr = (FuncExpr *) node;
4829 if (expr->funcretset)
4831 if (!exec_simple_check_node((Node *) expr->args))
4839 OpExpr *expr = (OpExpr *) node;
4843 if (!exec_simple_check_node((Node *) expr->args))
4849 case T_DistinctExpr:
4851 DistinctExpr *expr = (DistinctExpr *) node;
4855 if (!exec_simple_check_node((Node *) expr->args))
4861 case T_ScalarArrayOpExpr:
4863 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
4865 if (!exec_simple_check_node((Node *) expr->args))
4873 BoolExpr *expr = (BoolExpr *) node;
4875 if (!exec_simple_check_node((Node *) expr->args))
4882 return exec_simple_check_node((Node *) ((FieldSelect *) node)->arg);
4886 FieldStore *expr = (FieldStore *) node;
4888 if (!exec_simple_check_node((Node *) expr->arg))
4890 if (!exec_simple_check_node((Node *) expr->newvals))
4897 return exec_simple_check_node((Node *) ((RelabelType *) node)->arg);
4900 return exec_simple_check_node((Node *) ((CoerceViaIO *) node)->arg);
4902 case T_ArrayCoerceExpr:
4903 return exec_simple_check_node((Node *) ((ArrayCoerceExpr *) node)->arg);
4905 case T_ConvertRowtypeExpr:
4906 return exec_simple_check_node((Node *) ((ConvertRowtypeExpr *) node)->arg);
4910 CaseExpr *expr = (CaseExpr *) node;
4912 if (!exec_simple_check_node((Node *) expr->arg))
4914 if (!exec_simple_check_node((Node *) expr->args))
4916 if (!exec_simple_check_node((Node *) expr->defresult))
4924 CaseWhen *when = (CaseWhen *) node;
4926 if (!exec_simple_check_node((Node *) when->expr))
4928 if (!exec_simple_check_node((Node *) when->result))
4934 case T_CaseTestExpr:
4939 ArrayExpr *expr = (ArrayExpr *) node;
4941 if (!exec_simple_check_node((Node *) expr->elements))
4949 RowExpr *expr = (RowExpr *) node;
4951 if (!exec_simple_check_node((Node *) expr->args))
4957 case T_RowCompareExpr:
4959 RowCompareExpr *expr = (RowCompareExpr *) node;
4961 if (!exec_simple_check_node((Node *) expr->largs))
4963 if (!exec_simple_check_node((Node *) expr->rargs))
4969 case T_CoalesceExpr:
4971 CoalesceExpr *expr = (CoalesceExpr *) node;
4973 if (!exec_simple_check_node((Node *) expr->args))
4981 MinMaxExpr *expr = (MinMaxExpr *) node;
4983 if (!exec_simple_check_node((Node *) expr->args))
4991 XmlExpr *expr = (XmlExpr *) node;
4993 if (!exec_simple_check_node((Node *) expr->named_args))
4995 if (!exec_simple_check_node((Node *) expr->args))
5003 NullIfExpr *expr = (NullIfExpr *) node;
5007 if (!exec_simple_check_node((Node *) expr->args))
5014 return exec_simple_check_node((Node *) ((NullTest *) node)->arg);
5017 return exec_simple_check_node((Node *) ((BooleanTest *) node)->arg);
5019 case T_CoerceToDomain:
5020 return exec_simple_check_node((Node *) ((CoerceToDomain *) node)->arg);
5022 case T_CoerceToDomainValue:
5027 List *expr = (List *) node;
5032 if (!exec_simple_check_node(lfirst(l)))
5046 * exec_simple_check_plan - Check if a plan is simple enough to
5047 * be evaluated by ExecEvalExpr() instead
5052 exec_simple_check_plan(PLpgSQL_expr *expr)
5054 CachedPlanSource *plansource;
5060 * Initialize to "not simple", and remember the plan generation number we
5061 * last checked. (If the query produces more or less than one parsetree
5062 * we just leave expr_simple_generation set to 0.)
5064 expr->expr_simple_expr = NULL;
5065 expr->expr_simple_generation = 0;
5068 * 1. We can only evaluate queries that resulted in one single execution
5071 if (list_length(expr->plan->plancache_list) != 1)
5073 plansource = (CachedPlanSource *) linitial(expr->plan->plancache_list);
5074 expr->expr_simple_generation = plansource->generation;
5075 if (list_length(plansource->plan->stmt_list) != 1)
5078 stmt = (PlannedStmt *) linitial(plansource->plan->stmt_list);
5081 * 2. It must be a RESULT plan --> no scan's required
5083 if (!IsA(stmt, PlannedStmt))
5085 plan = stmt->planTree;
5086 if (!IsA(plan, Result))
5090 * 3. Can't have any subplan or qual clause, either
5092 if (plan->lefttree != NULL ||
5093 plan->righttree != NULL ||
5094 plan->initPlan != NULL ||
5095 plan->qual != NULL ||
5096 ((Result *) plan)->resconstantqual != NULL)
5100 * 4. The plan must have a single attribute as result
5102 if (list_length(plan->targetlist) != 1)
5105 tle = (TargetEntry *) linitial(plan->targetlist);
5108 * 5. Check that all the nodes in the expression are non-scary.
5110 if (!exec_simple_check_node((Node *) tle->expr))
5114 * Yes - this is a simple expression. Mark it as such, and initialize
5115 * state to "not valid in current transaction".
5117 expr->expr_simple_expr = tle->expr;
5118 expr->expr_simple_state = NULL;
5119 expr->expr_simple_lxid = InvalidLocalTransactionId;
5120 /* Also stash away the expression result type */
5121 expr->expr_simple_type = exprType((Node *) tle->expr);
5125 * Validates compatibility of supplied TupleDesc pair by checking number and type
5129 validate_tupdesc_compat(TupleDesc expected, TupleDesc returned, const char *msg)
5132 const char *dropped_column_type = gettext_noop("N/A (dropped column)");
5134 if (!expected || !returned)
5136 (errcode(ERRCODE_DATATYPE_MISMATCH),
5137 errmsg("%s", _(msg))));
5139 if (expected->natts != returned->natts)
5141 (errcode(ERRCODE_DATATYPE_MISMATCH),
5142 errmsg("%s", _(msg)),
5143 errdetail("Number of returned columns (%d) does not match "
5144 "expected column count (%d).",
5145 returned->natts, expected->natts)));
5147 for (i = 0; i < expected->natts; i++)
5148 if (expected->attrs[i]->atttypid != returned->attrs[i]->atttypid)
5150 (errcode(ERRCODE_DATATYPE_MISMATCH),
5151 errmsg("%s", _(msg)),
5152 errdetail("Returned type %s does not match expected type "
5153 "%s in column \"%s\".",
5154 OidIsValid(returned->attrs[i]->atttypid) ?
5155 format_type_be(returned->attrs[i]->atttypid) :
5156 _(dropped_column_type),
5157 OidIsValid(expected->attrs[i]->atttypid) ?
5158 format_type_be(expected->attrs[i]->atttypid) :
5159 _(dropped_column_type),
5160 NameStr(expected->attrs[i]->attname))));
5164 * exec_set_found Set the global found variable
5169 exec_set_found(PLpgSQL_execstate *estate, bool state)
5173 var = (PLpgSQL_var *) (estate->datums[estate->found_varno]);
5174 var->value = PointerGetDatum(state);
5175 var->isnull = false;
5179 * plpgsql_create_econtext --- create an eval_econtext for the current function
5181 * We may need to create a new simple_eval_estate too, if there's not one
5182 * already for the current transaction. The EState will be cleaned up at
5186 plpgsql_create_econtext(PLpgSQL_execstate *estate)
5188 SimpleEcontextStackEntry *entry;
5191 * Create an EState for evaluation of simple expressions, if there's not
5192 * one already in the current transaction. The EState is made a child of
5193 * TopTransactionContext so it will have the right lifespan.
5195 if (simple_eval_estate == NULL)
5197 MemoryContext oldcontext;
5199 oldcontext = MemoryContextSwitchTo(TopTransactionContext);
5200 simple_eval_estate = CreateExecutorState();
5201 MemoryContextSwitchTo(oldcontext);
5205 * Create a child econtext for the current function.
5207 estate->eval_econtext = CreateExprContext(simple_eval_estate);
5210 * Make a stack entry so we can clean up the econtext at subxact end.
5211 * Stack entries are kept in TopTransactionContext for simplicity.
5213 entry = (SimpleEcontextStackEntry *)
5214 MemoryContextAlloc(TopTransactionContext,
5215 sizeof(SimpleEcontextStackEntry));
5217 entry->stack_econtext = estate->eval_econtext;
5218 entry->xact_subxid = GetCurrentSubTransactionId();
5220 entry->next = simple_econtext_stack;
5221 simple_econtext_stack = entry;
5225 * plpgsql_destroy_econtext --- destroy function's econtext
5227 * We check that it matches the top stack entry, and destroy the stack
5228 * entry along with the context.
5231 plpgsql_destroy_econtext(PLpgSQL_execstate *estate)
5233 SimpleEcontextStackEntry *next;
5235 Assert(simple_econtext_stack != NULL);
5236 Assert(simple_econtext_stack->stack_econtext == estate->eval_econtext);
5238 next = simple_econtext_stack->next;
5239 pfree(simple_econtext_stack);
5240 simple_econtext_stack = next;
5242 FreeExprContext(estate->eval_econtext, true);
5243 estate->eval_econtext = NULL;
5247 * plpgsql_xact_cb --- post-transaction-commit-or-abort cleanup
5249 * If a simple-expression EState was created in the current transaction,
5250 * it has to be cleaned up.
5253 plpgsql_xact_cb(XactEvent event, void *arg)
5256 * If we are doing a clean transaction shutdown, free the EState (so that
5257 * any remaining resources will be released correctly). In an abort, we
5258 * expect the regular abort recovery procedures to release everything of
5261 if (event != XACT_EVENT_ABORT)
5263 /* Shouldn't be any econtext stack entries left at commit */
5264 Assert(simple_econtext_stack == NULL);
5266 if (simple_eval_estate)
5267 FreeExecutorState(simple_eval_estate);
5268 simple_eval_estate = NULL;
5272 simple_econtext_stack = NULL;
5273 simple_eval_estate = NULL;
5278 * plpgsql_subxact_cb --- post-subtransaction-commit-or-abort cleanup
5280 * Make sure any simple-expression econtexts created in the current
5281 * subtransaction get cleaned up. We have to do this explicitly because
5282 * no other code knows which child econtexts of simple_eval_estate belong
5283 * to which level of subxact.
5286 plpgsql_subxact_cb(SubXactEvent event, SubTransactionId mySubid,
5287 SubTransactionId parentSubid, void *arg)
5289 if (event == SUBXACT_EVENT_START_SUB)
5292 while (simple_econtext_stack != NULL &&
5293 simple_econtext_stack->xact_subxid == mySubid)
5295 SimpleEcontextStackEntry *next;
5297 FreeExprContext(simple_econtext_stack->stack_econtext,
5298 (event == SUBXACT_EVENT_COMMIT_SUB));
5299 next = simple_econtext_stack->next;
5300 pfree(simple_econtext_stack);
5301 simple_econtext_stack = next;
5306 * free_var --- pfree any pass-by-reference value of the variable.
5308 * This should always be followed by some assignment to var->value,
5309 * as it leaves a dangling pointer.
5312 free_var(PLpgSQL_var *var)
5316 pfree(DatumGetPointer(var->value));
5317 var->freeval = false;
5322 * free old value of a text variable and assign new value from C string
5325 assign_text_var(PLpgSQL_var *var, const char *str)
5328 var->value = CStringGetTextDatum(str);
5329 var->isnull = false;
5330 var->freeval = true;
5334 * exec_eval_using_params --- evaluate params of USING clause
5336 static PreparedParamsData *
5337 exec_eval_using_params(PLpgSQL_execstate *estate, List *params)
5339 PreparedParamsData *ppd;
5344 ppd = (PreparedParamsData *) palloc(sizeof(PreparedParamsData));
5345 nargs = list_length(params);
5348 ppd->types = (Oid *) palloc(nargs * sizeof(Oid));
5349 ppd->values = (Datum *) palloc(nargs * sizeof(Datum));
5350 ppd->nulls = (char *) palloc(nargs * sizeof(char));
5351 ppd->freevals = (bool *) palloc(nargs * sizeof(bool));
5356 PLpgSQL_expr *param = (PLpgSQL_expr *) lfirst(lc);
5359 ppd->values[i] = exec_eval_expr(estate, param,
5362 ppd->nulls[i] = isnull ? 'n' : ' ';
5363 ppd->freevals[i] = false;
5365 /* pass-by-ref non null values must be copied into plpgsql context */
5371 get_typlenbyval(ppd->types[i], &typLen, &typByVal);
5374 ppd->values[i] = datumCopy(ppd->values[i], typByVal, typLen);
5375 ppd->freevals[i] = true;
5379 exec_eval_cleanup(estate);
5388 * free_params_data --- pfree all pass-by-reference values used in USING clause
5391 free_params_data(PreparedParamsData *ppd)
5395 for (i = 0; i < ppd->nargs; i++)
5397 if (ppd->freevals[i])
5398 pfree(DatumGetPointer(ppd->values[i]));
5404 pfree(ppd->freevals);
5410 * Open portal for dynamic query
5413 exec_dynquery_with_params(PLpgSQL_execstate *estate, PLpgSQL_expr *dynquery,
5423 * Evaluate the string expression after the EXECUTE keyword. Its result is
5424 * the querystring we have to execute.
5426 query = exec_eval_expr(estate, dynquery, &isnull, &restype);
5429 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
5430 errmsg("query string argument of EXECUTE is null")));
5432 /* Get the C-String representation */
5433 querystr = convert_value_to_string(query, restype);
5435 exec_eval_cleanup(estate);
5438 * Open an implicit cursor for the query. We use
5439 * SPI_cursor_open_with_args even when there are no params, because this
5440 * avoids making and freeing one copy of the plan.
5444 PreparedParamsData *ppd;
5446 ppd = exec_eval_using_params(estate, params);
5447 portal = SPI_cursor_open_with_args(NULL,
5449 ppd->nargs, ppd->types,
5450 ppd->values, ppd->nulls,
5451 estate->readonly_func, 0);
5452 free_params_data(ppd);
5456 portal = SPI_cursor_open_with_args(NULL,
5460 estate->readonly_func, 0);
5464 elog(ERROR, "could not open implicit cursor for query \"%s\": %s",
5465 querystr, SPI_result_code_string(SPI_result));