1 /*-------------------------------------------------------------------------
3 * pl_exec.c - Executor for the PL/pgSQL
6 * Portions Copyright (c) 1996-2010, 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.261.2.4 2010/08/19 18:10:56 tgl Exp $
13 *-------------------------------------------------------------------------
20 #include "access/transam.h"
21 #include "access/tupconvert.h"
22 #include "catalog/pg_proc.h"
23 #include "catalog/pg_type.h"
24 #include "executor/spi_priv.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,
159 static int exec_eval_integer(PLpgSQL_execstate *estate,
162 static bool exec_eval_boolean(PLpgSQL_execstate *estate,
165 static Datum exec_eval_expr(PLpgSQL_execstate *estate,
169 static int exec_run_select(PLpgSQL_execstate *estate,
170 PLpgSQL_expr *expr, long maxtuples, Portal *portalP);
171 static int exec_for_query(PLpgSQL_execstate *estate, PLpgSQL_stmt_forq *stmt,
172 Portal portal, bool prefetch_ok);
173 static ParamListInfo setup_param_list(PLpgSQL_execstate *estate,
175 static void plpgsql_param_fetch(ParamListInfo params, int paramid);
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 exec_set_found(PLpgSQL_execstate *estate, bool state);
195 static void plpgsql_create_econtext(PLpgSQL_execstate *estate);
196 static void plpgsql_destroy_econtext(PLpgSQL_execstate *estate);
197 static void free_var(PLpgSQL_var *var);
198 static void assign_text_var(PLpgSQL_var *var, const char *str);
199 static PreparedParamsData *exec_eval_using_params(PLpgSQL_execstate *estate,
201 static void free_params_data(PreparedParamsData *ppd);
202 static Portal exec_dynquery_with_params(PLpgSQL_execstate *estate,
203 PLpgSQL_expr *dynquery, List *params,
204 const char *portalname, int cursorOptions);
208 * plpgsql_exec_function Called by the call handler for
209 * function execution.
213 plpgsql_exec_function(PLpgSQL_function *func, FunctionCallInfo fcinfo)
215 PLpgSQL_execstate estate;
216 ErrorContextCallback plerrcontext;
221 * Setup the execution state
223 plpgsql_estate_setup(&estate, func, (ReturnSetInfo *) fcinfo->resultinfo);
226 * Setup error traceback support for ereport()
228 plerrcontext.callback = plpgsql_exec_error_callback;
229 plerrcontext.arg = &estate;
230 plerrcontext.previous = error_context_stack;
231 error_context_stack = &plerrcontext;
234 * Make local execution copies of all the datums
236 estate.err_text = gettext_noop("during initialization of execution state");
237 for (i = 0; i < estate.ndatums; i++)
238 estate.datums[i] = copy_plpgsql_datum(func->datums[i]);
241 * Store the actual call argument values into the appropriate variables
243 estate.err_text = gettext_noop("while storing call arguments into local variables");
244 for (i = 0; i < func->fn_nargs; i++)
246 int n = func->fn_argvarnos[i];
248 switch (estate.datums[n]->dtype)
250 case PLPGSQL_DTYPE_VAR:
252 PLpgSQL_var *var = (PLpgSQL_var *) estate.datums[n];
254 var->value = fcinfo->arg[i];
255 var->isnull = fcinfo->argnull[i];
256 var->freeval = false;
260 case PLPGSQL_DTYPE_ROW:
262 PLpgSQL_row *row = (PLpgSQL_row *) estate.datums[n];
264 if (!fcinfo->argnull[i])
270 HeapTupleData tmptup;
272 td = DatumGetHeapTupleHeader(fcinfo->arg[i]);
273 /* Extract rowtype info and find a tupdesc */
274 tupType = HeapTupleHeaderGetTypeId(td);
275 tupTypmod = HeapTupleHeaderGetTypMod(td);
276 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
277 /* Build a temporary HeapTuple control structure */
278 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
279 ItemPointerSetInvalid(&(tmptup.t_self));
280 tmptup.t_tableOid = InvalidOid;
282 exec_move_row(&estate, NULL, row, &tmptup, tupdesc);
283 ReleaseTupleDesc(tupdesc);
287 /* If arg is null, treat it as an empty row */
288 exec_move_row(&estate, NULL, row, NULL, NULL);
294 elog(ERROR, "unrecognized dtype: %d", func->datums[i]->dtype);
298 estate.err_text = gettext_noop("during function entry");
301 * Set the magic variable FOUND to false
303 exec_set_found(&estate, false);
306 * Let the instrumentation plugin peek at this function
308 if (*plugin_ptr && (*plugin_ptr)->func_beg)
309 ((*plugin_ptr)->func_beg) (&estate, func);
312 * Now call the toplevel block of statements
314 estate.err_text = NULL;
315 estate.err_stmt = (PLpgSQL_stmt *) (func->action);
316 rc = exec_stmt_block(&estate, func->action);
317 if (rc != PLPGSQL_RC_RETURN)
319 estate.err_stmt = NULL;
320 estate.err_text = NULL;
323 * Provide a more helpful message if a CONTINUE or RAISE has been used
324 * outside the context it can work in.
326 if (rc == PLPGSQL_RC_CONTINUE)
328 (errcode(ERRCODE_SYNTAX_ERROR),
329 errmsg("CONTINUE cannot be used outside a loop")));
330 else if (rc == PLPGSQL_RC_RERAISE)
332 (errcode(ERRCODE_SYNTAX_ERROR),
333 errmsg("RAISE without parameters cannot be used outside an exception handler")));
336 (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
337 errmsg("control reached end of function without RETURN")));
341 * We got a return value - process it
343 estate.err_stmt = NULL;
344 estate.err_text = gettext_noop("while casting return value to function's return type");
346 fcinfo->isnull = estate.retisnull;
350 ReturnSetInfo *rsi = estate.rsi;
352 /* Check caller can handle a set result */
353 if (!rsi || !IsA(rsi, ReturnSetInfo) ||
354 (rsi->allowedModes & SFRM_Materialize) == 0)
356 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
357 errmsg("set-valued function called in context that cannot accept a set")));
358 rsi->returnMode = SFRM_Materialize;
360 /* If we produced any tuples, send back the result */
361 if (estate.tuple_store)
363 rsi->setResult = estate.tuple_store;
364 if (estate.rettupdesc)
366 MemoryContext oldcxt;
368 oldcxt = MemoryContextSwitchTo(estate.tuple_store_cxt);
369 rsi->setDesc = CreateTupleDescCopy(estate.rettupdesc);
370 MemoryContextSwitchTo(oldcxt);
373 estate.retval = (Datum) 0;
374 fcinfo->isnull = true;
376 else if (!estate.retisnull)
378 if (estate.retistuple)
381 * We have to check that the returned tuple actually matches the
382 * expected result type. XXX would be better to cache the tupdesc
383 * instead of repeating get_call_result_type()
385 HeapTuple rettup = (HeapTuple) DatumGetPointer(estate.retval);
387 TupleConversionMap *tupmap;
389 switch (get_call_result_type(fcinfo, NULL, &tupdesc))
391 case TYPEFUNC_COMPOSITE:
392 /* got the expected result rowtype, now check it */
393 tupmap = convert_tuples_by_position(estate.rettupdesc,
395 gettext_noop("returned record type does not match expected record type"));
396 /* it might need conversion */
398 rettup = do_convert_tuple(rettup, tupmap);
399 /* no need to free map, we're about to return anyway */
401 case TYPEFUNC_RECORD:
404 * Failed to determine actual type of RECORD. We could
405 * raise an error here, but what this means in practice is
406 * that the caller is expecting any old generic rowtype,
407 * so we don't really need to be restrictive. Pass back
408 * the generated result type, instead.
410 tupdesc = estate.rettupdesc;
411 if (tupdesc == NULL) /* shouldn't happen */
412 elog(ERROR, "return type must be a row type");
415 /* shouldn't get here if retistuple is true ... */
416 elog(ERROR, "return type must be a row type");
421 * Copy tuple to upper executor memory, as a tuple Datum. Make
422 * sure it is labeled with the caller-supplied tuple type.
424 estate.retval = PointerGetDatum(SPI_returntuple(rettup, tupdesc));
428 /* Cast value to proper type */
429 estate.retval = exec_cast_value(estate.retval, estate.rettype,
431 &(func->fn_retinput),
432 func->fn_rettypioparam,
437 * If the function's return type isn't by value, copy the value
438 * into upper executor memory context.
440 if (!fcinfo->isnull && !func->fn_retbyval)
445 len = datumGetSize(estate.retval, false, func->fn_rettyplen);
446 tmp = SPI_palloc(len);
447 memcpy(tmp, DatumGetPointer(estate.retval), len);
448 estate.retval = PointerGetDatum(tmp);
453 estate.err_text = gettext_noop("during function exit");
456 * Let the instrumentation plugin peek at this function
458 if (*plugin_ptr && (*plugin_ptr)->func_end)
459 ((*plugin_ptr)->func_end) (&estate, func);
461 /* Clean up any leftover temporary memory */
462 plpgsql_destroy_econtext(&estate);
463 exec_eval_cleanup(&estate);
466 * Pop the error context stack
468 error_context_stack = plerrcontext.previous;
471 * Return the function's result
473 return estate.retval;
478 * plpgsql_exec_trigger Called by the call handler for
483 plpgsql_exec_trigger(PLpgSQL_function *func,
484 TriggerData *trigdata)
486 PLpgSQL_execstate estate;
487 ErrorContextCallback plerrcontext;
491 PLpgSQL_rec *rec_new,
496 * Setup the execution state
498 plpgsql_estate_setup(&estate, func, NULL);
501 * Setup error traceback support for ereport()
503 plerrcontext.callback = plpgsql_exec_error_callback;
504 plerrcontext.arg = &estate;
505 plerrcontext.previous = error_context_stack;
506 error_context_stack = &plerrcontext;
509 * Make local execution copies of all the datums
511 estate.err_text = gettext_noop("during initialization of execution state");
512 for (i = 0; i < estate.ndatums; i++)
513 estate.datums[i] = copy_plpgsql_datum(func->datums[i]);
516 * Put the OLD and NEW tuples into record variables
518 * We make the tupdescs available in both records even though only one may
519 * have a value. This allows parsing of record references to succeed in
520 * functions that are used for multiple trigger types. For example, we
521 * might have a test like "if (TG_OP = 'INSERT' and NEW.foo = 'xyz')",
522 * which should parse regardless of the current trigger type.
524 rec_new = (PLpgSQL_rec *) (estate.datums[func->new_varno]);
525 rec_new->freetup = false;
526 rec_new->tupdesc = trigdata->tg_relation->rd_att;
527 rec_new->freetupdesc = false;
528 rec_old = (PLpgSQL_rec *) (estate.datums[func->old_varno]);
529 rec_old->freetup = false;
530 rec_old->tupdesc = trigdata->tg_relation->rd_att;
531 rec_old->freetupdesc = false;
533 if (TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
536 * Per-statement triggers don't use OLD/NEW variables
541 else if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
543 rec_new->tup = trigdata->tg_trigtuple;
546 else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
548 rec_new->tup = trigdata->tg_newtuple;
549 rec_old->tup = trigdata->tg_trigtuple;
551 else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
554 rec_old->tup = trigdata->tg_trigtuple;
557 elog(ERROR, "unrecognized trigger action: not INSERT, DELETE, or UPDATE");
560 * Assign the special tg_ variables
563 var = (PLpgSQL_var *) (estate.datums[func->tg_op_varno]);
564 if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
565 var->value = CStringGetTextDatum("INSERT");
566 else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
567 var->value = CStringGetTextDatum("UPDATE");
568 else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
569 var->value = CStringGetTextDatum("DELETE");
570 else if (TRIGGER_FIRED_BY_TRUNCATE(trigdata->tg_event))
571 var->value = CStringGetTextDatum("TRUNCATE");
573 elog(ERROR, "unrecognized trigger action: not INSERT, DELETE, UPDATE, or TRUNCATE");
577 var = (PLpgSQL_var *) (estate.datums[func->tg_name_varno]);
578 var->value = DirectFunctionCall1(namein,
579 CStringGetDatum(trigdata->tg_trigger->tgname));
583 var = (PLpgSQL_var *) (estate.datums[func->tg_when_varno]);
584 if (TRIGGER_FIRED_BEFORE(trigdata->tg_event))
585 var->value = CStringGetTextDatum("BEFORE");
586 else if (TRIGGER_FIRED_AFTER(trigdata->tg_event))
587 var->value = CStringGetTextDatum("AFTER");
589 elog(ERROR, "unrecognized trigger execution time: not BEFORE or AFTER");
593 var = (PLpgSQL_var *) (estate.datums[func->tg_level_varno]);
594 if (TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
595 var->value = CStringGetTextDatum("ROW");
596 else if (TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
597 var->value = CStringGetTextDatum("STATEMENT");
599 elog(ERROR, "unrecognized trigger event type: not ROW or STATEMENT");
603 var = (PLpgSQL_var *) (estate.datums[func->tg_relid_varno]);
604 var->value = ObjectIdGetDatum(trigdata->tg_relation->rd_id);
606 var->freeval = false;
608 var = (PLpgSQL_var *) (estate.datums[func->tg_relname_varno]);
609 var->value = DirectFunctionCall1(namein,
610 CStringGetDatum(RelationGetRelationName(trigdata->tg_relation)));
614 var = (PLpgSQL_var *) (estate.datums[func->tg_table_name_varno]);
615 var->value = DirectFunctionCall1(namein,
616 CStringGetDatum(RelationGetRelationName(trigdata->tg_relation)));
620 var = (PLpgSQL_var *) (estate.datums[func->tg_table_schema_varno]);
621 var->value = DirectFunctionCall1(namein,
624 RelationGetNamespace(
625 trigdata->tg_relation))));
629 var = (PLpgSQL_var *) (estate.datums[func->tg_nargs_varno]);
630 var->value = Int16GetDatum(trigdata->tg_trigger->tgnargs);
632 var->freeval = false;
634 var = (PLpgSQL_var *) (estate.datums[func->tg_argv_varno]);
635 if (trigdata->tg_trigger->tgnargs > 0)
638 * For historical reasons, tg_argv[] subscripts start at zero not one.
639 * So we can't use construct_array().
641 int nelems = trigdata->tg_trigger->tgnargs;
646 elems = palloc(sizeof(Datum) * nelems);
647 for (i = 0; i < nelems; i++)
648 elems[i] = CStringGetTextDatum(trigdata->tg_trigger->tgargs[i]);
652 var->value = PointerGetDatum(construct_md_array(elems, NULL,
661 var->value = (Datum) 0;
663 var->freeval = false;
666 estate.err_text = gettext_noop("during function entry");
669 * Set the magic variable FOUND to false
671 exec_set_found(&estate, false);
674 * Let the instrumentation plugin peek at this function
676 if (*plugin_ptr && (*plugin_ptr)->func_beg)
677 ((*plugin_ptr)->func_beg) (&estate, func);
680 * Now call the toplevel block of statements
682 estate.err_text = NULL;
683 estate.err_stmt = (PLpgSQL_stmt *) (func->action);
684 rc = exec_stmt_block(&estate, func->action);
685 if (rc != PLPGSQL_RC_RETURN)
687 estate.err_stmt = NULL;
688 estate.err_text = NULL;
691 * Provide a more helpful message if a CONTINUE or RAISE has been used
692 * outside the context it can work in.
694 if (rc == PLPGSQL_RC_CONTINUE)
696 (errcode(ERRCODE_SYNTAX_ERROR),
697 errmsg("CONTINUE cannot be used outside a loop")));
698 else if (rc == PLPGSQL_RC_RERAISE)
700 (errcode(ERRCODE_SYNTAX_ERROR),
701 errmsg("RAISE without parameters cannot be used outside an exception handler")));
704 (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
705 errmsg("control reached end of trigger procedure without RETURN")));
708 estate.err_stmt = NULL;
709 estate.err_text = gettext_noop("during function exit");
713 (errcode(ERRCODE_DATATYPE_MISMATCH),
714 errmsg("trigger procedure cannot return a set")));
717 * Check that the returned tuple structure has the same attributes, the
718 * relation that fired the trigger has. A per-statement trigger always
719 * needs to return NULL, so we ignore any return value the function itself
720 * produces (XXX: is this a good idea?)
722 * XXX This way it is possible, that the trigger returns a tuple where
723 * attributes don't have the correct atttypmod's length. It's up to the
724 * trigger's programmer to ensure that this doesn't happen. Jan
726 if (estate.retisnull || TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
730 TupleConversionMap *tupmap;
732 rettup = (HeapTuple) DatumGetPointer(estate.retval);
733 /* check rowtype compatibility */
734 tupmap = convert_tuples_by_position(estate.rettupdesc,
735 trigdata->tg_relation->rd_att,
736 gettext_noop("returned row structure does not match the structure of the triggering table"));
737 /* it might need conversion */
739 rettup = do_convert_tuple(rettup, tupmap);
740 /* no need to free map, we're about to return anyway */
742 /* Copy tuple to upper executor memory */
743 rettup = SPI_copytuple(rettup);
747 * Let the instrumentation plugin peek at this function
749 if (*plugin_ptr && (*plugin_ptr)->func_end)
750 ((*plugin_ptr)->func_end) (&estate, func);
752 /* Clean up any leftover temporary memory */
753 plpgsql_destroy_econtext(&estate);
754 exec_eval_cleanup(&estate);
757 * Pop the error context stack
759 error_context_stack = plerrcontext.previous;
762 * Return the trigger's result
769 * error context callback to let us supply a call-stack traceback
772 plpgsql_exec_error_callback(void *arg)
774 PLpgSQL_execstate *estate = (PLpgSQL_execstate *) arg;
776 /* if we are doing RAISE, don't report its location */
777 if (estate->err_text == raise_skip_msg)
780 if (estate->err_text != NULL)
783 * We don't expend the cycles to run gettext() on err_text unless we
784 * actually need it. Therefore, places that set up err_text should
785 * use gettext_noop() to ensure the strings get recorded in the
786 * message dictionary.
788 * If both err_text and err_stmt are set, use the err_text as
789 * description, but report the err_stmt's line number. When err_stmt
790 * is not set, we're in function entry/exit, or some such place not
791 * attached to a specific line number.
793 if (estate->err_stmt != NULL)
796 * translator: last %s is a phrase such as "during statement block
797 * local variable initialization"
799 errcontext("PL/pgSQL function \"%s\" line %d %s",
800 estate->func->fn_name,
801 estate->err_stmt->lineno,
802 _(estate->err_text));
807 * translator: last %s is a phrase such as "while storing call
808 * arguments into local variables"
810 errcontext("PL/pgSQL function \"%s\" %s",
811 estate->func->fn_name,
812 _(estate->err_text));
815 else if (estate->err_stmt != NULL)
817 /* translator: last %s is a plpgsql statement type name */
818 errcontext("PL/pgSQL function \"%s\" line %d at %s",
819 estate->func->fn_name,
820 estate->err_stmt->lineno,
821 plpgsql_stmt_typename(estate->err_stmt));
824 errcontext("PL/pgSQL function \"%s\"",
825 estate->func->fn_name);
830 * Support function for initializing local execution variables
833 static PLpgSQL_datum *
834 copy_plpgsql_datum(PLpgSQL_datum *datum)
836 PLpgSQL_datum *result;
838 switch (datum->dtype)
840 case PLPGSQL_DTYPE_VAR:
842 PLpgSQL_var *new = palloc(sizeof(PLpgSQL_var));
844 memcpy(new, datum, sizeof(PLpgSQL_var));
845 /* Ensure the value is null (possibly not needed?) */
848 new->freeval = false;
850 result = (PLpgSQL_datum *) new;
854 case PLPGSQL_DTYPE_REC:
856 PLpgSQL_rec *new = palloc(sizeof(PLpgSQL_rec));
858 memcpy(new, datum, sizeof(PLpgSQL_rec));
859 /* Ensure the value is null (possibly not needed?) */
862 new->freetup = false;
863 new->freetupdesc = false;
865 result = (PLpgSQL_datum *) new;
869 case PLPGSQL_DTYPE_ROW:
870 case PLPGSQL_DTYPE_RECFIELD:
871 case PLPGSQL_DTYPE_ARRAYELEM:
874 * These datum records are read-only at runtime, so no need to
881 elog(ERROR, "unrecognized dtype: %d", datum->dtype);
882 result = NULL; /* keep compiler quiet */
891 exception_matches_conditions(ErrorData *edata, PLpgSQL_condition *cond)
893 for (; cond != NULL; cond = cond->next)
895 int sqlerrstate = cond->sqlerrstate;
898 * OTHERS matches everything *except* query-canceled; if you're
899 * foolish enough, you can match that explicitly.
901 if (sqlerrstate == 0)
903 if (edata->sqlerrcode != ERRCODE_QUERY_CANCELED)
907 else if (edata->sqlerrcode == sqlerrstate)
909 /* Category match? */
910 else if (ERRCODE_IS_CATEGORY(sqlerrstate) &&
911 ERRCODE_TO_CATEGORY(edata->sqlerrcode) == sqlerrstate)
919 * exec_stmt_block Execute a block of statements
923 exec_stmt_block(PLpgSQL_execstate *estate, PLpgSQL_stmt_block *block)
925 volatile int rc = -1;
930 * First initialize all variables declared in this block
932 estate->err_text = gettext_noop("during statement block local variable initialization");
934 for (i = 0; i < block->n_initvars; i++)
936 n = block->initvarnos[i];
938 switch (estate->datums[n]->dtype)
940 case PLPGSQL_DTYPE_VAR:
942 PLpgSQL_var *var = (PLpgSQL_var *) (estate->datums[n]);
944 /* free any old value, in case re-entering block */
947 /* Initially it contains a NULL */
948 var->value = (Datum) 0;
951 if (var->default_val == NULL)
954 * If needed, give the datatype a chance to reject
955 * NULLs, by assigning a NULL to the variable. We
956 * claim the value is of type UNKNOWN, not the var's
957 * datatype, else coercion will be skipped. (Do this
958 * before the notnull check to be consistent with
959 * exec_assign_value.)
961 if (!var->datatype->typinput.fn_strict)
963 bool valIsNull = true;
965 exec_assign_value(estate,
966 (PLpgSQL_datum *) var,
973 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
974 errmsg("variable \"%s\" declared NOT NULL cannot default to NULL",
979 exec_assign_expr(estate, (PLpgSQL_datum *) var,
985 case PLPGSQL_DTYPE_REC:
987 PLpgSQL_rec *rec = (PLpgSQL_rec *) (estate->datums[n]);
991 heap_freetuple(rec->tup);
992 rec->freetup = false;
994 if (rec->freetupdesc)
996 FreeTupleDesc(rec->tupdesc);
997 rec->freetupdesc = false;
1000 rec->tupdesc = NULL;
1004 case PLPGSQL_DTYPE_RECFIELD:
1005 case PLPGSQL_DTYPE_ARRAYELEM:
1009 elog(ERROR, "unrecognized dtype: %d",
1010 estate->datums[n]->dtype);
1014 if (block->exceptions)
1017 * Execute the statements in the block's body inside a sub-transaction
1019 MemoryContext oldcontext = CurrentMemoryContext;
1020 ResourceOwner oldowner = CurrentResourceOwner;
1021 ExprContext *old_eval_econtext = estate->eval_econtext;
1023 estate->err_text = gettext_noop("during statement block entry");
1025 BeginInternalSubTransaction(NULL);
1026 /* Want to run statements inside function's memory context */
1027 MemoryContextSwitchTo(oldcontext);
1032 * We need to run the block's statements with a new eval_econtext
1033 * that belongs to the current subtransaction; if we try to use
1034 * the outer econtext then ExprContext shutdown callbacks will be
1035 * called at the wrong times.
1037 plpgsql_create_econtext(estate);
1039 estate->err_text = NULL;
1041 /* Run the block's statements */
1042 rc = exec_stmts(estate, block->body);
1044 estate->err_text = gettext_noop("during statement block exit");
1047 * If the block ended with RETURN, we may need to copy the return
1048 * value out of the subtransaction eval_context. This is
1049 * currently only needed for scalar result types --- rowtype
1050 * values will always exist in the function's own memory context.
1052 if (rc == PLPGSQL_RC_RETURN &&
1053 !estate->retisset &&
1054 !estate->retisnull &&
1055 estate->rettupdesc == NULL)
1060 get_typlenbyval(estate->rettype, &resTypLen, &resTypByVal);
1061 estate->retval = datumCopy(estate->retval,
1062 resTypByVal, resTypLen);
1065 /* Commit the inner transaction, return to outer xact context */
1066 ReleaseCurrentSubTransaction();
1067 MemoryContextSwitchTo(oldcontext);
1068 CurrentResourceOwner = oldowner;
1071 * Revert to outer eval_econtext. (The inner one was
1072 * automatically cleaned up during subxact exit.)
1074 estate->eval_econtext = old_eval_econtext;
1077 * AtEOSubXact_SPI() should not have popped any SPI context, but
1078 * just in case it did, make sure we remain connected.
1080 SPI_restore_connection();
1087 estate->err_text = gettext_noop("during exception cleanup");
1089 /* Save error info */
1090 MemoryContextSwitchTo(oldcontext);
1091 edata = CopyErrorData();
1094 /* Abort the inner transaction */
1095 RollbackAndReleaseCurrentSubTransaction();
1096 MemoryContextSwitchTo(oldcontext);
1097 CurrentResourceOwner = oldowner;
1099 /* Revert to outer eval_econtext */
1100 estate->eval_econtext = old_eval_econtext;
1103 * If AtEOSubXact_SPI() popped any SPI context of the subxact, it
1104 * will have left us in a disconnected state. We need this hack
1105 * to return to connected state.
1107 SPI_restore_connection();
1109 /* Must clean up the econtext too */
1110 exec_eval_cleanup(estate);
1112 /* Look for a matching exception handler */
1113 foreach(e, block->exceptions->exc_list)
1115 PLpgSQL_exception *exception = (PLpgSQL_exception *) lfirst(e);
1117 if (exception_matches_conditions(edata, exception->conditions))
1120 * Initialize the magic SQLSTATE and SQLERRM variables for
1121 * the exception block. We needn't do this until we have
1122 * found a matching exception.
1124 PLpgSQL_var *state_var;
1125 PLpgSQL_var *errm_var;
1127 state_var = (PLpgSQL_var *)
1128 estate->datums[block->exceptions->sqlstate_varno];
1129 errm_var = (PLpgSQL_var *)
1130 estate->datums[block->exceptions->sqlerrm_varno];
1132 assign_text_var(state_var,
1133 unpack_sql_state(edata->sqlerrcode));
1134 assign_text_var(errm_var, edata->message);
1136 estate->err_text = NULL;
1138 rc = exec_stmts(estate, exception->action);
1140 free_var(state_var);
1141 state_var->value = (Datum) 0;
1142 state_var->isnull = true;
1144 errm_var->value = (Datum) 0;
1145 errm_var->isnull = true;
1147 /* re-throw error if requested by handler */
1148 if (rc == PLPGSQL_RC_RERAISE)
1149 ReThrowError(edata);
1155 /* If no match found, re-throw the error */
1157 ReThrowError(edata);
1159 FreeErrorData(edata);
1166 * Just execute the statements in the block's body
1168 estate->err_text = NULL;
1170 rc = exec_stmts(estate, block->body);
1173 estate->err_text = NULL;
1176 * Handle the return code.
1181 case PLPGSQL_RC_RETURN:
1182 case PLPGSQL_RC_CONTINUE:
1183 case PLPGSQL_RC_RERAISE:
1186 case PLPGSQL_RC_EXIT:
1189 * This is intentionally different from the handling of RC_EXIT
1190 * for loops: to match a block, we require a match by label.
1192 if (estate->exitlabel == NULL)
1193 return PLPGSQL_RC_EXIT;
1194 if (block->label == NULL)
1195 return PLPGSQL_RC_EXIT;
1196 if (strcmp(block->label, estate->exitlabel) != 0)
1197 return PLPGSQL_RC_EXIT;
1198 estate->exitlabel = NULL;
1199 return PLPGSQL_RC_OK;
1202 elog(ERROR, "unrecognized rc: %d", rc);
1205 return PLPGSQL_RC_OK;
1210 * exec_stmts Iterate over a list of statements
1211 * as long as their return code is OK
1215 exec_stmts(PLpgSQL_execstate *estate, List *stmts)
1222 * Ensure we do a CHECK_FOR_INTERRUPTS() even though there is no
1223 * statement. This prevents hangup in a tight loop if, for instance,
1224 * there is a LOOP construct with an empty body.
1226 CHECK_FOR_INTERRUPTS();
1227 return PLPGSQL_RC_OK;
1232 PLpgSQL_stmt *stmt = (PLpgSQL_stmt *) lfirst(s);
1233 int rc = exec_stmt(estate, stmt);
1235 if (rc != PLPGSQL_RC_OK)
1239 return PLPGSQL_RC_OK;
1244 * exec_stmt Distribute one statement to the statements
1245 * type specific execution function.
1249 exec_stmt(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
1251 PLpgSQL_stmt *save_estmt;
1254 save_estmt = estate->err_stmt;
1255 estate->err_stmt = stmt;
1257 /* Let the plugin know that we are about to execute this statement */
1258 if (*plugin_ptr && (*plugin_ptr)->stmt_beg)
1259 ((*plugin_ptr)->stmt_beg) (estate, stmt);
1261 CHECK_FOR_INTERRUPTS();
1263 switch ((enum PLpgSQL_stmt_types) stmt->cmd_type)
1265 case PLPGSQL_STMT_BLOCK:
1266 rc = exec_stmt_block(estate, (PLpgSQL_stmt_block *) stmt);
1269 case PLPGSQL_STMT_ASSIGN:
1270 rc = exec_stmt_assign(estate, (PLpgSQL_stmt_assign *) stmt);
1273 case PLPGSQL_STMT_PERFORM:
1274 rc = exec_stmt_perform(estate, (PLpgSQL_stmt_perform *) stmt);
1277 case PLPGSQL_STMT_GETDIAG:
1278 rc = exec_stmt_getdiag(estate, (PLpgSQL_stmt_getdiag *) stmt);
1281 case PLPGSQL_STMT_IF:
1282 rc = exec_stmt_if(estate, (PLpgSQL_stmt_if *) stmt);
1285 case PLPGSQL_STMT_CASE:
1286 rc = exec_stmt_case(estate, (PLpgSQL_stmt_case *) stmt);
1289 case PLPGSQL_STMT_LOOP:
1290 rc = exec_stmt_loop(estate, (PLpgSQL_stmt_loop *) stmt);
1293 case PLPGSQL_STMT_WHILE:
1294 rc = exec_stmt_while(estate, (PLpgSQL_stmt_while *) stmt);
1297 case PLPGSQL_STMT_FORI:
1298 rc = exec_stmt_fori(estate, (PLpgSQL_stmt_fori *) stmt);
1301 case PLPGSQL_STMT_FORS:
1302 rc = exec_stmt_fors(estate, (PLpgSQL_stmt_fors *) stmt);
1305 case PLPGSQL_STMT_FORC:
1306 rc = exec_stmt_forc(estate, (PLpgSQL_stmt_forc *) stmt);
1309 case PLPGSQL_STMT_EXIT:
1310 rc = exec_stmt_exit(estate, (PLpgSQL_stmt_exit *) stmt);
1313 case PLPGSQL_STMT_RETURN:
1314 rc = exec_stmt_return(estate, (PLpgSQL_stmt_return *) stmt);
1317 case PLPGSQL_STMT_RETURN_NEXT:
1318 rc = exec_stmt_return_next(estate, (PLpgSQL_stmt_return_next *) stmt);
1321 case PLPGSQL_STMT_RETURN_QUERY:
1322 rc = exec_stmt_return_query(estate, (PLpgSQL_stmt_return_query *) stmt);
1325 case PLPGSQL_STMT_RAISE:
1326 rc = exec_stmt_raise(estate, (PLpgSQL_stmt_raise *) stmt);
1329 case PLPGSQL_STMT_EXECSQL:
1330 rc = exec_stmt_execsql(estate, (PLpgSQL_stmt_execsql *) stmt);
1333 case PLPGSQL_STMT_DYNEXECUTE:
1334 rc = exec_stmt_dynexecute(estate, (PLpgSQL_stmt_dynexecute *) stmt);
1337 case PLPGSQL_STMT_DYNFORS:
1338 rc = exec_stmt_dynfors(estate, (PLpgSQL_stmt_dynfors *) stmt);
1341 case PLPGSQL_STMT_OPEN:
1342 rc = exec_stmt_open(estate, (PLpgSQL_stmt_open *) stmt);
1345 case PLPGSQL_STMT_FETCH:
1346 rc = exec_stmt_fetch(estate, (PLpgSQL_stmt_fetch *) stmt);
1349 case PLPGSQL_STMT_CLOSE:
1350 rc = exec_stmt_close(estate, (PLpgSQL_stmt_close *) stmt);
1354 estate->err_stmt = save_estmt;
1355 elog(ERROR, "unrecognized cmdtype: %d", stmt->cmd_type);
1358 /* Let the plugin know that we have finished executing this statement */
1359 if (*plugin_ptr && (*plugin_ptr)->stmt_end)
1360 ((*plugin_ptr)->stmt_end) (estate, stmt);
1362 estate->err_stmt = save_estmt;
1369 * exec_stmt_assign Evaluate an expression and
1370 * put the result into a variable.
1374 exec_stmt_assign(PLpgSQL_execstate *estate, PLpgSQL_stmt_assign *stmt)
1376 Assert(stmt->varno >= 0);
1378 exec_assign_expr(estate, estate->datums[stmt->varno], stmt->expr);
1380 return PLPGSQL_RC_OK;
1384 * exec_stmt_perform Evaluate query and discard result (but set
1385 * FOUND depending on whether at least one row
1390 exec_stmt_perform(PLpgSQL_execstate *estate, PLpgSQL_stmt_perform *stmt)
1392 PLpgSQL_expr *expr = stmt->expr;
1394 (void) exec_run_select(estate, expr, 0, NULL);
1395 exec_set_found(estate, (estate->eval_processed != 0));
1396 exec_eval_cleanup(estate);
1398 return PLPGSQL_RC_OK;
1402 * exec_stmt_getdiag Put internal PG information into
1403 * specified variables.
1407 exec_stmt_getdiag(PLpgSQL_execstate *estate, PLpgSQL_stmt_getdiag *stmt)
1411 foreach(lc, stmt->diag_items)
1413 PLpgSQL_diag_item *diag_item = (PLpgSQL_diag_item *) lfirst(lc);
1415 bool isnull = false;
1417 if (diag_item->target <= 0)
1420 var = estate->datums[diag_item->target];
1425 switch (diag_item->kind)
1427 case PLPGSQL_GETDIAG_ROW_COUNT:
1429 exec_assign_value(estate, var,
1430 UInt32GetDatum(estate->eval_processed),
1434 case PLPGSQL_GETDIAG_RESULT_OID:
1436 exec_assign_value(estate, var,
1437 ObjectIdGetDatum(estate->eval_lastoid),
1442 elog(ERROR, "unrecognized attribute request: %d",
1447 return PLPGSQL_RC_OK;
1451 * exec_stmt_if Evaluate a bool expression and
1452 * execute the true or false body
1457 exec_stmt_if(PLpgSQL_execstate *estate, PLpgSQL_stmt_if *stmt)
1462 value = exec_eval_boolean(estate, stmt->cond, &isnull);
1463 exec_eval_cleanup(estate);
1465 if (!isnull && value)
1467 if (stmt->true_body != NIL)
1468 return exec_stmts(estate, stmt->true_body);
1472 if (stmt->false_body != NIL)
1473 return exec_stmts(estate, stmt->false_body);
1476 return PLPGSQL_RC_OK;
1485 exec_stmt_case(PLpgSQL_execstate *estate, PLpgSQL_stmt_case *stmt)
1487 PLpgSQL_var *t_var = NULL;
1491 if (stmt->t_expr != NULL)
1497 t_val = exec_eval_expr(estate, stmt->t_expr, &isnull, &t_oid);
1499 t_var = (PLpgSQL_var *) estate->datums[stmt->t_varno];
1502 * When expected datatype is different from real, change it. Note that
1503 * what we're modifying here is an execution copy of the datum, so
1504 * this doesn't affect the originally stored function parse tree.
1506 if (t_var->datatype->typoid != t_oid)
1507 t_var->datatype = plpgsql_build_datatype(t_oid, -1);
1509 /* now we can assign to the variable */
1510 exec_assign_value(estate,
1511 (PLpgSQL_datum *) t_var,
1516 exec_eval_cleanup(estate);
1519 /* Now search for a successful WHEN clause */
1520 foreach(l, stmt->case_when_list)
1522 PLpgSQL_case_when *cwt = (PLpgSQL_case_when *) lfirst(l);
1525 value = exec_eval_boolean(estate, cwt->expr, &isnull);
1526 exec_eval_cleanup(estate);
1527 if (!isnull && value)
1531 /* We can now discard any value we had for the temp variable */
1535 t_var->value = (Datum) 0;
1536 t_var->isnull = true;
1539 /* Evaluate the statement(s), and we're done */
1540 return exec_stmts(estate, cwt->stmts);
1544 /* We can now discard any value we had for the temp variable */
1548 t_var->value = (Datum) 0;
1549 t_var->isnull = true;
1552 /* SQL2003 mandates this error if there was no ELSE clause */
1553 if (!stmt->have_else)
1555 (errcode(ERRCODE_CASE_NOT_FOUND),
1556 errmsg("case not found"),
1557 errhint("CASE statement is missing ELSE part.")));
1559 /* Evaluate the ELSE statements, and we're done */
1560 return exec_stmts(estate, stmt->else_stmts);
1565 * exec_stmt_loop Loop over statements until
1570 exec_stmt_loop(PLpgSQL_execstate *estate, PLpgSQL_stmt_loop *stmt)
1574 int rc = exec_stmts(estate, stmt->body);
1581 case PLPGSQL_RC_EXIT:
1582 if (estate->exitlabel == NULL)
1583 return PLPGSQL_RC_OK;
1584 if (stmt->label == NULL)
1585 return PLPGSQL_RC_EXIT;
1586 if (strcmp(stmt->label, estate->exitlabel) != 0)
1587 return PLPGSQL_RC_EXIT;
1588 estate->exitlabel = NULL;
1589 return PLPGSQL_RC_OK;
1591 case PLPGSQL_RC_CONTINUE:
1592 if (estate->exitlabel == NULL)
1593 /* anonymous continue, so re-run the loop */
1595 else if (stmt->label != NULL &&
1596 strcmp(stmt->label, estate->exitlabel) == 0)
1597 /* label matches named continue, so re-run loop */
1598 estate->exitlabel = NULL;
1600 /* label doesn't match named continue, so propagate upward */
1601 return PLPGSQL_RC_CONTINUE;
1604 case PLPGSQL_RC_RETURN:
1605 case PLPGSQL_RC_RERAISE:
1609 elog(ERROR, "unrecognized rc: %d", rc);
1613 return PLPGSQL_RC_OK;
1618 * exec_stmt_while Loop over statements as long
1619 * as an expression evaluates to
1620 * true or an exit occurs.
1624 exec_stmt_while(PLpgSQL_execstate *estate, PLpgSQL_stmt_while *stmt)
1632 value = exec_eval_boolean(estate, stmt->cond, &isnull);
1633 exec_eval_cleanup(estate);
1635 if (isnull || !value)
1638 rc = exec_stmts(estate, stmt->body);
1645 case PLPGSQL_RC_EXIT:
1646 if (estate->exitlabel == NULL)
1647 return PLPGSQL_RC_OK;
1648 if (stmt->label == NULL)
1649 return PLPGSQL_RC_EXIT;
1650 if (strcmp(stmt->label, estate->exitlabel) != 0)
1651 return PLPGSQL_RC_EXIT;
1652 estate->exitlabel = NULL;
1653 return PLPGSQL_RC_OK;
1655 case PLPGSQL_RC_CONTINUE:
1656 if (estate->exitlabel == NULL)
1657 /* anonymous continue, so re-run loop */
1659 else if (stmt->label != NULL &&
1660 strcmp(stmt->label, estate->exitlabel) == 0)
1661 /* label matches named continue, so re-run loop */
1662 estate->exitlabel = NULL;
1664 /* label doesn't match named continue, propagate upward */
1665 return PLPGSQL_RC_CONTINUE;
1668 case PLPGSQL_RC_RETURN:
1669 case PLPGSQL_RC_RERAISE:
1673 elog(ERROR, "unrecognized rc: %d", rc);
1677 return PLPGSQL_RC_OK;
1682 * exec_stmt_fori Iterate an integer variable
1683 * from a lower to an upper value
1684 * incrementing or decrementing by the BY value
1688 exec_stmt_fori(PLpgSQL_execstate *estate, PLpgSQL_stmt_fori *stmt)
1698 int rc = PLPGSQL_RC_OK;
1700 var = (PLpgSQL_var *) (estate->datums[stmt->var->dno]);
1703 * Get the value of the lower bound
1705 value = exec_eval_expr(estate, stmt->lower, &isnull, &valtype);
1706 value = exec_cast_value(value, valtype, var->datatype->typoid,
1707 &(var->datatype->typinput),
1708 var->datatype->typioparam,
1709 var->datatype->atttypmod, isnull);
1712 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1713 errmsg("lower bound of FOR loop cannot be null")));
1714 loop_value = DatumGetInt32(value);
1715 exec_eval_cleanup(estate);
1718 * Get the value of the upper bound
1720 value = exec_eval_expr(estate, stmt->upper, &isnull, &valtype);
1721 value = exec_cast_value(value, valtype, var->datatype->typoid,
1722 &(var->datatype->typinput),
1723 var->datatype->typioparam,
1724 var->datatype->atttypmod, isnull);
1727 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1728 errmsg("upper bound of FOR loop cannot be null")));
1729 end_value = DatumGetInt32(value);
1730 exec_eval_cleanup(estate);
1733 * Get the step value
1737 value = exec_eval_expr(estate, stmt->step, &isnull, &valtype);
1738 value = exec_cast_value(value, valtype, var->datatype->typoid,
1739 &(var->datatype->typinput),
1740 var->datatype->typioparam,
1741 var->datatype->atttypmod, isnull);
1744 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1745 errmsg("BY value of FOR loop cannot be null")));
1746 step_value = DatumGetInt32(value);
1747 exec_eval_cleanup(estate);
1748 if (step_value <= 0)
1750 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1751 errmsg("BY value of FOR loop must be greater than zero")));
1762 * Check against upper bound
1766 if (loop_value < end_value)
1771 if (loop_value > end_value)
1775 found = true; /* looped at least once */
1778 * Assign current value to loop var
1780 var->value = Int32GetDatum(loop_value);
1781 var->isnull = false;
1784 * Execute the statements
1786 rc = exec_stmts(estate, stmt->body);
1788 if (rc == PLPGSQL_RC_RETURN ||
1789 rc == PLPGSQL_RC_RERAISE)
1790 break; /* break out of the loop */
1791 else if (rc == PLPGSQL_RC_EXIT)
1793 if (estate->exitlabel == NULL)
1794 /* unlabelled exit, finish the current loop */
1796 else if (stmt->label != NULL &&
1797 strcmp(stmt->label, estate->exitlabel) == 0)
1799 /* labelled exit, matches the current stmt's label */
1800 estate->exitlabel = NULL;
1805 * otherwise, this is a labelled exit that does not match the
1806 * current statement's label, if any: return RC_EXIT so that the
1807 * EXIT continues to propagate up the stack.
1811 else if (rc == PLPGSQL_RC_CONTINUE)
1813 if (estate->exitlabel == NULL)
1814 /* unlabelled continue, so re-run the current loop */
1816 else if (stmt->label != NULL &&
1817 strcmp(stmt->label, estate->exitlabel) == 0)
1819 /* label matches named continue, so re-run loop */
1820 estate->exitlabel = NULL;
1826 * otherwise, this is a named continue that does not match the
1827 * current statement's label, if any: return RC_CONTINUE so
1828 * that the CONTINUE will propagate up the stack.
1835 * Increase/decrease loop value, unless it would overflow, in which
1836 * case exit the loop.
1840 if ((int32) (loop_value - step_value) > loop_value)
1842 loop_value -= step_value;
1846 if ((int32) (loop_value + step_value) < loop_value)
1848 loop_value += step_value;
1853 * Set the FOUND variable to indicate the result of executing the loop
1854 * (namely, whether we looped one or more times). This must be set here so
1855 * that it does not interfere with the value of the FOUND variable inside
1856 * the loop processing itself.
1858 exec_set_found(estate, found);
1865 * exec_stmt_fors Execute a query, assign each
1866 * tuple to a record or row and
1867 * execute a group of statements
1872 exec_stmt_fors(PLpgSQL_execstate *estate, PLpgSQL_stmt_fors *stmt)
1878 * Open the implicit cursor for the statement using exec_run_select
1880 exec_run_select(estate, stmt->query, 0, &portal);
1885 rc = exec_for_query(estate, (PLpgSQL_stmt_forq *) stmt, portal, true);
1888 * Close the implicit cursor
1890 SPI_cursor_close(portal);
1897 * exec_stmt_forc Execute a loop for each row from a cursor.
1901 exec_stmt_forc(PLpgSQL_execstate *estate, PLpgSQL_stmt_forc *stmt)
1903 PLpgSQL_var *curvar;
1904 char *curname = NULL;
1905 const char *portalname;
1906 PLpgSQL_expr *query;
1907 ParamListInfo paramLI;
1912 * Get the cursor variable and if it has an assigned name, check
1913 * that it's not in use currently.
1916 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
1917 if (!curvar->isnull)
1919 curname = TextDatumGetCString(curvar->value);
1920 if (SPI_cursor_find(curname) != NULL)
1922 (errcode(ERRCODE_DUPLICATE_CURSOR),
1923 errmsg("cursor \"%s\" already in use", curname)));
1927 * Open the cursor just like an OPEN command
1929 * Note: parser should already have checked that statement supplies
1930 * args iff cursor needs them, but we check again to be safe.
1933 if (stmt->argquery != NULL)
1936 * OPEN CURSOR with args. We fake a SELECT ... INTO ...
1937 * statement to evaluate the args and put 'em into the
1941 PLpgSQL_stmt_execsql set_args;
1943 if (curvar->cursor_explicit_argrow < 0)
1945 (errcode(ERRCODE_SYNTAX_ERROR),
1946 errmsg("arguments given for cursor without arguments")));
1948 memset(&set_args, 0, sizeof(set_args));
1949 set_args.cmd_type = PLPGSQL_STMT_EXECSQL;
1950 set_args.lineno = stmt->lineno;
1951 set_args.sqlstmt = stmt->argquery;
1952 set_args.into = true;
1953 /* XXX historically this has not been STRICT */
1954 set_args.row = (PLpgSQL_row *)
1955 (estate->datums[curvar->cursor_explicit_argrow]);
1957 if (exec_stmt_execsql(estate, &set_args) != PLPGSQL_RC_OK)
1958 elog(ERROR, "open cursor failed during argument processing");
1962 if (curvar->cursor_explicit_argrow >= 0)
1964 (errcode(ERRCODE_SYNTAX_ERROR),
1965 errmsg("arguments required for cursor")));
1968 query = curvar->cursor_explicit_expr;
1971 if (query->plan == NULL)
1972 exec_prepare_plan(estate, query, curvar->cursor_options);
1975 * Set up ParamListInfo (note this is only carrying a hook function, not
1976 * any actual data values, at this point)
1978 paramLI = setup_param_list(estate, query);
1981 * Open the cursor (the paramlist will get copied into the portal)
1983 portal = SPI_cursor_open_with_paramlist(curname, query->plan,
1985 estate->readonly_func);
1987 elog(ERROR, "could not open cursor: %s",
1988 SPI_result_code_string(SPI_result));
1989 portalname = portal->name;
1991 /* don't need paramlist any more */
1996 * If cursor variable was NULL, store the generated portal name in it
1998 if (curname == NULL)
1999 assign_text_var(curvar, portal->name);
2002 * Execute the loop. We can't prefetch because the cursor is accessible
2003 * to the user, for instance via UPDATE WHERE CURRENT OF within the loop.
2005 rc = exec_for_query(estate, (PLpgSQL_stmt_forq *) stmt, portal, false);
2008 * Close portal, and restore cursor variable if it was initially NULL.
2011 SPI_cursor_close(portal);
2013 if (curname == NULL)
2016 curvar->value = (Datum) 0;
2017 curvar->isnull = true;
2028 * exec_stmt_exit Implements EXIT and CONTINUE
2030 * This begins the process of exiting / restarting a loop.
2034 exec_stmt_exit(PLpgSQL_execstate *estate, PLpgSQL_stmt_exit *stmt)
2037 * If the exit / continue has a condition, evaluate it
2039 if (stmt->cond != NULL)
2044 value = exec_eval_boolean(estate, stmt->cond, &isnull);
2045 exec_eval_cleanup(estate);
2046 if (isnull || value == false)
2047 return PLPGSQL_RC_OK;
2050 estate->exitlabel = stmt->label;
2052 return PLPGSQL_RC_EXIT;
2054 return PLPGSQL_RC_CONTINUE;
2059 * exec_stmt_return Evaluate an expression and start
2060 * returning from the function.
2064 exec_stmt_return(PLpgSQL_execstate *estate, PLpgSQL_stmt_return *stmt)
2067 * If processing a set-returning PL/PgSQL function, the final RETURN
2068 * indicates that the function is finished producing tuples. The rest of
2069 * the work will be done at the top level.
2071 if (estate->retisset)
2072 return PLPGSQL_RC_RETURN;
2074 /* initialize for null result (possibly a tuple) */
2075 estate->retval = (Datum) 0;
2076 estate->rettupdesc = NULL;
2077 estate->retisnull = true;
2079 if (stmt->retvarno >= 0)
2081 PLpgSQL_datum *retvar = estate->datums[stmt->retvarno];
2083 switch (retvar->dtype)
2085 case PLPGSQL_DTYPE_VAR:
2087 PLpgSQL_var *var = (PLpgSQL_var *) retvar;
2089 estate->retval = var->value;
2090 estate->retisnull = var->isnull;
2091 estate->rettype = var->datatype->typoid;
2095 case PLPGSQL_DTYPE_REC:
2097 PLpgSQL_rec *rec = (PLpgSQL_rec *) retvar;
2099 if (HeapTupleIsValid(rec->tup))
2101 estate->retval = PointerGetDatum(rec->tup);
2102 estate->rettupdesc = rec->tupdesc;
2103 estate->retisnull = false;
2108 case PLPGSQL_DTYPE_ROW:
2110 PLpgSQL_row *row = (PLpgSQL_row *) retvar;
2112 Assert(row->rowtupdesc);
2114 PointerGetDatum(make_tuple_from_row(estate, row,
2116 if (DatumGetPointer(estate->retval) == NULL) /* should not happen */
2117 elog(ERROR, "row not compatible with its own tupdesc");
2118 estate->rettupdesc = row->rowtupdesc;
2119 estate->retisnull = false;
2124 elog(ERROR, "unrecognized dtype: %d", retvar->dtype);
2127 return PLPGSQL_RC_RETURN;
2130 if (stmt->expr != NULL)
2132 if (estate->retistuple)
2134 exec_run_select(estate, stmt->expr, 1, NULL);
2135 if (estate->eval_processed > 0)
2137 estate->retval = PointerGetDatum(estate->eval_tuptable->vals[0]);
2138 estate->rettupdesc = estate->eval_tuptable->tupdesc;
2139 estate->retisnull = false;
2144 /* Normal case for scalar results */
2145 estate->retval = exec_eval_expr(estate, stmt->expr,
2146 &(estate->retisnull),
2147 &(estate->rettype));
2150 return PLPGSQL_RC_RETURN;
2154 * Special hack for function returning VOID: instead of NULL, return a
2155 * non-null VOID value. This is of dubious importance but is kept for
2156 * backwards compatibility. Note that the only other way to get here is
2157 * to have written "RETURN NULL" in a function returning tuple.
2159 if (estate->fn_rettype == VOIDOID)
2161 estate->retval = (Datum) 0;
2162 estate->retisnull = false;
2163 estate->rettype = VOIDOID;
2166 return PLPGSQL_RC_RETURN;
2170 * exec_stmt_return_next Evaluate an expression and add it to the
2171 * list of tuples returned by the current
2176 exec_stmt_return_next(PLpgSQL_execstate *estate,
2177 PLpgSQL_stmt_return_next *stmt)
2181 HeapTuple tuple = NULL;
2182 bool free_tuple = false;
2184 if (!estate->retisset)
2186 (errcode(ERRCODE_SYNTAX_ERROR),
2187 errmsg("cannot use RETURN NEXT in a non-SETOF function")));
2189 if (estate->tuple_store == NULL)
2190 exec_init_tuple_store(estate);
2192 /* rettupdesc will be filled by exec_init_tuple_store */
2193 tupdesc = estate->rettupdesc;
2194 natts = tupdesc->natts;
2196 if (stmt->retvarno >= 0)
2198 PLpgSQL_datum *retvar = estate->datums[stmt->retvarno];
2200 switch (retvar->dtype)
2202 case PLPGSQL_DTYPE_VAR:
2204 PLpgSQL_var *var = (PLpgSQL_var *) retvar;
2205 Datum retval = var->value;
2206 bool isNull = var->isnull;
2210 (errcode(ERRCODE_DATATYPE_MISMATCH),
2211 errmsg("wrong result type supplied in RETURN NEXT")));
2213 /* coerce type if needed */
2214 retval = exec_simple_cast_value(retval,
2215 var->datatype->typoid,
2216 tupdesc->attrs[0]->atttypid,
2217 tupdesc->attrs[0]->atttypmod,
2220 tuplestore_putvalues(estate->tuple_store, tupdesc,
2225 case PLPGSQL_DTYPE_REC:
2227 PLpgSQL_rec *rec = (PLpgSQL_rec *) retvar;
2228 TupleConversionMap *tupmap;
2230 if (!HeapTupleIsValid(rec->tup))
2232 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2233 errmsg("record \"%s\" is not assigned yet",
2235 errdetail("The tuple structure of a not-yet-assigned"
2236 " record is indeterminate.")));
2237 tupmap = convert_tuples_by_position(rec->tupdesc,
2239 gettext_noop("wrong record type supplied in RETURN NEXT"));
2241 /* it might need conversion */
2244 tuple = do_convert_tuple(tuple, tupmap);
2245 free_conversion_map(tupmap);
2250 case PLPGSQL_DTYPE_ROW:
2252 PLpgSQL_row *row = (PLpgSQL_row *) retvar;
2254 tuple = make_tuple_from_row(estate, row, tupdesc);
2257 (errcode(ERRCODE_DATATYPE_MISMATCH),
2258 errmsg("wrong record type supplied in RETURN NEXT")));
2264 elog(ERROR, "unrecognized dtype: %d", retvar->dtype);
2268 else if (stmt->expr)
2276 (errcode(ERRCODE_DATATYPE_MISMATCH),
2277 errmsg("wrong result type supplied in RETURN NEXT")));
2279 retval = exec_eval_expr(estate,
2284 /* coerce type if needed */
2285 retval = exec_simple_cast_value(retval,
2287 tupdesc->attrs[0]->atttypid,
2288 tupdesc->attrs[0]->atttypmod,
2291 tuplestore_putvalues(estate->tuple_store, tupdesc,
2294 exec_eval_cleanup(estate);
2299 (errcode(ERRCODE_SYNTAX_ERROR),
2300 errmsg("RETURN NEXT must have a parameter")));
2303 if (HeapTupleIsValid(tuple))
2305 tuplestore_puttuple(estate->tuple_store, tuple);
2308 heap_freetuple(tuple);
2311 return PLPGSQL_RC_OK;
2315 * exec_stmt_return_query Evaluate a query and add it to the
2316 * list of tuples returned by the current
2321 exec_stmt_return_query(PLpgSQL_execstate *estate,
2322 PLpgSQL_stmt_return_query *stmt)
2325 uint32 processed = 0;
2326 TupleConversionMap *tupmap;
2328 if (!estate->retisset)
2330 (errcode(ERRCODE_SYNTAX_ERROR),
2331 errmsg("cannot use RETURN QUERY in a non-SETOF function")));
2333 if (estate->tuple_store == NULL)
2334 exec_init_tuple_store(estate);
2336 if (stmt->query != NULL)
2339 exec_run_select(estate, stmt->query, 0, &portal);
2343 /* RETURN QUERY EXECUTE */
2344 Assert(stmt->dynquery != NULL);
2345 portal = exec_dynquery_with_params(estate, stmt->dynquery,
2346 stmt->params, NULL, 0);
2349 tupmap = convert_tuples_by_position(portal->tupDesc,
2351 gettext_noop("structure of query does not match function result type"));
2357 SPI_cursor_fetch(portal, true, 50);
2358 if (SPI_processed == 0)
2361 for (i = 0; i < SPI_processed; i++)
2363 HeapTuple tuple = SPI_tuptable->vals[i];
2366 tuple = do_convert_tuple(tuple, tupmap);
2367 tuplestore_puttuple(estate->tuple_store, tuple);
2369 heap_freetuple(tuple);
2373 SPI_freetuptable(SPI_tuptable);
2377 free_conversion_map(tupmap);
2379 SPI_freetuptable(SPI_tuptable);
2380 SPI_cursor_close(portal);
2382 estate->eval_processed = processed;
2383 exec_set_found(estate, processed != 0);
2385 return PLPGSQL_RC_OK;
2389 exec_init_tuple_store(PLpgSQL_execstate *estate)
2391 ReturnSetInfo *rsi = estate->rsi;
2392 MemoryContext oldcxt;
2393 ResourceOwner oldowner;
2396 * Check caller can handle a set result in the way we want
2398 if (!rsi || !IsA(rsi, ReturnSetInfo) ||
2399 (rsi->allowedModes & SFRM_Materialize) == 0 ||
2400 rsi->expectedDesc == NULL)
2402 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2403 errmsg("set-valued function called in context that cannot accept a set")));
2406 * Switch to the right memory context and resource owner for storing the
2407 * tuplestore for return set. If we're within a subtransaction opened for
2408 * an exception-block, for example, we must still create the tuplestore in
2409 * the resource owner that was active when this function was entered, and
2410 * not in the subtransaction resource owner.
2412 oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
2413 oldowner = CurrentResourceOwner;
2414 CurrentResourceOwner = estate->tuple_store_owner;
2416 estate->tuple_store =
2417 tuplestore_begin_heap(rsi->allowedModes & SFRM_Materialize_Random,
2420 CurrentResourceOwner = oldowner;
2421 MemoryContextSwitchTo(oldcxt);
2423 estate->rettupdesc = rsi->expectedDesc;
2427 * exec_stmt_raise Build a message and throw it with elog()
2431 exec_stmt_raise(PLpgSQL_execstate *estate, PLpgSQL_stmt_raise *stmt)
2434 char *condname = NULL;
2435 char *err_message = NULL;
2436 char *err_detail = NULL;
2437 char *err_hint = NULL;
2440 /* RAISE with no parameters: re-throw current exception */
2441 if (stmt->condname == NULL && stmt->message == NULL &&
2442 stmt->options == NIL)
2443 return PLPGSQL_RC_RERAISE;
2447 err_code = plpgsql_recognize_err_condition(stmt->condname, true);
2448 condname = pstrdup(stmt->condname);
2454 ListCell *current_param;
2457 initStringInfo(&ds);
2458 current_param = list_head(stmt->params);
2460 for (cp = stmt->message; *cp; cp++)
2463 * Occurrences of a single % are replaced by the next parameter's
2464 * external representation. Double %'s are converted to one %.
2475 appendStringInfoChar(&ds, '%');
2480 if (current_param == NULL)
2482 (errcode(ERRCODE_SYNTAX_ERROR),
2483 errmsg("too few parameters specified for RAISE")));
2485 paramvalue = exec_eval_expr(estate,
2486 (PLpgSQL_expr *) lfirst(current_param),
2493 extval = convert_value_to_string(paramvalue, paramtypeid);
2494 appendStringInfoString(&ds, extval);
2495 current_param = lnext(current_param);
2496 exec_eval_cleanup(estate);
2499 appendStringInfoChar(&ds, cp[0]);
2503 * If more parameters were specified than were required to process the
2504 * format string, throw an error
2506 if (current_param != NULL)
2508 (errcode(ERRCODE_SYNTAX_ERROR),
2509 errmsg("too many parameters specified for RAISE")));
2511 err_message = ds.data;
2512 /* No pfree(ds.data), the pfree(err_message) does it */
2515 foreach(lc, stmt->options)
2517 PLpgSQL_raise_option *opt = (PLpgSQL_raise_option *) lfirst(lc);
2523 optionvalue = exec_eval_expr(estate, opt->expr,
2528 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2529 errmsg("RAISE statement option cannot be null")));
2531 extval = convert_value_to_string(optionvalue, optiontypeid);
2533 switch (opt->opt_type)
2535 case PLPGSQL_RAISEOPTION_ERRCODE:
2538 (errcode(ERRCODE_SYNTAX_ERROR),
2539 errmsg("RAISE option already specified: %s",
2541 err_code = plpgsql_recognize_err_condition(extval, true);
2542 condname = pstrdup(extval);
2544 case PLPGSQL_RAISEOPTION_MESSAGE:
2547 (errcode(ERRCODE_SYNTAX_ERROR),
2548 errmsg("RAISE option already specified: %s",
2550 err_message = pstrdup(extval);
2552 case PLPGSQL_RAISEOPTION_DETAIL:
2555 (errcode(ERRCODE_SYNTAX_ERROR),
2556 errmsg("RAISE option already specified: %s",
2558 err_detail = pstrdup(extval);
2560 case PLPGSQL_RAISEOPTION_HINT:
2563 (errcode(ERRCODE_SYNTAX_ERROR),
2564 errmsg("RAISE option already specified: %s",
2566 err_hint = pstrdup(extval);
2569 elog(ERROR, "unrecognized raise option: %d", opt->opt_type);
2572 exec_eval_cleanup(estate);
2575 /* Default code if nothing specified */
2576 if (err_code == 0 && stmt->elog_level >= ERROR)
2577 err_code = ERRCODE_RAISE_EXCEPTION;
2579 /* Default error message if nothing specified */
2580 if (err_message == NULL)
2584 err_message = condname;
2588 err_message = pstrdup(unpack_sql_state(err_code));
2592 * Throw the error (may or may not come back)
2594 estate->err_text = raise_skip_msg; /* suppress traceback of raise */
2596 ereport(stmt->elog_level,
2597 (err_code ? errcode(err_code) : 0,
2598 errmsg_internal("%s", err_message),
2599 (err_detail != NULL) ? errdetail("%s", err_detail) : 0,
2600 (err_hint != NULL) ? errhint("%s", err_hint) : 0));
2602 estate->err_text = NULL; /* un-suppress... */
2604 if (condname != NULL)
2606 if (err_message != NULL)
2608 if (err_detail != NULL)
2610 if (err_hint != NULL)
2613 return PLPGSQL_RC_OK;
2618 * Initialize a mostly empty execution state
2622 plpgsql_estate_setup(PLpgSQL_execstate *estate,
2623 PLpgSQL_function *func,
2626 /* this link will be restored at exit from plpgsql_call_handler */
2627 func->cur_estate = estate;
2629 estate->func = func;
2631 estate->retval = (Datum) 0;
2632 estate->retisnull = true;
2633 estate->rettype = InvalidOid;
2635 estate->fn_rettype = func->fn_rettype;
2636 estate->retistuple = func->fn_retistuple;
2637 estate->retisset = func->fn_retset;
2639 estate->readonly_func = func->fn_readonly;
2641 estate->rettupdesc = NULL;
2642 estate->exitlabel = NULL;
2644 estate->tuple_store = NULL;
2647 estate->tuple_store_cxt = rsi->econtext->ecxt_per_query_memory;
2648 estate->tuple_store_owner = CurrentResourceOwner;
2652 estate->tuple_store_cxt = NULL;
2653 estate->tuple_store_owner = NULL;
2657 estate->found_varno = func->found_varno;
2658 estate->ndatums = func->ndatums;
2659 estate->datums = palloc(sizeof(PLpgSQL_datum *) * estate->ndatums);
2660 /* caller is expected to fill the datums array */
2662 estate->eval_tuptable = NULL;
2663 estate->eval_processed = 0;
2664 estate->eval_lastoid = InvalidOid;
2665 estate->eval_econtext = NULL;
2666 estate->cur_expr = NULL;
2668 estate->err_stmt = NULL;
2669 estate->err_text = NULL;
2671 estate->plugin_info = NULL;
2674 * Create an EState and ExprContext for evaluation of simple expressions.
2676 plpgsql_create_econtext(estate);
2679 * Let the plugin see this function before we initialize any local
2680 * PL/pgSQL variables - note that we also give the plugin a few function
2681 * pointers so it can call back into PL/pgSQL for doing things like
2682 * variable assignments and stack traces
2686 (*plugin_ptr)->error_callback = plpgsql_exec_error_callback;
2687 (*plugin_ptr)->assign_expr = exec_assign_expr;
2689 if ((*plugin_ptr)->func_setup)
2690 ((*plugin_ptr)->func_setup) (estate, func);
2695 * Release temporary memory used by expression/subselect evaluation
2697 * NB: the result of the evaluation is no longer valid after this is done,
2698 * unless it is a pass-by-value datatype.
2700 * NB: if you change this code, see also the hacks in exec_assign_value's
2701 * PLPGSQL_DTYPE_ARRAYELEM case.
2705 exec_eval_cleanup(PLpgSQL_execstate *estate)
2707 /* Clear result of a full SPI_execute */
2708 if (estate->eval_tuptable != NULL)
2709 SPI_freetuptable(estate->eval_tuptable);
2710 estate->eval_tuptable = NULL;
2712 /* Clear result of exec_eval_simple_expr (but keep the econtext) */
2713 if (estate->eval_econtext != NULL)
2714 ResetExprContext(estate->eval_econtext);
2719 * Generate a prepared plan
2723 exec_prepare_plan(PLpgSQL_execstate *estate,
2724 PLpgSQL_expr *expr, int cursorOptions)
2729 * The grammar can't conveniently set expr->func while building the parse
2730 * tree, so make sure it's set before parser hooks need it.
2732 expr->func = estate->func;
2735 * Generate and save the plan
2737 plan = SPI_prepare_params(expr->query,
2738 (ParserSetupHook) plpgsql_parser_setup,
2743 /* Some SPI errors deserve specific error messages */
2746 case SPI_ERROR_COPY:
2748 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2749 errmsg("cannot COPY to/from client in PL/pgSQL")));
2750 case SPI_ERROR_TRANSACTION:
2752 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2753 errmsg("cannot begin/end transactions in PL/pgSQL"),
2754 errhint("Use a BEGIN block with an EXCEPTION clause instead.")));
2756 elog(ERROR, "SPI_prepare_params failed for \"%s\": %s",
2757 expr->query, SPI_result_code_string(SPI_result));
2760 expr->plan = SPI_saveplan(plan);
2762 exec_simple_check_plan(expr);
2767 * exec_stmt_execsql Execute an SQL statement (possibly with INTO).
2771 exec_stmt_execsql(PLpgSQL_execstate *estate,
2772 PLpgSQL_stmt_execsql *stmt)
2774 ParamListInfo paramLI;
2777 PLpgSQL_expr *expr = stmt->sqlstmt;
2780 * On the first call for this statement generate the plan, and detect
2781 * whether the statement is INSERT/UPDATE/DELETE
2783 if (expr->plan == NULL)
2787 exec_prepare_plan(estate, expr, 0);
2788 stmt->mod_stmt = false;
2789 foreach(l, expr->plan->plancache_list)
2791 CachedPlanSource *plansource = (CachedPlanSource *) lfirst(l);
2794 foreach(l2, plansource->plan->stmt_list)
2796 PlannedStmt *p = (PlannedStmt *) lfirst(l2);
2798 if (IsA(p, PlannedStmt) &&
2801 if (p->commandType == CMD_INSERT ||
2802 p->commandType == CMD_UPDATE ||
2803 p->commandType == CMD_DELETE)
2804 stmt->mod_stmt = true;
2811 * Set up ParamListInfo (note this is only carrying a hook function, not
2812 * any actual data values, at this point)
2814 paramLI = setup_param_list(estate, expr);
2817 * If we have INTO, then we only need one row back ... but if we have INTO
2818 * STRICT, ask for two rows, so that we can verify the statement returns
2819 * only one. INSERT/UPDATE/DELETE are always treated strictly. Without
2820 * INTO, just run the statement to completion (tcount = 0).
2822 * We could just ask for two rows always when using INTO, but there are
2823 * some cases where demanding the extra row costs significant time, eg by
2824 * forcing completion of a sequential scan. So don't do it unless we need
2825 * to enforce strictness.
2829 if (stmt->strict || stmt->mod_stmt)
2840 rc = SPI_execute_plan_with_paramlist(expr->plan, paramLI,
2841 estate->readonly_func, tcount);
2844 * Check for error, and set FOUND if appropriate (for historical reasons
2845 * we set FOUND only for certain query types). Also Assert that we
2846 * identified the statement type the same as SPI did.
2851 Assert(!stmt->mod_stmt);
2852 exec_set_found(estate, (SPI_processed != 0));
2858 case SPI_OK_INSERT_RETURNING:
2859 case SPI_OK_UPDATE_RETURNING:
2860 case SPI_OK_DELETE_RETURNING:
2861 Assert(stmt->mod_stmt);
2862 exec_set_found(estate, (SPI_processed != 0));
2865 case SPI_OK_SELINTO:
2866 case SPI_OK_UTILITY:
2867 Assert(!stmt->mod_stmt);
2870 case SPI_OK_REWRITTEN:
2871 Assert(!stmt->mod_stmt);
2874 * The command was rewritten into another kind of command. It's
2875 * not clear what FOUND would mean in that case (and SPI doesn't
2876 * return the row count either), so just set it to false.
2878 exec_set_found(estate, false);
2882 elog(ERROR, "SPI_execute_plan_with_paramlist failed executing query \"%s\": %s",
2883 expr->query, SPI_result_code_string(rc));
2886 /* All variants should save result info for GET DIAGNOSTICS */
2887 estate->eval_processed = SPI_processed;
2888 estate->eval_lastoid = SPI_lastoid;
2890 /* Process INTO if present */
2893 SPITupleTable *tuptab = SPI_tuptable;
2894 uint32 n = SPI_processed;
2895 PLpgSQL_rec *rec = NULL;
2896 PLpgSQL_row *row = NULL;
2898 /* If the statement did not return a tuple table, complain */
2901 (errcode(ERRCODE_SYNTAX_ERROR),
2902 errmsg("INTO used with a command that cannot return data")));
2904 /* Determine if we assign to a record or a row */
2905 if (stmt->rec != NULL)
2906 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->dno]);
2907 else if (stmt->row != NULL)
2908 row = (PLpgSQL_row *) (estate->datums[stmt->row->dno]);
2910 elog(ERROR, "unsupported target");
2913 * If SELECT ... INTO specified STRICT, and the query didn't find
2914 * exactly one row, throw an error. If STRICT was not specified, then
2915 * allow the query to find any number of rows.
2921 (errcode(ERRCODE_NO_DATA_FOUND),
2922 errmsg("query returned no rows")));
2923 /* set the target to NULL(s) */
2924 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
2928 if (n > 1 && (stmt->strict || stmt->mod_stmt))
2930 (errcode(ERRCODE_TOO_MANY_ROWS),
2931 errmsg("query returned more than one row")));
2932 /* Put the first result row into the target */
2933 exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
2937 SPI_freetuptable(SPI_tuptable);
2941 /* If the statement returned a tuple table, complain */
2942 if (SPI_tuptable != NULL)
2944 (errcode(ERRCODE_SYNTAX_ERROR),
2945 errmsg("query has no destination for result data"),
2946 (rc == SPI_OK_SELECT) ? errhint("If you want to discard the results of a SELECT, use PERFORM instead.") : 0));
2952 return PLPGSQL_RC_OK;
2957 * exec_stmt_dynexecute Execute a dynamic SQL query
2958 * (possibly with INTO).
2962 exec_stmt_dynexecute(PLpgSQL_execstate *estate,
2963 PLpgSQL_stmt_dynexecute *stmt)
2966 bool isnull = false;
2972 * First we evaluate the string expression after the EXECUTE keyword. Its
2973 * result is the querystring we have to execute.
2975 query = exec_eval_expr(estate, stmt->query, &isnull, &restype);
2978 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2979 errmsg("query string argument of EXECUTE is null")));
2981 /* Get the C-String representation */
2982 querystr = convert_value_to_string(query, restype);
2984 exec_eval_cleanup(estate);
2987 * Execute the query without preparing a saved plan.
2991 PreparedParamsData *ppd;
2993 ppd = exec_eval_using_params(estate, stmt->params);
2994 exec_res = SPI_execute_with_args(querystr,
2995 ppd->nargs, ppd->types,
2996 ppd->values, ppd->nulls,
2997 estate->readonly_func, 0);
2998 free_params_data(ppd);
3001 exec_res = SPI_execute(querystr, estate->readonly_func, 0);
3009 case SPI_OK_INSERT_RETURNING:
3010 case SPI_OK_UPDATE_RETURNING:
3011 case SPI_OK_DELETE_RETURNING:
3012 case SPI_OK_UTILITY:
3013 case SPI_OK_REWRITTEN:
3019 * Also allow a zero return, which implies the querystring
3020 * contained no commands.
3024 case SPI_OK_SELINTO:
3027 * We want to disallow SELECT INTO for now, because its behavior
3028 * is not consistent with SELECT INTO in a normal plpgsql context.
3029 * (We need to reimplement EXECUTE to parse the string as a
3030 * plpgsql command, not just feed it to SPI_execute.) However,
3031 * CREATE AS should be allowed ... and since it produces the same
3032 * parsetree as SELECT INTO, there's no way to tell the difference
3033 * except to look at the source text. Wotta kluge!
3038 for (ptr = querystr; *ptr; ptr++)
3039 if (!scanner_isspace(*ptr))
3041 if (*ptr == 'S' || *ptr == 's')
3043 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3044 errmsg("EXECUTE of SELECT ... INTO is not implemented"),
3045 errhint("You might want to use EXECUTE ... INTO instead.")));
3049 /* Some SPI errors deserve specific error messages */
3050 case SPI_ERROR_COPY:
3052 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3053 errmsg("cannot COPY to/from client in PL/pgSQL")));
3054 case SPI_ERROR_TRANSACTION:
3056 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3057 errmsg("cannot begin/end transactions in PL/pgSQL"),
3058 errhint("Use a BEGIN block with an EXCEPTION clause instead.")));
3061 elog(ERROR, "SPI_execute failed executing query \"%s\": %s",
3062 querystr, SPI_result_code_string(exec_res));
3066 /* Save result info for GET DIAGNOSTICS */
3067 estate->eval_processed = SPI_processed;
3068 estate->eval_lastoid = SPI_lastoid;
3070 /* Process INTO if present */
3073 SPITupleTable *tuptab = SPI_tuptable;
3074 uint32 n = SPI_processed;
3075 PLpgSQL_rec *rec = NULL;
3076 PLpgSQL_row *row = NULL;
3078 /* If the statement did not return a tuple table, complain */
3081 (errcode(ERRCODE_SYNTAX_ERROR),
3082 errmsg("INTO used with a command that cannot return data")));
3084 /* Determine if we assign to a record or a row */
3085 if (stmt->rec != NULL)
3086 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->dno]);
3087 else if (stmt->row != NULL)
3088 row = (PLpgSQL_row *) (estate->datums[stmt->row->dno]);
3090 elog(ERROR, "unsupported target");
3093 * If SELECT ... INTO specified STRICT, and the query didn't find
3094 * exactly one row, throw an error. If STRICT was not specified, then
3095 * allow the query to find any number of rows.
3101 (errcode(ERRCODE_NO_DATA_FOUND),
3102 errmsg("query returned no rows")));
3103 /* set the target to NULL(s) */
3104 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
3108 if (n > 1 && stmt->strict)
3110 (errcode(ERRCODE_TOO_MANY_ROWS),
3111 errmsg("query returned more than one row")));
3112 /* Put the first result row into the target */
3113 exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
3119 * It might be a good idea to raise an error if the query returned
3120 * tuples that are being ignored, but historically we have not done
3125 /* Release any result from SPI_execute, as well as the querystring */
3126 SPI_freetuptable(SPI_tuptable);
3129 return PLPGSQL_RC_OK;
3134 * exec_stmt_dynfors Execute a dynamic query, assign each
3135 * tuple to a record or row and
3136 * execute a group of statements
3141 exec_stmt_dynfors(PLpgSQL_execstate *estate, PLpgSQL_stmt_dynfors *stmt)
3146 portal = exec_dynquery_with_params(estate, stmt->query, stmt->params,
3152 rc = exec_for_query(estate, (PLpgSQL_stmt_forq *) stmt, portal, true);
3155 * Close the implicit cursor
3157 SPI_cursor_close(portal);
3164 * exec_stmt_open Execute an OPEN cursor statement
3168 exec_stmt_open(PLpgSQL_execstate *estate, PLpgSQL_stmt_open *stmt)
3170 PLpgSQL_var *curvar;
3171 char *curname = NULL;
3172 PLpgSQL_expr *query;
3174 ParamListInfo paramLI;
3177 * Get the cursor variable and if it has an assigned name, check
3178 * that it's not in use currently.
3181 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
3182 if (!curvar->isnull)
3184 curname = TextDatumGetCString(curvar->value);
3185 if (SPI_cursor_find(curname) != NULL)
3187 (errcode(ERRCODE_DUPLICATE_CURSOR),
3188 errmsg("cursor \"%s\" already in use", curname)));
3192 * Process the OPEN according to it's type.
3195 if (stmt->query != NULL)
3198 * This is an OPEN refcursor FOR SELECT ...
3200 * We just make sure the query is planned. The real work is
3204 query = stmt->query;
3205 if (query->plan == NULL)
3206 exec_prepare_plan(estate, query, stmt->cursor_options);
3208 else if (stmt->dynquery != NULL)
3211 * This is an OPEN refcursor FOR EXECUTE ...
3214 portal = exec_dynquery_with_params(estate,
3218 stmt->cursor_options);
3221 * If cursor variable was NULL, store the generated portal name in it
3223 if (curname == NULL)
3224 assign_text_var(curvar, portal->name);
3226 return PLPGSQL_RC_OK;
3231 * This is an OPEN cursor
3233 * Note: parser should already have checked that statement supplies
3234 * args iff cursor needs them, but we check again to be safe.
3237 if (stmt->argquery != NULL)
3240 * OPEN CURSOR with args. We fake a SELECT ... INTO ...
3241 * statement to evaluate the args and put 'em into the
3245 PLpgSQL_stmt_execsql set_args;
3247 if (curvar->cursor_explicit_argrow < 0)
3249 (errcode(ERRCODE_SYNTAX_ERROR),
3250 errmsg("arguments given for cursor without arguments")));
3252 memset(&set_args, 0, sizeof(set_args));
3253 set_args.cmd_type = PLPGSQL_STMT_EXECSQL;
3254 set_args.lineno = stmt->lineno;
3255 set_args.sqlstmt = stmt->argquery;
3256 set_args.into = true;
3257 /* XXX historically this has not been STRICT */
3258 set_args.row = (PLpgSQL_row *)
3259 (estate->datums[curvar->cursor_explicit_argrow]);
3261 if (exec_stmt_execsql(estate, &set_args) != PLPGSQL_RC_OK)
3262 elog(ERROR, "open cursor failed during argument processing");
3266 if (curvar->cursor_explicit_argrow >= 0)
3268 (errcode(ERRCODE_SYNTAX_ERROR),
3269 errmsg("arguments required for cursor")));
3272 query = curvar->cursor_explicit_expr;
3273 if (query->plan == NULL)
3274 exec_prepare_plan(estate, query, curvar->cursor_options);
3278 * Set up ParamListInfo (note this is only carrying a hook function, not
3279 * any actual data values, at this point)
3281 paramLI = setup_param_list(estate, query);
3286 portal = SPI_cursor_open_with_paramlist(curname, query->plan,
3288 estate->readonly_func);
3290 elog(ERROR, "could not open cursor: %s",
3291 SPI_result_code_string(SPI_result));
3294 * If cursor variable was NULL, store the generated portal name in it
3296 if (curname == NULL)
3297 assign_text_var(curvar, portal->name);
3304 return PLPGSQL_RC_OK;
3309 * exec_stmt_fetch Fetch from a cursor into a target, or just
3310 * move the current position of the cursor
3314 exec_stmt_fetch(PLpgSQL_execstate *estate, PLpgSQL_stmt_fetch *stmt)
3316 PLpgSQL_var *curvar = NULL;
3317 PLpgSQL_rec *rec = NULL;
3318 PLpgSQL_row *row = NULL;
3319 long how_many = stmt->how_many;
3320 SPITupleTable *tuptab;
3326 * Get the portal of the cursor by name
3329 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
3332 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3333 errmsg("cursor variable \"%s\" is null", curvar->refname)));
3334 curname = TextDatumGetCString(curvar->value);
3336 portal = SPI_cursor_find(curname);
3339 (errcode(ERRCODE_UNDEFINED_CURSOR),
3340 errmsg("cursor \"%s\" does not exist", curname)));
3343 /* Calculate position for FETCH_RELATIVE or FETCH_ABSOLUTE */
3348 /* XXX should be doing this in LONG not INT width */
3349 how_many = exec_eval_integer(estate, stmt->expr, &isnull);
3353 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3354 errmsg("relative or absolute cursor position is null")));
3356 exec_eval_cleanup(estate);
3362 * Determine if we fetch into a record or a row
3365 if (stmt->rec != NULL)
3366 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->dno]);
3367 else if (stmt->row != NULL)
3368 row = (PLpgSQL_row *) (estate->datums[stmt->row->dno]);
3370 elog(ERROR, "unsupported target");
3373 * Fetch 1 tuple from the cursor
3376 SPI_scroll_cursor_fetch(portal, stmt->direction, how_many);
3377 tuptab = SPI_tuptable;
3381 * Set the target appropriately.
3385 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
3387 exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
3389 SPI_freetuptable(tuptab);
3393 /* Move the cursor */
3394 SPI_scroll_cursor_move(portal, stmt->direction, how_many);
3398 /* Set the ROW_COUNT and the global FOUND variable appropriately. */
3399 estate->eval_processed = n;
3400 exec_set_found(estate, n != 0);
3402 return PLPGSQL_RC_OK;
3406 * exec_stmt_close Close a cursor
3410 exec_stmt_close(PLpgSQL_execstate *estate, PLpgSQL_stmt_close *stmt)
3412 PLpgSQL_var *curvar = NULL;
3417 * Get the portal of the cursor by name
3420 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
3423 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3424 errmsg("cursor variable \"%s\" is null", curvar->refname)));
3425 curname = TextDatumGetCString(curvar->value);
3427 portal = SPI_cursor_find(curname);
3430 (errcode(ERRCODE_UNDEFINED_CURSOR),
3431 errmsg("cursor \"%s\" does not exist", curname)));
3438 SPI_cursor_close(portal);
3440 return PLPGSQL_RC_OK;
3445 * exec_assign_expr Put an expression's result into
3450 exec_assign_expr(PLpgSQL_execstate *estate, PLpgSQL_datum *target,
3455 bool isnull = false;
3457 value = exec_eval_expr(estate, expr, &isnull, &valtype);
3458 exec_assign_value(estate, target, value, valtype, &isnull);
3459 exec_eval_cleanup(estate);
3464 * exec_assign_value Put a value into a target field
3466 * Note: in some code paths, this may leak memory in the eval_econtext;
3467 * we assume that will be cleaned up later by exec_eval_cleanup. We cannot
3468 * call exec_eval_cleanup here for fear of destroying the input Datum value.
3472 exec_assign_value(PLpgSQL_execstate *estate,
3473 PLpgSQL_datum *target,
3474 Datum value, Oid valtype, bool *isNull)
3476 switch (target->dtype)
3478 case PLPGSQL_DTYPE_VAR:
3481 * Target is a variable
3483 PLpgSQL_var *var = (PLpgSQL_var *) target;
3486 newvalue = exec_cast_value(value, valtype, var->datatype->typoid,
3487 &(var->datatype->typinput),
3488 var->datatype->typioparam,
3489 var->datatype->atttypmod,
3492 if (*isNull && var->notnull)
3494 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3495 errmsg("null value cannot be assigned to variable \"%s\" declared NOT NULL",
3499 * If type is by-reference, make sure we have a freshly
3500 * palloc'd copy; the originally passed value may not live as
3501 * long as the variable! But we don't need to re-copy if
3502 * exec_cast_value performed a conversion; its output must
3503 * already be palloc'd.
3505 if (!var->datatype->typbyval && !*isNull)
3507 if (newvalue == value)
3508 newvalue = datumCopy(newvalue,
3510 var->datatype->typlen);
3514 * Now free the old value. (We can't do this any earlier
3515 * because of the possibility that we are assigning the var's
3516 * old value to it, eg "foo := foo". We could optimize out
3517 * the assignment altogether in such cases, but it's too
3518 * infrequent to be worth testing for.)
3522 var->value = newvalue;
3523 var->isnull = *isNull;
3524 if (!var->datatype->typbyval && !*isNull)
3525 var->freeval = true;
3529 case PLPGSQL_DTYPE_ROW:
3532 * Target is a row variable
3534 PLpgSQL_row *row = (PLpgSQL_row *) target;
3538 /* If source is null, just assign nulls to the row */
3539 exec_move_row(estate, NULL, row, NULL, NULL);
3547 HeapTupleData tmptup;
3549 /* Source must be of RECORD or composite type */
3550 if (!type_is_rowtype(valtype))
3552 (errcode(ERRCODE_DATATYPE_MISMATCH),
3553 errmsg("cannot assign non-composite value to a row variable")));
3554 /* Source is a tuple Datum, so safe to do this: */
3555 td = DatumGetHeapTupleHeader(value);
3556 /* Extract rowtype info and find a tupdesc */
3557 tupType = HeapTupleHeaderGetTypeId(td);
3558 tupTypmod = HeapTupleHeaderGetTypMod(td);
3559 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
3560 /* Build a temporary HeapTuple control structure */
3561 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
3562 ItemPointerSetInvalid(&(tmptup.t_self));
3563 tmptup.t_tableOid = InvalidOid;
3565 exec_move_row(estate, NULL, row, &tmptup, tupdesc);
3566 ReleaseTupleDesc(tupdesc);
3571 case PLPGSQL_DTYPE_REC:
3574 * Target is a record variable
3576 PLpgSQL_rec *rec = (PLpgSQL_rec *) target;
3580 /* If source is null, just assign nulls to the record */
3581 exec_move_row(estate, rec, NULL, NULL, NULL);
3589 HeapTupleData tmptup;
3591 /* Source must be of RECORD or composite type */
3592 if (!type_is_rowtype(valtype))
3594 (errcode(ERRCODE_DATATYPE_MISMATCH),
3595 errmsg("cannot assign non-composite value to a record variable")));
3597 /* Source is a tuple Datum, so safe to do this: */
3598 td = DatumGetHeapTupleHeader(value);
3599 /* Extract rowtype info and find a tupdesc */
3600 tupType = HeapTupleHeaderGetTypeId(td);
3601 tupTypmod = HeapTupleHeaderGetTypMod(td);
3602 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
3603 /* Build a temporary HeapTuple control structure */
3604 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
3605 ItemPointerSetInvalid(&(tmptup.t_self));
3606 tmptup.t_tableOid = InvalidOid;
3608 exec_move_row(estate, rec, NULL, &tmptup, tupdesc);
3609 ReleaseTupleDesc(tupdesc);
3614 case PLPGSQL_DTYPE_RECFIELD:
3617 * Target is a field of a record
3619 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) target;
3632 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
3635 * Check that there is already a tuple in the record. We need
3636 * that because records don't have any predefined field
3639 if (!HeapTupleIsValid(rec->tup))
3641 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3642 errmsg("record \"%s\" is not assigned yet",
3644 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
3647 * Get the number of the records field to change and the
3648 * number of attributes in the tuple. Note: disallow system
3649 * column names because the code below won't cope.
3651 fno = SPI_fnumber(rec->tupdesc, recfield->fieldname);
3654 (errcode(ERRCODE_UNDEFINED_COLUMN),
3655 errmsg("record \"%s\" has no field \"%s\"",
3656 rec->refname, recfield->fieldname)));
3658 natts = rec->tupdesc->natts;
3661 * Set up values/control arrays for heap_modify_tuple. For all
3662 * the attributes except the one we want to replace, use the
3663 * value that's in the old tuple.
3665 values = palloc(sizeof(Datum) * natts);
3666 nulls = palloc(sizeof(bool) * natts);
3667 replaces = palloc(sizeof(bool) * natts);
3669 memset(replaces, false, sizeof(bool) * natts);
3670 replaces[fno] = true;
3673 * Now insert the new value, being careful to cast it to the
3676 atttype = SPI_gettypeid(rec->tupdesc, fno + 1);
3677 atttypmod = rec->tupdesc->attrs[fno]->atttypmod;
3678 attisnull = *isNull;
3679 values[fno] = exec_simple_cast_value(value,
3684 nulls[fno] = attisnull;
3687 * Avoid leaking the result of exec_simple_cast_value, if it
3688 * performed a conversion to a pass-by-ref type.
3690 if (!attisnull && values[fno] != value && !get_typbyval(atttype))
3691 mustfree = DatumGetPointer(values[fno]);
3696 * Now call heap_modify_tuple() to create a new tuple that
3697 * replaces the old one in the record.
3699 newtup = heap_modify_tuple(rec->tup, rec->tupdesc,
3700 values, nulls, replaces);
3703 heap_freetuple(rec->tup);
3706 rec->freetup = true;
3717 case PLPGSQL_DTYPE_ARRAYELEM:
3720 * Target is an element of an array
3724 PLpgSQL_expr *subscripts[MAXDIM];
3725 int subscriptvals[MAXDIM];
3726 bool oldarrayisnull;
3733 Datum oldarraydatum,
3735 ArrayType *oldarrayval;
3736 ArrayType *newarrayval;
3737 SPITupleTable *save_eval_tuptable;
3740 * We need to do subscript evaluation, which might require
3741 * evaluating general expressions; and the caller might have
3742 * done that too in order to prepare the input Datum. We
3743 * have to save and restore the caller's SPI_execute result,
3746 save_eval_tuptable = estate->eval_tuptable;
3747 estate->eval_tuptable = NULL;
3750 * To handle constructs like x[1][2] := something, we have to
3751 * be prepared to deal with a chain of arrayelem datums. Chase
3752 * back to find the base array datum, and save the subscript
3753 * expressions as we go. (We are scanning right to left here,
3754 * but want to evaluate the subscripts left-to-right to
3755 * minimize surprises.)
3760 PLpgSQL_arrayelem *arrayelem = (PLpgSQL_arrayelem *) target;
3762 if (nsubscripts >= MAXDIM)
3764 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
3765 errmsg("number of array dimensions (%d) exceeds the maximum allowed (%d)",
3766 nsubscripts, MAXDIM)));
3767 subscripts[nsubscripts++] = arrayelem->subscript;
3768 target = estate->datums[arrayelem->arrayparentno];
3769 } while (target->dtype == PLPGSQL_DTYPE_ARRAYELEM);
3771 /* Fetch current value of array datum */
3772 exec_eval_datum(estate, target,
3773 &arraytypeid, &oldarraydatum, &oldarrayisnull);
3775 arrayelemtypeid = get_element_type(arraytypeid);
3776 if (!OidIsValid(arrayelemtypeid))
3778 (errcode(ERRCODE_DATATYPE_MISMATCH),
3779 errmsg("subscripted object is not an array")));
3781 get_typlenbyvalalign(arrayelemtypeid,
3785 arraytyplen = get_typlen(arraytypeid);
3788 * Evaluate the subscripts, switch into left-to-right order.
3789 * Like ExecEvalArrayRef(), complain if any subscript is null.
3791 for (i = 0; i < nsubscripts; i++)
3796 exec_eval_integer(estate,
3797 subscripts[nsubscripts - 1 - i],
3801 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3802 errmsg("array subscript in assignment must not be null")));
3805 * Clean up in case the subscript expression wasn't simple.
3806 * We can't do exec_eval_cleanup, but we can do this much
3807 * (which is safe because the integer subscript value is
3808 * surely pass-by-value), and we must do it in case the
3809 * next subscript expression isn't simple either.
3811 if (estate->eval_tuptable != NULL)
3812 SPI_freetuptable(estate->eval_tuptable);
3813 estate->eval_tuptable = NULL;
3816 /* Now we can restore caller's SPI_execute result if any. */
3817 Assert(estate->eval_tuptable == NULL);
3818 estate->eval_tuptable = save_eval_tuptable;
3820 /* Coerce source value to match array element type. */
3821 coerced_value = exec_simple_cast_value(value,
3828 * If the original array is null, cons up an empty array so
3829 * that the assignment can proceed; we'll end with a
3830 * one-element array containing just the assigned-to
3831 * subscript. This only works for varlena arrays, though; for
3832 * fixed-length array types we skip the assignment. We can't
3833 * support assignment of a null entry into a fixed-length
3834 * array, either, so that's a no-op too. This is all ugly but
3835 * corresponds to the current behavior of ExecEvalArrayRef().
3837 if (arraytyplen > 0 && /* fixed-length array? */
3838 (oldarrayisnull || *isNull))
3842 oldarrayval = construct_empty_array(arrayelemtypeid);
3844 oldarrayval = (ArrayType *) DatumGetPointer(oldarraydatum);
3847 * Build the modified array value.
3849 newarrayval = array_set(oldarrayval,
3860 * Avoid leaking the result of exec_simple_cast_value, if it
3861 * performed a conversion to a pass-by-ref type.
3863 if (!*isNull && coerced_value != value && !elemtypbyval)
3864 pfree(DatumGetPointer(coerced_value));
3867 * Assign the new array to the base variable. It's never NULL
3871 exec_assign_value(estate, target,
3872 PointerGetDatum(newarrayval),
3873 arraytypeid, isNull);
3876 * Avoid leaking the modified array value, too.
3883 elog(ERROR, "unrecognized dtype: %d", target->dtype);
3888 * exec_eval_datum Get current value of a PLpgSQL_datum
3890 * The type oid, value in Datum format, and null flag are returned.
3892 * At present this doesn't handle PLpgSQL_expr or PLpgSQL_arrayelem datums.
3894 * NOTE: caller must not modify the returned value, since it points right
3895 * at the stored value in the case of pass-by-reference datatypes. In some
3896 * cases we have to palloc a return value, and in such cases we put it into
3897 * the estate's short-term memory context.
3900 exec_eval_datum(PLpgSQL_execstate *estate,
3901 PLpgSQL_datum *datum,
3906 MemoryContext oldcontext;
3908 switch (datum->dtype)
3910 case PLPGSQL_DTYPE_VAR:
3912 PLpgSQL_var *var = (PLpgSQL_var *) datum;
3914 *typeid = var->datatype->typoid;
3915 *value = var->value;
3916 *isnull = var->isnull;
3920 case PLPGSQL_DTYPE_ROW:
3922 PLpgSQL_row *row = (PLpgSQL_row *) datum;
3925 if (!row->rowtupdesc) /* should not happen */
3926 elog(ERROR, "row variable has no tupdesc");
3927 /* Make sure we have a valid type/typmod setting */
3928 BlessTupleDesc(row->rowtupdesc);
3929 oldcontext = MemoryContextSwitchTo(estate->eval_econtext->ecxt_per_tuple_memory);
3930 tup = make_tuple_from_row(estate, row, row->rowtupdesc);
3931 if (tup == NULL) /* should not happen */
3932 elog(ERROR, "row not compatible with its own tupdesc");
3933 MemoryContextSwitchTo(oldcontext);
3934 *typeid = row->rowtupdesc->tdtypeid;
3935 *value = HeapTupleGetDatum(tup);
3940 case PLPGSQL_DTYPE_REC:
3942 PLpgSQL_rec *rec = (PLpgSQL_rec *) datum;
3943 HeapTupleData worktup;
3945 if (!HeapTupleIsValid(rec->tup))
3947 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3948 errmsg("record \"%s\" is not assigned yet",
3950 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
3951 Assert(rec->tupdesc != NULL);
3952 /* Make sure we have a valid type/typmod setting */
3953 BlessTupleDesc(rec->tupdesc);
3956 * In a trigger, the NEW and OLD parameters are likely to be
3957 * on-disk tuples that don't have the desired Datum fields.
3958 * Copy the tuple body and insert the right values.
3960 oldcontext = MemoryContextSwitchTo(estate->eval_econtext->ecxt_per_tuple_memory);
3961 heap_copytuple_with_tuple(rec->tup, &worktup);
3962 HeapTupleHeaderSetDatumLength(worktup.t_data, worktup.t_len);
3963 HeapTupleHeaderSetTypeId(worktup.t_data, rec->tupdesc->tdtypeid);
3964 HeapTupleHeaderSetTypMod(worktup.t_data, rec->tupdesc->tdtypmod);
3965 MemoryContextSwitchTo(oldcontext);
3966 *typeid = rec->tupdesc->tdtypeid;
3967 *value = HeapTupleGetDatum(&worktup);
3972 case PLPGSQL_DTYPE_RECFIELD:
3974 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) datum;
3978 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
3979 if (!HeapTupleIsValid(rec->tup))
3981 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3982 errmsg("record \"%s\" is not assigned yet",
3984 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
3985 fno = SPI_fnumber(rec->tupdesc, recfield->fieldname);
3986 if (fno == SPI_ERROR_NOATTRIBUTE)
3988 (errcode(ERRCODE_UNDEFINED_COLUMN),
3989 errmsg("record \"%s\" has no field \"%s\"",
3990 rec->refname, recfield->fieldname)));
3991 *typeid = SPI_gettypeid(rec->tupdesc, fno);
3992 *value = SPI_getbinval(rec->tup, rec->tupdesc, fno, isnull);
3997 elog(ERROR, "unrecognized dtype: %d", datum->dtype);
4002 * exec_get_datum_type Get datatype of a PLpgSQL_datum
4004 * This is the same logic as in exec_eval_datum, except that it can handle
4005 * some cases where exec_eval_datum has to fail; specifically, we may have
4006 * a tupdesc but no row value for a record variable. (This currently can
4007 * happen only for a trigger's NEW/OLD records.)
4010 exec_get_datum_type(PLpgSQL_execstate *estate,
4011 PLpgSQL_datum *datum)
4015 switch (datum->dtype)
4017 case PLPGSQL_DTYPE_VAR:
4019 PLpgSQL_var *var = (PLpgSQL_var *) datum;
4021 typeid = var->datatype->typoid;
4025 case PLPGSQL_DTYPE_ROW:
4027 PLpgSQL_row *row = (PLpgSQL_row *) datum;
4029 if (!row->rowtupdesc) /* should not happen */
4030 elog(ERROR, "row variable has no tupdesc");
4031 /* Make sure we have a valid type/typmod setting */
4032 BlessTupleDesc(row->rowtupdesc);
4033 typeid = row->rowtupdesc->tdtypeid;
4037 case PLPGSQL_DTYPE_REC:
4039 PLpgSQL_rec *rec = (PLpgSQL_rec *) datum;
4041 if (rec->tupdesc == NULL)
4043 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4044 errmsg("record \"%s\" is not assigned yet",
4046 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
4047 /* Make sure we have a valid type/typmod setting */
4048 BlessTupleDesc(rec->tupdesc);
4049 typeid = rec->tupdesc->tdtypeid;
4053 case PLPGSQL_DTYPE_RECFIELD:
4055 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) datum;
4059 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
4060 if (rec->tupdesc == NULL)
4062 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4063 errmsg("record \"%s\" is not assigned yet",
4065 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
4066 fno = SPI_fnumber(rec->tupdesc, recfield->fieldname);
4067 if (fno == SPI_ERROR_NOATTRIBUTE)
4069 (errcode(ERRCODE_UNDEFINED_COLUMN),
4070 errmsg("record \"%s\" has no field \"%s\"",
4071 rec->refname, recfield->fieldname)));
4072 typeid = SPI_gettypeid(rec->tupdesc, fno);
4077 elog(ERROR, "unrecognized dtype: %d", datum->dtype);
4078 typeid = InvalidOid; /* keep compiler quiet */
4086 * exec_get_rec_fieldtype Get datatype of a PLpgSQL record field
4088 * Also returns the field number to *fieldno.
4091 exec_get_rec_fieldtype(PLpgSQL_rec *rec, const char *fieldname,
4097 if (rec->tupdesc == NULL)
4099 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4100 errmsg("record \"%s\" is not assigned yet",
4102 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
4103 fno = SPI_fnumber(rec->tupdesc, fieldname);
4104 if (fno == SPI_ERROR_NOATTRIBUTE)
4106 (errcode(ERRCODE_UNDEFINED_COLUMN),
4107 errmsg("record \"%s\" has no field \"%s\"",
4108 rec->refname, fieldname)));
4109 typeid = SPI_gettypeid(rec->tupdesc, fno);
4116 * exec_eval_integer Evaluate an expression, coerce result to int4
4118 * Note we do not do exec_eval_cleanup here; the caller must do it at
4119 * some later point. (We do this because the caller may be holding the
4120 * results of other, pass-by-reference, expression evaluations, such as
4121 * an array value to be subscripted. Also see notes in exec_eval_simple_expr
4122 * about allocation of the parameter array.)
4126 exec_eval_integer(PLpgSQL_execstate *estate,
4133 exprdatum = exec_eval_expr(estate, expr, isNull, &exprtypeid);
4134 exprdatum = exec_simple_cast_value(exprdatum, exprtypeid,
4137 return DatumGetInt32(exprdatum);
4141 * exec_eval_boolean Evaluate an expression, coerce result to bool
4143 * Note we do not do exec_eval_cleanup here; the caller must do it at
4148 exec_eval_boolean(PLpgSQL_execstate *estate,
4155 exprdatum = exec_eval_expr(estate, expr, isNull, &exprtypeid);
4156 exprdatum = exec_simple_cast_value(exprdatum, exprtypeid,
4159 return DatumGetBool(exprdatum);
4163 * exec_eval_expr Evaluate an expression and return
4166 * NOTE: caller must do exec_eval_cleanup when done with the Datum.
4170 exec_eval_expr(PLpgSQL_execstate *estate,
4179 * If first time through, create a plan for this expression.
4181 if (expr->plan == NULL)
4182 exec_prepare_plan(estate, expr, 0);
4185 * If this is a simple expression, bypass SPI and use the executor
4188 if (exec_eval_simple_expr(estate, expr, &result, isNull, rettype))
4192 * Else do it the hard way via exec_run_select
4194 rc = exec_run_select(estate, expr, 2, NULL);
4195 if (rc != SPI_OK_SELECT)
4197 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
4198 errmsg("query \"%s\" did not return data", expr->query)));
4201 * Check that the expression returns exactly one column...
4203 if (estate->eval_tuptable->tupdesc->natts != 1)
4205 (errcode(ERRCODE_SYNTAX_ERROR),
4206 errmsg_plural("query \"%s\" returned %d column",
4207 "query \"%s\" returned %d columns",
4208 estate->eval_tuptable->tupdesc->natts,
4210 estate->eval_tuptable->tupdesc->natts)));
4213 * ... and get the column's datatype.
4215 *rettype = SPI_gettypeid(estate->eval_tuptable->tupdesc, 1);
4218 * If there are no rows selected, the result is a NULL of that type.
4220 if (estate->eval_processed == 0)
4227 * Check that the expression returned no more than one row.
4229 if (estate->eval_processed != 1)
4231 (errcode(ERRCODE_CARDINALITY_VIOLATION),
4232 errmsg("query \"%s\" returned more than one row",
4236 * Return the single result Datum.
4238 return SPI_getbinval(estate->eval_tuptable->vals[0],
4239 estate->eval_tuptable->tupdesc, 1, isNull);
4244 * exec_run_select Execute a select query
4248 exec_run_select(PLpgSQL_execstate *estate,
4249 PLpgSQL_expr *expr, long maxtuples, Portal *portalP)
4251 ParamListInfo paramLI;
4255 * On the first call for this expression generate the plan
4257 if (expr->plan == NULL)
4258 exec_prepare_plan(estate, expr, 0);
4261 * Set up ParamListInfo (note this is only carrying a hook function, not
4262 * any actual data values, at this point)
4264 paramLI = setup_param_list(estate, expr);
4267 * If a portal was requested, put the query into the portal
4269 if (portalP != NULL)
4271 *portalP = SPI_cursor_open_with_paramlist(NULL, expr->plan,
4273 estate->readonly_func);
4274 if (*portalP == NULL)
4275 elog(ERROR, "could not open implicit cursor for query \"%s\": %s",
4276 expr->query, SPI_result_code_string(SPI_result));
4279 return SPI_OK_CURSOR;
4285 rc = SPI_execute_plan_with_paramlist(expr->plan, paramLI,
4286 estate->readonly_func, maxtuples);
4287 if (rc != SPI_OK_SELECT)
4289 (errcode(ERRCODE_SYNTAX_ERROR),
4290 errmsg("query \"%s\" is not a SELECT", expr->query)));
4292 /* Save query results for eventual cleanup */
4293 Assert(estate->eval_tuptable == NULL);
4294 estate->eval_tuptable = SPI_tuptable;
4295 estate->eval_processed = SPI_processed;
4296 estate->eval_lastoid = SPI_lastoid;
4306 * exec_for_query --- execute body of FOR loop for each row from a portal
4308 * Used by exec_stmt_fors, exec_stmt_forc and exec_stmt_dynfors
4311 exec_for_query(PLpgSQL_execstate *estate, PLpgSQL_stmt_forq *stmt,
4312 Portal portal, bool prefetch_ok)
4314 PLpgSQL_rec *rec = NULL;
4315 PLpgSQL_row *row = NULL;
4316 SPITupleTable *tuptab;
4318 int rc = PLPGSQL_RC_OK;
4322 * Determine if we assign to a record or a row
4324 if (stmt->rec != NULL)
4325 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->dno]);
4326 else if (stmt->row != NULL)
4327 row = (PLpgSQL_row *) (estate->datums[stmt->row->dno]);
4329 elog(ERROR, "unsupported target");
4332 * Make sure the portal doesn't get closed by the user statements we
4338 * Fetch the initial tuple(s). If prefetching is allowed then we grab a
4339 * few more rows to avoid multiple trips through executor startup
4342 SPI_cursor_fetch(portal, true, prefetch_ok ? 10 : 1);
4343 tuptab = SPI_tuptable;
4347 * If the query didn't return any rows, set the target to NULL and fall
4348 * through with found = false.
4351 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
4353 found = true; /* processed at least one tuple */
4362 for (i = 0; i < n; i++)
4365 * Assign the tuple to the target
4367 exec_move_row(estate, rec, row, tuptab->vals[i], tuptab->tupdesc);
4370 * Execute the statements
4372 rc = exec_stmts(estate, stmt->body);
4374 if (rc != PLPGSQL_RC_OK)
4376 if (rc == PLPGSQL_RC_EXIT)
4378 if (estate->exitlabel == NULL)
4380 /* unlabelled exit, so exit the current loop */
4383 else if (stmt->label != NULL &&
4384 strcmp(stmt->label, estate->exitlabel) == 0)
4386 /* label matches this loop, so exit loop */
4387 estate->exitlabel = NULL;
4392 * otherwise, we processed a labelled exit that does not
4393 * match the current statement's label, if any; return
4394 * RC_EXIT so that the EXIT continues to recurse upward.
4397 else if (rc == PLPGSQL_RC_CONTINUE)
4399 if (estate->exitlabel == NULL)
4401 /* unlabelled continue, so re-run the current loop */
4405 else if (stmt->label != NULL &&
4406 strcmp(stmt->label, estate->exitlabel) == 0)
4408 /* label matches this loop, so re-run loop */
4409 estate->exitlabel = NULL;
4415 * otherwise, we process a labelled continue that does not
4416 * match the current statement's label, if any; return
4417 * RC_CONTINUE so that the CONTINUE will propagate up the
4423 * We're aborting the loop. Need a goto to get out of two
4430 SPI_freetuptable(tuptab);
4433 * Fetch more tuples. If prefetching is allowed, grab 50 at a time.
4435 SPI_cursor_fetch(portal, true, prefetch_ok ? 50 : 1);
4436 tuptab = SPI_tuptable;
4443 * Release last group of tuples (if any)
4445 SPI_freetuptable(tuptab);
4447 UnpinPortal(portal);
4450 * Set the FOUND variable to indicate the result of executing the loop
4451 * (namely, whether we looped one or more times). This must be set last so
4452 * that it does not interfere with the value of the FOUND variable inside
4453 * the loop processing itself.
4455 exec_set_found(estate, found);
4462 * exec_eval_simple_expr - Evaluate a simple expression returning
4463 * a Datum by directly calling ExecEvalExpr().
4465 * If successful, store results into *result, *isNull, *rettype and return
4466 * TRUE. If the expression cannot be handled by simple evaluation,
4469 * Because we only store one execution tree for a simple expression, we
4470 * can't handle recursion cases. So, if we see the tree is already busy
4471 * with an evaluation in the current xact, we just return FALSE and let the
4472 * caller run the expression the hard way. (Other alternatives such as
4473 * creating a new tree for a recursive call either introduce memory leaks,
4474 * or add enough bookkeeping to be doubtful wins anyway.) Another case that
4475 * is covered by the expr_simple_in_use test is where a previous execution
4476 * of the tree was aborted by an error: the tree may contain bogus state
4477 * so we dare not re-use it.
4479 * It is possible though unlikely for a simple expression to become non-simple
4480 * (consider for example redefining a trivial view). We must handle that for
4481 * correctness; fortunately it's normally inexpensive to do
4482 * RevalidateCachedPlan on a simple expression. We do not consider the other
4483 * direction (non-simple expression becoming simple) because we'll still give
4484 * correct results if that happens, and it's unlikely to be worth the cycles
4487 * Note: if pass-by-reference, the result is in the eval_econtext's
4488 * temporary memory context. It will be freed when exec_eval_cleanup
4493 exec_eval_simple_expr(PLpgSQL_execstate *estate,
4499 ExprContext *econtext = estate->eval_econtext;
4500 LocalTransactionId curlxid = MyProc->lxid;
4501 CachedPlanSource *plansource;
4503 ParamListInfo paramLI;
4504 PLpgSQL_expr *save_cur_expr;
4505 MemoryContext oldcontext;
4508 * Forget it if expression wasn't simple before.
4510 if (expr->expr_simple_expr == NULL)
4514 * If expression is in use in current xact, don't touch it.
4516 if (expr->expr_simple_in_use && expr->expr_simple_lxid == curlxid)
4520 * Revalidate cached plan, so that we will notice if it became stale. (We
4521 * also need to hold a refcount while using the plan.) Note that even if
4522 * replanning occurs, the length of plancache_list can't change, since it
4523 * is a property of the raw parsetree generated from the query text.
4525 Assert(list_length(expr->plan->plancache_list) == 1);
4526 plansource = (CachedPlanSource *) linitial(expr->plan->plancache_list);
4527 cplan = RevalidateCachedPlan(plansource, true);
4528 if (cplan->generation != expr->expr_simple_generation)
4530 /* It got replanned ... is it still simple? */
4531 exec_simple_check_plan(expr);
4532 if (expr->expr_simple_expr == NULL)
4534 /* Ooops, release refcount and fail */
4535 ReleaseCachedPlan(cplan, true);
4541 * Pass back previously-determined result type.
4543 *rettype = expr->expr_simple_type;
4546 * Prepare the expression for execution, if it's not been done already in
4547 * the current transaction. (This will be forced to happen if we called
4548 * exec_simple_check_plan above.)
4550 if (expr->expr_simple_lxid != curlxid)
4552 expr->expr_simple_state = ExecPrepareExpr(expr->expr_simple_expr,
4553 simple_eval_estate);
4554 expr->expr_simple_in_use = false;
4555 expr->expr_simple_lxid = curlxid;
4559 * We have to do some of the things SPI_execute_plan would do, in
4560 * particular advance the snapshot if we are in a non-read-only function.
4561 * Without this, stable functions within the expression would fail to see
4562 * updates made so far by our own function.
4566 oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
4567 if (!estate->readonly_func)
4569 CommandCounterIncrement();
4570 PushActiveSnapshot(GetTransactionSnapshot());
4574 * Create the param list in econtext's temporary memory context. We won't
4575 * need to free it explicitly, since it will go away at the next reset of
4578 * XXX think about avoiding repeated palloc's for param lists? It should
4579 * be possible --- this routine isn't re-entrant anymore.
4581 * Just for paranoia's sake, save and restore the prior value of
4582 * estate->cur_expr, which setup_param_list() sets.
4584 save_cur_expr = estate->cur_expr;
4586 paramLI = setup_param_list(estate, expr);
4587 econtext->ecxt_param_list_info = paramLI;
4590 * Mark expression as busy for the duration of the ExecEvalExpr call.
4592 expr->expr_simple_in_use = true;
4595 * Finally we can call the executor to evaluate the expression
4597 *result = ExecEvalExpr(expr->expr_simple_state,
4602 /* Assorted cleanup */
4603 expr->expr_simple_in_use = false;
4605 estate->cur_expr = save_cur_expr;
4607 if (!estate->readonly_func)
4608 PopActiveSnapshot();
4610 MemoryContextSwitchTo(oldcontext);
4615 * Now we can release our refcount on the cached plan.
4617 ReleaseCachedPlan(cplan, true);
4627 * Create a ParamListInfo to pass to SPI
4629 * The ParamListInfo array is initially all zeroes, in particular the
4630 * ptype values are all InvalidOid. This causes the executor to call the
4631 * paramFetch hook each time it wants a value. We thus evaluate only the
4632 * parameters actually demanded.
4634 * The result is a locally palloc'd array that should be pfree'd after use;
4635 * but note it can be NULL.
4637 static ParamListInfo
4638 setup_param_list(PLpgSQL_execstate *estate, PLpgSQL_expr *expr)
4640 ParamListInfo paramLI;
4643 * Could we re-use these arrays instead of palloc'ing a new one each time?
4644 * However, we'd have to zero the array each time anyway, since new values
4645 * might have been assigned to the variables.
4647 if (estate->ndatums > 0)
4649 /* sizeof(ParamListInfoData) includes the first array element */
4650 paramLI = (ParamListInfo)
4651 palloc0(sizeof(ParamListInfoData) +
4652 (estate->ndatums - 1) *sizeof(ParamExternData));
4653 paramLI->paramFetch = plpgsql_param_fetch;
4654 paramLI->paramFetchArg = (void *) estate;
4655 paramLI->parserSetup = (ParserSetupHook) plpgsql_parser_setup;
4656 paramLI->parserSetupArg = (void *) expr;
4657 paramLI->numParams = estate->ndatums;
4660 * Set up link to active expr where the hook functions can find it.
4661 * Callers must save and restore cur_expr if there is any chance that
4662 * they are interrupting an active use of parameters.
4664 estate->cur_expr = expr;
4667 * Also make sure this is set before parser hooks need it. There is
4668 * no need to save and restore, since the value is always correct once
4671 expr->func = estate->func;
4679 * plpgsql_param_fetch paramFetch callback for dynamic parameter fetch
4682 plpgsql_param_fetch(ParamListInfo params, int paramid)
4685 PLpgSQL_execstate *estate;
4687 PLpgSQL_datum *datum;
4688 ParamExternData *prm;
4690 /* paramid's are 1-based, but dnos are 0-based */
4692 Assert(dno >= 0 && dno < params->numParams);
4694 /* fetch back the hook data */
4695 estate = (PLpgSQL_execstate *) params->paramFetchArg;
4696 expr = estate->cur_expr;
4697 Assert(params->numParams == estate->ndatums);
4700 * Do nothing if asked for a value that's not supposed to be used by this
4701 * SQL expression. This avoids unwanted evaluations when functions such
4702 * as copyParamList try to materialize all the values.
4704 if (!bms_is_member(dno, expr->paramnos))
4707 /* OK, evaluate the value and store into the appropriate paramlist slot */
4708 datum = estate->datums[dno];
4709 prm = ¶ms->params[dno];
4710 exec_eval_datum(estate, datum,
4711 &prm->ptype, &prm->value, &prm->isnull);
4716 * exec_move_row Move one tuple's values into a record or row
4720 exec_move_row(PLpgSQL_execstate *estate,
4723 HeapTuple tup, TupleDesc tupdesc)
4726 * Record is simple - just copy the tuple and its descriptor into the
4732 * Copy input first, just in case it is pointing at variable's value
4734 if (HeapTupleIsValid(tup))
4735 tup = heap_copytuple(tup);
4738 /* If we have a tupdesc but no data, form an all-nulls tuple */
4741 nulls = (bool *) palloc(tupdesc->natts * sizeof(bool));
4742 memset(nulls, true, tupdesc->natts * sizeof(bool));
4744 tup = heap_form_tuple(tupdesc, NULL, nulls);
4750 tupdesc = CreateTupleDescCopy(tupdesc);
4752 /* Free the old value ... */
4755 heap_freetuple(rec->tup);
4756 rec->freetup = false;
4758 if (rec->freetupdesc)
4760 FreeTupleDesc(rec->tupdesc);
4761 rec->freetupdesc = false;
4764 /* ... and install the new */
4765 if (HeapTupleIsValid(tup))
4768 rec->freetup = true;
4775 rec->tupdesc = tupdesc;
4776 rec->freetupdesc = true;
4779 rec->tupdesc = NULL;
4785 * Row is a bit more complicated in that we assign the individual
4786 * attributes of the tuple to the variables the row points to.
4788 * NOTE: this code used to demand row->nfields ==
4789 * HeapTupleHeaderGetNatts(tup->t_data), but that's wrong. The tuple
4790 * might have more fields than we expected if it's from an
4791 * inheritance-child table of the current table, or it might have fewer if
4792 * the table has had columns added by ALTER TABLE. Ignore extra columns
4793 * and assume NULL for missing columns, the same as heap_getattr would do.
4794 * We also have to skip over dropped columns in either the source or
4797 * If we have no tuple data at all, we'll assign NULL to all columns of
4802 int td_natts = tupdesc ? tupdesc->natts : 0;
4807 if (HeapTupleIsValid(tup))
4808 t_natts = HeapTupleHeaderGetNatts(tup->t_data);
4813 for (fnum = 0; fnum < row->nfields; fnum++)
4820 if (row->varnos[fnum] < 0)
4821 continue; /* skip dropped column in row struct */
4823 var = (PLpgSQL_var *) (estate->datums[row->varnos[fnum]]);
4825 while (anum < td_natts && tupdesc->attrs[anum]->attisdropped)
4826 anum++; /* skip dropped column in tuple */
4828 if (anum < td_natts)
4831 value = SPI_getbinval(tup, tupdesc, anum + 1, &isnull);
4837 valtype = SPI_gettypeid(tupdesc, anum + 1);
4846 * InvalidOid is OK because exec_assign_value doesn't care
4847 * about the type of a source NULL
4849 valtype = InvalidOid;
4852 exec_assign_value(estate, (PLpgSQL_datum *) var,
4853 value, valtype, &isnull);
4859 elog(ERROR, "unsupported target");
4863 * make_tuple_from_row Make a tuple from the values of a row object
4865 * A NULL return indicates rowtype mismatch; caller must raise suitable error
4869 make_tuple_from_row(PLpgSQL_execstate *estate,
4873 int natts = tupdesc->natts;
4879 if (natts != row->nfields)
4882 dvalues = (Datum *) palloc0(natts * sizeof(Datum));
4883 nulls = (bool *) palloc(natts * sizeof(bool));
4885 for (i = 0; i < natts; i++)
4889 if (tupdesc->attrs[i]->attisdropped)
4891 nulls[i] = true; /* leave the column as null */
4894 if (row->varnos[i] < 0) /* should not happen */
4895 elog(ERROR, "dropped rowtype entry for non-dropped column");
4897 exec_eval_datum(estate, estate->datums[row->varnos[i]],
4898 &fieldtypeid, &dvalues[i], &nulls[i]);
4899 if (fieldtypeid != tupdesc->attrs[i]->atttypid)
4903 tuple = heap_form_tuple(tupdesc, dvalues, nulls);
4912 * convert_value_to_string Convert a non-null Datum to C string
4914 * Note: callers generally assume that the result is a palloc'd string and
4915 * should be pfree'd. This is not all that safe an assumption ...
4917 * Note: not caching the conversion function lookup is bad for performance.
4921 convert_value_to_string(Datum value, Oid valtype)
4926 getTypeOutputInfo(valtype, &typoutput, &typIsVarlena);
4927 return OidOutputFunctionCall(typoutput, value);
4931 * exec_cast_value Cast a value if required
4935 exec_cast_value(Datum value, Oid valtype,
4943 * If the type of the queries return value isn't that of the variable,
4946 if (valtype != reqtype || reqtypmod != -1)
4952 extval = convert_value_to_string(value, valtype);
4953 value = InputFunctionCall(reqinput, extval,
4954 reqtypioparam, reqtypmod);
4959 value = InputFunctionCall(reqinput, NULL,
4960 reqtypioparam, reqtypmod);
4968 * exec_simple_cast_value Cast a value if required
4970 * As above, but need not supply details about target type. Note that this
4971 * is slower than exec_cast_value with cached type info, and so should be
4972 * avoided in heavily used code paths.
4976 exec_simple_cast_value(Datum value, Oid valtype,
4977 Oid reqtype, int32 reqtypmod,
4980 if (valtype != reqtype || reqtypmod != -1)
4984 FmgrInfo finfo_input;
4986 getTypeInputInfo(reqtype, &typinput, &typioparam);
4988 fmgr_info(typinput, &finfo_input);
4990 value = exec_cast_value(value,
5004 * exec_simple_check_node - Recursively check if an expression
5005 * is made only of simple things we can
5006 * hand out directly to ExecEvalExpr()
5007 * instead of calling SPI.
5011 exec_simple_check_node(Node *node)
5016 switch (nodeTag(node))
5026 ArrayRef *expr = (ArrayRef *) node;
5028 if (!exec_simple_check_node((Node *) expr->refupperindexpr))
5030 if (!exec_simple_check_node((Node *) expr->reflowerindexpr))
5032 if (!exec_simple_check_node((Node *) expr->refexpr))
5034 if (!exec_simple_check_node((Node *) expr->refassgnexpr))
5042 FuncExpr *expr = (FuncExpr *) node;
5044 if (expr->funcretset)
5046 if (!exec_simple_check_node((Node *) expr->args))
5054 OpExpr *expr = (OpExpr *) node;
5058 if (!exec_simple_check_node((Node *) expr->args))
5064 case T_DistinctExpr:
5066 DistinctExpr *expr = (DistinctExpr *) node;
5070 if (!exec_simple_check_node((Node *) expr->args))
5076 case T_ScalarArrayOpExpr:
5078 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
5080 if (!exec_simple_check_node((Node *) expr->args))
5088 BoolExpr *expr = (BoolExpr *) node;
5090 if (!exec_simple_check_node((Node *) expr->args))
5097 return exec_simple_check_node((Node *) ((FieldSelect *) node)->arg);
5101 FieldStore *expr = (FieldStore *) node;
5103 if (!exec_simple_check_node((Node *) expr->arg))
5105 if (!exec_simple_check_node((Node *) expr->newvals))
5112 return exec_simple_check_node((Node *) ((RelabelType *) node)->arg);
5115 return exec_simple_check_node((Node *) ((CoerceViaIO *) node)->arg);
5117 case T_ArrayCoerceExpr:
5118 return exec_simple_check_node((Node *) ((ArrayCoerceExpr *) node)->arg);
5120 case T_ConvertRowtypeExpr:
5121 return exec_simple_check_node((Node *) ((ConvertRowtypeExpr *) node)->arg);
5125 CaseExpr *expr = (CaseExpr *) node;
5127 if (!exec_simple_check_node((Node *) expr->arg))
5129 if (!exec_simple_check_node((Node *) expr->args))
5131 if (!exec_simple_check_node((Node *) expr->defresult))
5139 CaseWhen *when = (CaseWhen *) node;
5141 if (!exec_simple_check_node((Node *) when->expr))
5143 if (!exec_simple_check_node((Node *) when->result))
5149 case T_CaseTestExpr:
5154 ArrayExpr *expr = (ArrayExpr *) node;
5156 if (!exec_simple_check_node((Node *) expr->elements))
5164 RowExpr *expr = (RowExpr *) node;
5166 if (!exec_simple_check_node((Node *) expr->args))
5172 case T_RowCompareExpr:
5174 RowCompareExpr *expr = (RowCompareExpr *) node;
5176 if (!exec_simple_check_node((Node *) expr->largs))
5178 if (!exec_simple_check_node((Node *) expr->rargs))
5184 case T_CoalesceExpr:
5186 CoalesceExpr *expr = (CoalesceExpr *) node;
5188 if (!exec_simple_check_node((Node *) expr->args))
5196 MinMaxExpr *expr = (MinMaxExpr *) node;
5198 if (!exec_simple_check_node((Node *) expr->args))
5206 XmlExpr *expr = (XmlExpr *) node;
5208 if (!exec_simple_check_node((Node *) expr->named_args))
5210 if (!exec_simple_check_node((Node *) expr->args))
5218 NullIfExpr *expr = (NullIfExpr *) node;
5222 if (!exec_simple_check_node((Node *) expr->args))
5229 return exec_simple_check_node((Node *) ((NullTest *) node)->arg);
5232 return exec_simple_check_node((Node *) ((BooleanTest *) node)->arg);
5234 case T_CoerceToDomain:
5235 return exec_simple_check_node((Node *) ((CoerceToDomain *) node)->arg);
5237 case T_CoerceToDomainValue:
5242 List *expr = (List *) node;
5247 if (!exec_simple_check_node(lfirst(l)))
5261 * exec_simple_check_plan - Check if a plan is simple enough to
5262 * be evaluated by ExecEvalExpr() instead
5267 exec_simple_check_plan(PLpgSQL_expr *expr)
5269 CachedPlanSource *plansource;
5275 * Initialize to "not simple", and remember the plan generation number we
5276 * last checked. (If the query produces more or less than one parsetree
5277 * we just leave expr_simple_generation set to 0.)
5279 expr->expr_simple_expr = NULL;
5280 expr->expr_simple_generation = 0;
5283 * 1. We can only evaluate queries that resulted in one single execution
5286 if (list_length(expr->plan->plancache_list) != 1)
5288 plansource = (CachedPlanSource *) linitial(expr->plan->plancache_list);
5289 expr->expr_simple_generation = plansource->generation;
5290 if (list_length(plansource->plan->stmt_list) != 1)
5293 stmt = (PlannedStmt *) linitial(plansource->plan->stmt_list);
5296 * 2. It must be a RESULT plan --> no scan's required
5298 if (!IsA(stmt, PlannedStmt))
5300 if (stmt->commandType != CMD_SELECT || stmt->intoClause)
5302 plan = stmt->planTree;
5303 if (!IsA(plan, Result))
5307 * 3. Can't have any subplan or qual clause, either
5309 if (plan->lefttree != NULL ||
5310 plan->righttree != NULL ||
5311 plan->initPlan != NULL ||
5312 plan->qual != NULL ||
5313 ((Result *) plan)->resconstantqual != NULL)
5317 * 4. The plan must have a single attribute as result
5319 if (list_length(plan->targetlist) != 1)
5322 tle = (TargetEntry *) linitial(plan->targetlist);
5325 * 5. Check that all the nodes in the expression are non-scary.
5327 if (!exec_simple_check_node((Node *) tle->expr))
5331 * Yes - this is a simple expression. Mark it as such, and initialize
5332 * state to "not valid in current transaction".
5334 expr->expr_simple_expr = tle->expr;
5335 expr->expr_simple_state = NULL;
5336 expr->expr_simple_in_use = false;
5337 expr->expr_simple_lxid = InvalidLocalTransactionId;
5338 /* Also stash away the expression result type */
5339 expr->expr_simple_type = exprType((Node *) tle->expr);
5343 * exec_set_found Set the global found variable
5348 exec_set_found(PLpgSQL_execstate *estate, bool state)
5352 var = (PLpgSQL_var *) (estate->datums[estate->found_varno]);
5353 var->value = PointerGetDatum(state);
5354 var->isnull = false;
5358 * plpgsql_create_econtext --- create an eval_econtext for the current function
5360 * We may need to create a new simple_eval_estate too, if there's not one
5361 * already for the current transaction. The EState will be cleaned up at
5365 plpgsql_create_econtext(PLpgSQL_execstate *estate)
5367 SimpleEcontextStackEntry *entry;
5370 * Create an EState for evaluation of simple expressions, if there's not
5371 * one already in the current transaction. The EState is made a child of
5372 * TopTransactionContext so it will have the right lifespan.
5374 if (simple_eval_estate == NULL)
5376 MemoryContext oldcontext;
5378 oldcontext = MemoryContextSwitchTo(TopTransactionContext);
5379 simple_eval_estate = CreateExecutorState();
5380 MemoryContextSwitchTo(oldcontext);
5384 * Create a child econtext for the current function.
5386 estate->eval_econtext = CreateExprContext(simple_eval_estate);
5389 * Make a stack entry so we can clean up the econtext at subxact end.
5390 * Stack entries are kept in TopTransactionContext for simplicity.
5392 entry = (SimpleEcontextStackEntry *)
5393 MemoryContextAlloc(TopTransactionContext,
5394 sizeof(SimpleEcontextStackEntry));
5396 entry->stack_econtext = estate->eval_econtext;
5397 entry->xact_subxid = GetCurrentSubTransactionId();
5399 entry->next = simple_econtext_stack;
5400 simple_econtext_stack = entry;
5404 * plpgsql_destroy_econtext --- destroy function's econtext
5406 * We check that it matches the top stack entry, and destroy the stack
5407 * entry along with the context.
5410 plpgsql_destroy_econtext(PLpgSQL_execstate *estate)
5412 SimpleEcontextStackEntry *next;
5414 Assert(simple_econtext_stack != NULL);
5415 Assert(simple_econtext_stack->stack_econtext == estate->eval_econtext);
5417 next = simple_econtext_stack->next;
5418 pfree(simple_econtext_stack);
5419 simple_econtext_stack = next;
5421 FreeExprContext(estate->eval_econtext, true);
5422 estate->eval_econtext = NULL;
5426 * plpgsql_xact_cb --- post-transaction-commit-or-abort cleanup
5428 * If a simple-expression EState was created in the current transaction,
5429 * it has to be cleaned up.
5432 plpgsql_xact_cb(XactEvent event, void *arg)
5435 * If we are doing a clean transaction shutdown, free the EState (so that
5436 * any remaining resources will be released correctly). In an abort, we
5437 * expect the regular abort recovery procedures to release everything of
5440 if (event != XACT_EVENT_ABORT)
5442 /* Shouldn't be any econtext stack entries left at commit */
5443 Assert(simple_econtext_stack == NULL);
5445 if (simple_eval_estate)
5446 FreeExecutorState(simple_eval_estate);
5447 simple_eval_estate = NULL;
5451 simple_econtext_stack = NULL;
5452 simple_eval_estate = NULL;
5457 * plpgsql_subxact_cb --- post-subtransaction-commit-or-abort cleanup
5459 * Make sure any simple-expression econtexts created in the current
5460 * subtransaction get cleaned up. We have to do this explicitly because
5461 * no other code knows which child econtexts of simple_eval_estate belong
5462 * to which level of subxact.
5465 plpgsql_subxact_cb(SubXactEvent event, SubTransactionId mySubid,
5466 SubTransactionId parentSubid, void *arg)
5468 if (event == SUBXACT_EVENT_START_SUB)
5471 while (simple_econtext_stack != NULL &&
5472 simple_econtext_stack->xact_subxid == mySubid)
5474 SimpleEcontextStackEntry *next;
5476 FreeExprContext(simple_econtext_stack->stack_econtext,
5477 (event == SUBXACT_EVENT_COMMIT_SUB));
5478 next = simple_econtext_stack->next;
5479 pfree(simple_econtext_stack);
5480 simple_econtext_stack = next;
5485 * free_var --- pfree any pass-by-reference value of the variable.
5487 * This should always be followed by some assignment to var->value,
5488 * as it leaves a dangling pointer.
5491 free_var(PLpgSQL_var *var)
5495 pfree(DatumGetPointer(var->value));
5496 var->freeval = false;
5501 * free old value of a text variable and assign new value from C string
5504 assign_text_var(PLpgSQL_var *var, const char *str)
5507 var->value = CStringGetTextDatum(str);
5508 var->isnull = false;
5509 var->freeval = true;
5513 * exec_eval_using_params --- evaluate params of USING clause
5515 static PreparedParamsData *
5516 exec_eval_using_params(PLpgSQL_execstate *estate, List *params)
5518 PreparedParamsData *ppd;
5523 ppd = (PreparedParamsData *) palloc(sizeof(PreparedParamsData));
5524 nargs = list_length(params);
5527 ppd->types = (Oid *) palloc(nargs * sizeof(Oid));
5528 ppd->values = (Datum *) palloc(nargs * sizeof(Datum));
5529 ppd->nulls = (char *) palloc(nargs * sizeof(char));
5530 ppd->freevals = (bool *) palloc(nargs * sizeof(bool));
5535 PLpgSQL_expr *param = (PLpgSQL_expr *) lfirst(lc);
5538 ppd->values[i] = exec_eval_expr(estate, param,
5541 ppd->nulls[i] = isnull ? 'n' : ' ';
5542 ppd->freevals[i] = false;
5544 if (ppd->types[i] == UNKNOWNOID)
5547 * Treat 'unknown' parameters as text, since that's what most
5548 * people would expect. SPI_execute_with_args can coerce unknown
5549 * constants in a more intelligent way, but not unknown Params.
5550 * This code also takes care of copying into the right context.
5551 * Note we assume 'unknown' has the representation of C-string.
5553 ppd->types[i] = TEXTOID;
5556 ppd->values[i] = CStringGetTextDatum(DatumGetCString(ppd->values[i]));
5557 ppd->freevals[i] = true;
5560 /* pass-by-ref non null values must be copied into plpgsql context */
5566 get_typlenbyval(ppd->types[i], &typLen, &typByVal);
5569 ppd->values[i] = datumCopy(ppd->values[i], typByVal, typLen);
5570 ppd->freevals[i] = true;
5574 exec_eval_cleanup(estate);
5583 * free_params_data --- pfree all pass-by-reference values used in USING clause
5586 free_params_data(PreparedParamsData *ppd)
5590 for (i = 0; i < ppd->nargs; i++)
5592 if (ppd->freevals[i])
5593 pfree(DatumGetPointer(ppd->values[i]));
5599 pfree(ppd->freevals);
5605 * Open portal for dynamic query
5608 exec_dynquery_with_params(PLpgSQL_execstate *estate,
5609 PLpgSQL_expr *dynquery,
5611 const char *portalname,
5621 * Evaluate the string expression after the EXECUTE keyword. Its result is
5622 * the querystring we have to execute.
5624 query = exec_eval_expr(estate, dynquery, &isnull, &restype);
5627 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
5628 errmsg("query string argument of EXECUTE is null")));
5630 /* Get the C-String representation */
5631 querystr = convert_value_to_string(query, restype);
5633 exec_eval_cleanup(estate);
5636 * Open an implicit cursor for the query. We use
5637 * SPI_cursor_open_with_args even when there are no params, because this
5638 * avoids making and freeing one copy of the plan.
5642 PreparedParamsData *ppd;
5644 ppd = exec_eval_using_params(estate, params);
5645 portal = SPI_cursor_open_with_args(portalname,
5647 ppd->nargs, ppd->types,
5648 ppd->values, ppd->nulls,
5649 estate->readonly_func,
5651 free_params_data(ppd);
5655 portal = SPI_cursor_open_with_args(portalname,
5659 estate->readonly_func,
5664 elog(ERROR, "could not open implicit cursor for query \"%s\": %s",
5665 querystr, SPI_result_code_string(SPI_result));