1 /*-------------------------------------------------------------------------
3 * pl_exec.c - Executor for the PL/pgSQL
6 * Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $PostgreSQL: pgsql/src/pl/plpgsql/src/pl_exec.c,v 1.249 2009/11/04 22:26:07 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 "lib/stringinfo.h"
27 #include "miscadmin.h"
28 #include "nodes/nodeFuncs.h"
29 #include "parser/parse_node.h"
30 #include "parser/scansup.h"
31 #include "storage/proc.h"
32 #include "tcop/tcopprot.h"
33 #include "utils/array.h"
34 #include "utils/builtins.h"
35 #include "utils/datum.h"
36 #include "utils/lsyscache.h"
37 #include "utils/memutils.h"
38 #include "utils/snapmgr.h"
39 #include "utils/typcache.h"
42 static const char *const raise_skip_msg = "RAISE";
46 int nargs; /* number of arguments */
47 Oid *types; /* types of arguments */
48 Datum *values; /* evaluated argument values */
49 char *nulls; /* null markers (' '/'n' style) */
50 bool *freevals; /* which arguments are pfree-able */
54 * All plpgsql function executions within a single transaction share the same
55 * executor EState for evaluating "simple" expressions. Each function call
56 * creates its own "eval_econtext" ExprContext within this estate for
57 * per-evaluation workspace. eval_econtext is freed at normal function exit,
58 * and the EState is freed at transaction end (in case of error, we assume
59 * that the abort mechanisms clean it all up). Furthermore, any exception
60 * block within a function has to have its own eval_econtext separate from
61 * the containing function's, so that we can clean up ExprContext callbacks
62 * properly at subtransaction exit. We maintain a stack that tracks the
63 * individual econtexts so that we can clean up correctly at subxact exit.
65 * This arrangement is a bit tedious to maintain, but it's worth the trouble
66 * so that we don't have to re-prepare simple expressions on each trip through
67 * a function. (We assume the case to optimize is many repetitions of a
68 * function within a transaction.)
70 typedef struct SimpleEcontextStackEntry
72 ExprContext *stack_econtext; /* a stacked econtext */
73 SubTransactionId xact_subxid; /* ID for current subxact */
74 struct SimpleEcontextStackEntry *next; /* next stack entry up */
75 } SimpleEcontextStackEntry;
77 static EState *simple_eval_estate = NULL;
78 static SimpleEcontextStackEntry *simple_econtext_stack = NULL;
80 /************************************************************
81 * Local function forward declarations
82 ************************************************************/
83 static void plpgsql_exec_error_callback(void *arg);
84 static PLpgSQL_datum *copy_plpgsql_datum(PLpgSQL_datum *datum);
86 static int exec_stmt_block(PLpgSQL_execstate *estate,
87 PLpgSQL_stmt_block *block);
88 static int exec_stmts(PLpgSQL_execstate *estate,
90 static int exec_stmt(PLpgSQL_execstate *estate,
92 static int exec_stmt_assign(PLpgSQL_execstate *estate,
93 PLpgSQL_stmt_assign *stmt);
94 static int exec_stmt_perform(PLpgSQL_execstate *estate,
95 PLpgSQL_stmt_perform *stmt);
96 static int exec_stmt_getdiag(PLpgSQL_execstate *estate,
97 PLpgSQL_stmt_getdiag *stmt);
98 static int exec_stmt_if(PLpgSQL_execstate *estate,
99 PLpgSQL_stmt_if *stmt);
100 static int exec_stmt_case(PLpgSQL_execstate *estate,
101 PLpgSQL_stmt_case *stmt);
102 static int exec_stmt_loop(PLpgSQL_execstate *estate,
103 PLpgSQL_stmt_loop *stmt);
104 static int exec_stmt_while(PLpgSQL_execstate *estate,
105 PLpgSQL_stmt_while *stmt);
106 static int exec_stmt_fori(PLpgSQL_execstate *estate,
107 PLpgSQL_stmt_fori *stmt);
108 static int exec_stmt_fors(PLpgSQL_execstate *estate,
109 PLpgSQL_stmt_fors *stmt);
110 static int exec_stmt_forc(PLpgSQL_execstate *estate,
111 PLpgSQL_stmt_forc *stmt);
112 static int exec_stmt_open(PLpgSQL_execstate *estate,
113 PLpgSQL_stmt_open *stmt);
114 static int exec_stmt_fetch(PLpgSQL_execstate *estate,
115 PLpgSQL_stmt_fetch *stmt);
116 static int exec_stmt_close(PLpgSQL_execstate *estate,
117 PLpgSQL_stmt_close *stmt);
118 static int exec_stmt_exit(PLpgSQL_execstate *estate,
119 PLpgSQL_stmt_exit *stmt);
120 static int exec_stmt_return(PLpgSQL_execstate *estate,
121 PLpgSQL_stmt_return *stmt);
122 static int exec_stmt_return_next(PLpgSQL_execstate *estate,
123 PLpgSQL_stmt_return_next *stmt);
124 static int exec_stmt_return_query(PLpgSQL_execstate *estate,
125 PLpgSQL_stmt_return_query *stmt);
126 static int exec_stmt_raise(PLpgSQL_execstate *estate,
127 PLpgSQL_stmt_raise *stmt);
128 static int exec_stmt_execsql(PLpgSQL_execstate *estate,
129 PLpgSQL_stmt_execsql *stmt);
130 static int exec_stmt_dynexecute(PLpgSQL_execstate *estate,
131 PLpgSQL_stmt_dynexecute *stmt);
132 static int exec_stmt_dynfors(PLpgSQL_execstate *estate,
133 PLpgSQL_stmt_dynfors *stmt);
135 static void plpgsql_estate_setup(PLpgSQL_execstate *estate,
136 PLpgSQL_function *func,
138 static void exec_eval_cleanup(PLpgSQL_execstate *estate);
140 static void exec_prepare_plan(PLpgSQL_execstate *estate,
141 PLpgSQL_expr *expr, int cursorOptions);
142 static bool exec_simple_check_node(Node *node);
143 static void exec_simple_check_plan(PLpgSQL_expr *expr);
144 static bool exec_eval_simple_expr(PLpgSQL_execstate *estate,
150 static void exec_assign_expr(PLpgSQL_execstate *estate,
151 PLpgSQL_datum *target,
153 static void exec_assign_value(PLpgSQL_execstate *estate,
154 PLpgSQL_datum *target,
155 Datum value, Oid valtype, bool *isNull);
156 static void exec_eval_datum(PLpgSQL_execstate *estate,
157 PLpgSQL_datum *datum,
161 static Oid exec_get_datum_type(PLpgSQL_execstate *estate,
162 PLpgSQL_datum *datum);
163 static int exec_eval_integer(PLpgSQL_execstate *estate,
166 static bool exec_eval_boolean(PLpgSQL_execstate *estate,
169 static Datum exec_eval_expr(PLpgSQL_execstate *estate,
173 static int exec_run_select(PLpgSQL_execstate *estate,
174 PLpgSQL_expr *expr, long maxtuples, Portal *portalP);
175 static int exec_for_query(PLpgSQL_execstate *estate, PLpgSQL_stmt_forq *stmt,
176 Portal portal, bool prefetch_ok);
177 static ParamListInfo setup_param_list(PLpgSQL_execstate *estate,
179 static void plpgsql_parser_setup(ParseState *pstate, PLpgSQL_expr *expr);
180 static Node *plpgsql_param_ref(ParseState *pstate, ParamRef *pref);
181 static void plpgsql_param_fetch(ParamListInfo params, int paramid);
182 static void exec_move_row(PLpgSQL_execstate *estate,
185 HeapTuple tup, TupleDesc tupdesc);
186 static HeapTuple make_tuple_from_row(PLpgSQL_execstate *estate,
189 static char *convert_value_to_string(Datum value, Oid valtype);
190 static Datum exec_cast_value(Datum value, Oid valtype,
196 static Datum exec_simple_cast_value(Datum value, Oid valtype,
197 Oid reqtype, int32 reqtypmod,
199 static void exec_init_tuple_store(PLpgSQL_execstate *estate);
200 static void exec_set_found(PLpgSQL_execstate *estate, bool state);
201 static void plpgsql_create_econtext(PLpgSQL_execstate *estate);
202 static void plpgsql_destroy_econtext(PLpgSQL_execstate *estate);
203 static void free_var(PLpgSQL_var *var);
204 static void assign_text_var(PLpgSQL_var *var, const char *str);
205 static PreparedParamsData *exec_eval_using_params(PLpgSQL_execstate *estate,
207 static void free_params_data(PreparedParamsData *ppd);
208 static Portal exec_dynquery_with_params(PLpgSQL_execstate *estate,
209 PLpgSQL_expr *query, List *params);
213 * plpgsql_exec_function Called by the call handler for
214 * function execution.
218 plpgsql_exec_function(PLpgSQL_function *func, FunctionCallInfo fcinfo)
220 PLpgSQL_execstate estate;
221 ErrorContextCallback plerrcontext;
226 * Setup the execution state
228 plpgsql_estate_setup(&estate, func, (ReturnSetInfo *) fcinfo->resultinfo);
231 * Setup error traceback support for ereport()
233 plerrcontext.callback = plpgsql_exec_error_callback;
234 plerrcontext.arg = &estate;
235 plerrcontext.previous = error_context_stack;
236 error_context_stack = &plerrcontext;
239 * Make local execution copies of all the datums
241 estate.err_text = gettext_noop("during initialization of execution state");
242 for (i = 0; i < estate.ndatums; i++)
243 estate.datums[i] = copy_plpgsql_datum(func->datums[i]);
246 * Store the actual call argument values into the appropriate variables
248 estate.err_text = gettext_noop("while storing call arguments into local variables");
249 for (i = 0; i < func->fn_nargs; i++)
251 int n = func->fn_argvarnos[i];
253 switch (estate.datums[n]->dtype)
255 case PLPGSQL_DTYPE_VAR:
257 PLpgSQL_var *var = (PLpgSQL_var *) estate.datums[n];
259 var->value = fcinfo->arg[i];
260 var->isnull = fcinfo->argnull[i];
261 var->freeval = false;
265 case PLPGSQL_DTYPE_ROW:
267 PLpgSQL_row *row = (PLpgSQL_row *) estate.datums[n];
269 if (!fcinfo->argnull[i])
275 HeapTupleData tmptup;
277 td = DatumGetHeapTupleHeader(fcinfo->arg[i]);
278 /* Extract rowtype info and find a tupdesc */
279 tupType = HeapTupleHeaderGetTypeId(td);
280 tupTypmod = HeapTupleHeaderGetTypMod(td);
281 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
282 /* Build a temporary HeapTuple control structure */
283 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
284 ItemPointerSetInvalid(&(tmptup.t_self));
285 tmptup.t_tableOid = InvalidOid;
287 exec_move_row(&estate, NULL, row, &tmptup, tupdesc);
288 ReleaseTupleDesc(tupdesc);
292 /* If arg is null, treat it as an empty row */
293 exec_move_row(&estate, NULL, row, NULL, NULL);
299 elog(ERROR, "unrecognized dtype: %d", func->datums[i]->dtype);
303 estate.err_text = gettext_noop("during function entry");
306 * Set the magic variable FOUND to false
308 exec_set_found(&estate, false);
311 * Let the instrumentation plugin peek at this function
313 if (*plugin_ptr && (*plugin_ptr)->func_beg)
314 ((*plugin_ptr)->func_beg) (&estate, func);
317 * Now call the toplevel block of statements
319 estate.err_text = NULL;
320 estate.err_stmt = (PLpgSQL_stmt *) (func->action);
321 rc = exec_stmt_block(&estate, func->action);
322 if (rc != PLPGSQL_RC_RETURN)
324 estate.err_stmt = NULL;
325 estate.err_text = NULL;
328 * Provide a more helpful message if a CONTINUE or RAISE has been used
329 * outside the context it can work in.
331 if (rc == PLPGSQL_RC_CONTINUE)
333 (errcode(ERRCODE_SYNTAX_ERROR),
334 errmsg("CONTINUE cannot be used outside a loop")));
335 else if (rc == PLPGSQL_RC_RERAISE)
337 (errcode(ERRCODE_SYNTAX_ERROR),
338 errmsg("RAISE without parameters cannot be used outside an exception handler")));
341 (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
342 errmsg("control reached end of function without RETURN")));
346 * We got a return value - process it
348 estate.err_stmt = NULL;
349 estate.err_text = gettext_noop("while casting return value to function's return type");
351 fcinfo->isnull = estate.retisnull;
355 ReturnSetInfo *rsi = estate.rsi;
357 /* Check caller can handle a set result */
358 if (!rsi || !IsA(rsi, ReturnSetInfo) ||
359 (rsi->allowedModes & SFRM_Materialize) == 0)
361 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
362 errmsg("set-valued function called in context that cannot accept a set")));
363 rsi->returnMode = SFRM_Materialize;
365 /* If we produced any tuples, send back the result */
366 if (estate.tuple_store)
368 rsi->setResult = estate.tuple_store;
369 if (estate.rettupdesc)
371 MemoryContext oldcxt;
373 oldcxt = MemoryContextSwitchTo(estate.tuple_store_cxt);
374 rsi->setDesc = CreateTupleDescCopy(estate.rettupdesc);
375 MemoryContextSwitchTo(oldcxt);
378 estate.retval = (Datum) 0;
379 fcinfo->isnull = true;
381 else if (!estate.retisnull)
383 if (estate.retistuple)
386 * We have to check that the returned tuple actually matches the
387 * expected result type. XXX would be better to cache the tupdesc
388 * instead of repeating get_call_result_type()
390 HeapTuple rettup = (HeapTuple) DatumGetPointer(estate.retval);
392 TupleConversionMap *tupmap;
394 switch (get_call_result_type(fcinfo, NULL, &tupdesc))
396 case TYPEFUNC_COMPOSITE:
397 /* got the expected result rowtype, now check it */
398 tupmap = convert_tuples_by_position(estate.rettupdesc,
400 gettext_noop("returned record type does not match expected record type"));
401 /* it might need conversion */
403 rettup = do_convert_tuple(rettup, tupmap);
404 /* no need to free map, we're about to return anyway */
406 case TYPEFUNC_RECORD:
409 * Failed to determine actual type of RECORD. We could
410 * raise an error here, but what this means in practice is
411 * that the caller is expecting any old generic rowtype,
412 * so we don't really need to be restrictive. Pass back
413 * the generated result type, instead.
415 tupdesc = estate.rettupdesc;
416 if (tupdesc == NULL) /* shouldn't happen */
417 elog(ERROR, "return type must be a row type");
420 /* shouldn't get here if retistuple is true ... */
421 elog(ERROR, "return type must be a row type");
426 * Copy tuple to upper executor memory, as a tuple Datum. Make
427 * sure it is labeled with the caller-supplied tuple type.
429 estate.retval = PointerGetDatum(SPI_returntuple(rettup, tupdesc));
433 /* Cast value to proper type */
434 estate.retval = exec_cast_value(estate.retval, estate.rettype,
436 &(func->fn_retinput),
437 func->fn_rettypioparam,
442 * If the function's return type isn't by value, copy the value
443 * into upper executor memory context.
445 if (!fcinfo->isnull && !func->fn_retbyval)
450 len = datumGetSize(estate.retval, false, func->fn_rettyplen);
451 tmp = SPI_palloc(len);
452 memcpy(tmp, DatumGetPointer(estate.retval), len);
453 estate.retval = PointerGetDatum(tmp);
458 estate.err_text = gettext_noop("during function exit");
461 * Let the instrumentation plugin peek at this function
463 if (*plugin_ptr && (*plugin_ptr)->func_end)
464 ((*plugin_ptr)->func_end) (&estate, func);
466 /* Clean up any leftover temporary memory */
467 plpgsql_destroy_econtext(&estate);
468 exec_eval_cleanup(&estate);
471 * Pop the error context stack
473 error_context_stack = plerrcontext.previous;
476 * Return the function's result
478 return estate.retval;
483 * plpgsql_exec_trigger Called by the call handler for
488 plpgsql_exec_trigger(PLpgSQL_function *func,
489 TriggerData *trigdata)
491 PLpgSQL_execstate estate;
492 ErrorContextCallback plerrcontext;
496 PLpgSQL_rec *rec_new,
501 * Setup the execution state
503 plpgsql_estate_setup(&estate, func, NULL);
506 * Setup error traceback support for ereport()
508 plerrcontext.callback = plpgsql_exec_error_callback;
509 plerrcontext.arg = &estate;
510 plerrcontext.previous = error_context_stack;
511 error_context_stack = &plerrcontext;
514 * Make local execution copies of all the datums
516 estate.err_text = gettext_noop("during initialization of execution state");
517 for (i = 0; i < estate.ndatums; i++)
518 estate.datums[i] = copy_plpgsql_datum(func->datums[i]);
521 * Put the OLD and NEW tuples into record variables
523 * We make the tupdescs available in both records even though only one
524 * may have a value. This allows parsing of record references to succeed
525 * in functions that are used for multiple trigger types. For example,
526 * we might have a test like "if (TG_OP = 'INSERT' and NEW.foo = 'xyz')",
527 * which should parse regardless of the current trigger type.
529 rec_new = (PLpgSQL_rec *) (estate.datums[func->new_varno]);
530 rec_new->freetup = false;
531 rec_new->tupdesc = trigdata->tg_relation->rd_att;
532 rec_new->freetupdesc = false;
533 rec_old = (PLpgSQL_rec *) (estate.datums[func->old_varno]);
534 rec_old->freetup = false;
535 rec_old->tupdesc = trigdata->tg_relation->rd_att;
536 rec_old->freetupdesc = false;
538 if (TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
541 * Per-statement triggers don't use OLD/NEW variables
546 else if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
548 rec_new->tup = trigdata->tg_trigtuple;
551 else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
553 rec_new->tup = trigdata->tg_newtuple;
554 rec_old->tup = trigdata->tg_trigtuple;
556 else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
559 rec_old->tup = trigdata->tg_trigtuple;
562 elog(ERROR, "unrecognized trigger action: not INSERT, DELETE, or UPDATE");
565 * Assign the special tg_ variables
568 var = (PLpgSQL_var *) (estate.datums[func->tg_op_varno]);
569 if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
570 var->value = CStringGetTextDatum("INSERT");
571 else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
572 var->value = CStringGetTextDatum("UPDATE");
573 else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
574 var->value = CStringGetTextDatum("DELETE");
575 else if (TRIGGER_FIRED_BY_TRUNCATE(trigdata->tg_event))
576 var->value = CStringGetTextDatum("TRUNCATE");
578 elog(ERROR, "unrecognized trigger action: not INSERT, DELETE, UPDATE, or TRUNCATE");
582 var = (PLpgSQL_var *) (estate.datums[func->tg_name_varno]);
583 var->value = DirectFunctionCall1(namein,
584 CStringGetDatum(trigdata->tg_trigger->tgname));
588 var = (PLpgSQL_var *) (estate.datums[func->tg_when_varno]);
589 if (TRIGGER_FIRED_BEFORE(trigdata->tg_event))
590 var->value = CStringGetTextDatum("BEFORE");
591 else if (TRIGGER_FIRED_AFTER(trigdata->tg_event))
592 var->value = CStringGetTextDatum("AFTER");
594 elog(ERROR, "unrecognized trigger execution time: not BEFORE or AFTER");
598 var = (PLpgSQL_var *) (estate.datums[func->tg_level_varno]);
599 if (TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
600 var->value = CStringGetTextDatum("ROW");
601 else if (TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
602 var->value = CStringGetTextDatum("STATEMENT");
604 elog(ERROR, "unrecognized trigger event type: not ROW or STATEMENT");
608 var = (PLpgSQL_var *) (estate.datums[func->tg_relid_varno]);
609 var->value = ObjectIdGetDatum(trigdata->tg_relation->rd_id);
611 var->freeval = false;
613 var = (PLpgSQL_var *) (estate.datums[func->tg_relname_varno]);
614 var->value = DirectFunctionCall1(namein,
615 CStringGetDatum(RelationGetRelationName(trigdata->tg_relation)));
619 var = (PLpgSQL_var *) (estate.datums[func->tg_table_name_varno]);
620 var->value = DirectFunctionCall1(namein,
621 CStringGetDatum(RelationGetRelationName(trigdata->tg_relation)));
625 var = (PLpgSQL_var *) (estate.datums[func->tg_table_schema_varno]);
626 var->value = DirectFunctionCall1(namein,
629 RelationGetNamespace(
630 trigdata->tg_relation))));
634 var = (PLpgSQL_var *) (estate.datums[func->tg_nargs_varno]);
635 var->value = Int16GetDatum(trigdata->tg_trigger->tgnargs);
637 var->freeval = false;
639 var = (PLpgSQL_var *) (estate.datums[func->tg_argv_varno]);
640 if (trigdata->tg_trigger->tgnargs > 0)
643 * For historical reasons, tg_argv[] subscripts start at zero not one.
644 * So we can't use construct_array().
646 int nelems = trigdata->tg_trigger->tgnargs;
651 elems = palloc(sizeof(Datum) * nelems);
652 for (i = 0; i < nelems; i++)
653 elems[i] = CStringGetTextDatum(trigdata->tg_trigger->tgargs[i]);
657 var->value = PointerGetDatum(construct_md_array(elems, NULL,
666 var->value = (Datum) 0;
668 var->freeval = false;
671 estate.err_text = gettext_noop("during function entry");
674 * Set the magic variable FOUND to false
676 exec_set_found(&estate, false);
679 * Let the instrumentation plugin peek at this function
681 if (*plugin_ptr && (*plugin_ptr)->func_beg)
682 ((*plugin_ptr)->func_beg) (&estate, func);
685 * Now call the toplevel block of statements
687 estate.err_text = NULL;
688 estate.err_stmt = (PLpgSQL_stmt *) (func->action);
689 rc = exec_stmt_block(&estate, func->action);
690 if (rc != PLPGSQL_RC_RETURN)
692 estate.err_stmt = NULL;
693 estate.err_text = NULL;
696 * Provide a more helpful message if a CONTINUE or RAISE has been used
697 * outside the context it can work in.
699 if (rc == PLPGSQL_RC_CONTINUE)
701 (errcode(ERRCODE_SYNTAX_ERROR),
702 errmsg("CONTINUE cannot be used outside a loop")));
703 else if (rc == PLPGSQL_RC_RERAISE)
705 (errcode(ERRCODE_SYNTAX_ERROR),
706 errmsg("RAISE without parameters cannot be used outside an exception handler")));
709 (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
710 errmsg("control reached end of trigger procedure without RETURN")));
713 estate.err_stmt = NULL;
714 estate.err_text = gettext_noop("during function exit");
718 (errcode(ERRCODE_DATATYPE_MISMATCH),
719 errmsg("trigger procedure cannot return a set")));
722 * Check that the returned tuple structure has the same attributes, the
723 * relation that fired the trigger has. A per-statement trigger always
724 * needs to return NULL, so we ignore any return value the function itself
725 * produces (XXX: is this a good idea?)
727 * XXX This way it is possible, that the trigger returns a tuple where
728 * attributes don't have the correct atttypmod's length. It's up to the
729 * trigger's programmer to ensure that this doesn't happen. Jan
731 if (estate.retisnull || TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
735 TupleConversionMap *tupmap;
737 rettup = (HeapTuple) DatumGetPointer(estate.retval);
738 /* check rowtype compatibility */
739 tupmap = convert_tuples_by_position(estate.rettupdesc,
740 trigdata->tg_relation->rd_att,
741 gettext_noop("returned row structure does not match the structure of the triggering table"));
742 /* it might need conversion */
744 rettup = do_convert_tuple(rettup, tupmap);
745 /* no need to free map, we're about to return anyway */
747 /* Copy tuple to upper executor memory */
748 rettup = SPI_copytuple(rettup);
752 * Let the instrumentation plugin peek at this function
754 if (*plugin_ptr && (*plugin_ptr)->func_end)
755 ((*plugin_ptr)->func_end) (&estate, func);
757 /* Clean up any leftover temporary memory */
758 plpgsql_destroy_econtext(&estate);
759 exec_eval_cleanup(&estate);
762 * Pop the error context stack
764 error_context_stack = plerrcontext.previous;
767 * Return the trigger's result
774 * error context callback to let us supply a call-stack traceback
777 plpgsql_exec_error_callback(void *arg)
779 PLpgSQL_execstate *estate = (PLpgSQL_execstate *) arg;
781 /* if we are doing RAISE, don't report its location */
782 if (estate->err_text == raise_skip_msg)
785 if (estate->err_text != NULL)
788 * We don't expend the cycles to run gettext() on err_text unless we
789 * actually need it. Therefore, places that set up err_text should
790 * use gettext_noop() to ensure the strings get recorded in the
791 * message dictionary.
793 * If both err_text and err_stmt are set, use the err_text as
794 * description, but report the err_stmt's line number. When err_stmt
795 * is not set, we're in function entry/exit, or some such place not
796 * attached to a specific line number.
798 if (estate->err_stmt != NULL)
801 * translator: last %s is a phrase such as "during statement block
802 * local variable initialization"
804 errcontext("PL/pgSQL function \"%s\" line %d %s",
805 estate->func->fn_name,
806 estate->err_stmt->lineno,
807 _(estate->err_text));
812 * translator: last %s is a phrase such as "while storing call
813 * arguments into local variables"
815 errcontext("PL/pgSQL function \"%s\" %s",
816 estate->func->fn_name,
817 _(estate->err_text));
820 else if (estate->err_stmt != NULL)
822 /* translator: last %s is a plpgsql statement type name */
823 errcontext("PL/pgSQL function \"%s\" line %d at %s",
824 estate->func->fn_name,
825 estate->err_stmt->lineno,
826 plpgsql_stmt_typename(estate->err_stmt));
829 errcontext("PL/pgSQL function \"%s\"",
830 estate->func->fn_name);
835 * Support function for initializing local execution variables
838 static PLpgSQL_datum *
839 copy_plpgsql_datum(PLpgSQL_datum *datum)
841 PLpgSQL_datum *result;
843 switch (datum->dtype)
845 case PLPGSQL_DTYPE_VAR:
847 PLpgSQL_var *new = palloc(sizeof(PLpgSQL_var));
849 memcpy(new, datum, sizeof(PLpgSQL_var));
850 /* Ensure the value is null (possibly not needed?) */
853 new->freeval = false;
855 result = (PLpgSQL_datum *) new;
859 case PLPGSQL_DTYPE_REC:
861 PLpgSQL_rec *new = palloc(sizeof(PLpgSQL_rec));
863 memcpy(new, datum, sizeof(PLpgSQL_rec));
864 /* Ensure the value is null (possibly not needed?) */
867 new->freetup = false;
868 new->freetupdesc = false;
870 result = (PLpgSQL_datum *) new;
874 case PLPGSQL_DTYPE_ROW:
875 case PLPGSQL_DTYPE_RECFIELD:
876 case PLPGSQL_DTYPE_ARRAYELEM:
879 * These datum records are read-only at runtime, so no need to
886 elog(ERROR, "unrecognized dtype: %d", datum->dtype);
887 result = NULL; /* keep compiler quiet */
896 exception_matches_conditions(ErrorData *edata, PLpgSQL_condition *cond)
898 for (; cond != NULL; cond = cond->next)
900 int sqlerrstate = cond->sqlerrstate;
903 * OTHERS matches everything *except* query-canceled; if you're
904 * foolish enough, you can match that explicitly.
906 if (sqlerrstate == 0)
908 if (edata->sqlerrcode != ERRCODE_QUERY_CANCELED)
912 else if (edata->sqlerrcode == sqlerrstate)
914 /* Category match? */
915 else if (ERRCODE_IS_CATEGORY(sqlerrstate) &&
916 ERRCODE_TO_CATEGORY(edata->sqlerrcode) == sqlerrstate)
924 * exec_stmt_block Execute a block of statements
928 exec_stmt_block(PLpgSQL_execstate *estate, PLpgSQL_stmt_block *block)
930 volatile int rc = -1;
935 * First initialize all variables declared in this block
937 estate->err_text = gettext_noop("during statement block local variable initialization");
939 for (i = 0; i < block->n_initvars; i++)
941 n = block->initvarnos[i];
943 switch (estate->datums[n]->dtype)
945 case PLPGSQL_DTYPE_VAR:
947 PLpgSQL_var *var = (PLpgSQL_var *) (estate->datums[n]);
949 /* free any old value, in case re-entering block */
952 /* Initially it contains a NULL */
953 var->value = (Datum) 0;
956 if (var->default_val == NULL)
959 * If needed, give the datatype a chance to reject
960 * NULLs, by assigning a NULL to the variable. We
961 * claim the value is of type UNKNOWN, not the var's
962 * datatype, else coercion will be skipped. (Do this
963 * before the notnull check to be consistent with
964 * exec_assign_value.)
966 if (!var->datatype->typinput.fn_strict)
968 bool valIsNull = true;
970 exec_assign_value(estate,
971 (PLpgSQL_datum *) var,
978 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
979 errmsg("variable \"%s\" declared NOT NULL cannot default to NULL",
984 exec_assign_expr(estate, (PLpgSQL_datum *) var,
990 case PLPGSQL_DTYPE_REC:
992 PLpgSQL_rec *rec = (PLpgSQL_rec *) (estate->datums[n]);
996 heap_freetuple(rec->tup);
997 rec->freetup = false;
999 if (rec->freetupdesc)
1001 FreeTupleDesc(rec->tupdesc);
1002 rec->freetupdesc = false;
1005 rec->tupdesc = NULL;
1009 case PLPGSQL_DTYPE_RECFIELD:
1010 case PLPGSQL_DTYPE_ARRAYELEM:
1014 elog(ERROR, "unrecognized dtype: %d",
1015 estate->datums[n]->dtype);
1019 if (block->exceptions)
1022 * Execute the statements in the block's body inside a sub-transaction
1024 MemoryContext oldcontext = CurrentMemoryContext;
1025 ResourceOwner oldowner = CurrentResourceOwner;
1026 ExprContext *old_eval_econtext = estate->eval_econtext;
1028 estate->err_text = gettext_noop("during statement block entry");
1030 BeginInternalSubTransaction(NULL);
1031 /* Want to run statements inside function's memory context */
1032 MemoryContextSwitchTo(oldcontext);
1037 * We need to run the block's statements with a new eval_econtext
1038 * that belongs to the current subtransaction; if we try to use
1039 * the outer econtext then ExprContext shutdown callbacks will be
1040 * called at the wrong times.
1042 plpgsql_create_econtext(estate);
1044 estate->err_text = NULL;
1046 /* Run the block's statements */
1047 rc = exec_stmts(estate, block->body);
1049 estate->err_text = gettext_noop("during statement block exit");
1052 * If the block ended with RETURN, we may need to copy the return
1053 * value out of the subtransaction eval_context. This is
1054 * currently only needed for scalar result types --- rowtype
1055 * values will always exist in the function's own memory context.
1057 if (rc == PLPGSQL_RC_RETURN &&
1058 !estate->retisset &&
1059 !estate->retisnull &&
1060 estate->rettupdesc == NULL)
1065 get_typlenbyval(estate->rettype, &resTypLen, &resTypByVal);
1066 estate->retval = datumCopy(estate->retval,
1067 resTypByVal, resTypLen);
1070 /* Commit the inner transaction, return to outer xact context */
1071 ReleaseCurrentSubTransaction();
1072 MemoryContextSwitchTo(oldcontext);
1073 CurrentResourceOwner = oldowner;
1076 * Revert to outer eval_econtext. (The inner one was
1077 * automatically cleaned up during subxact exit.)
1079 estate->eval_econtext = old_eval_econtext;
1082 * AtEOSubXact_SPI() should not have popped any SPI context, but
1083 * just in case it did, make sure we remain connected.
1085 SPI_restore_connection();
1092 estate->err_text = gettext_noop("during exception cleanup");
1094 /* Save error info */
1095 MemoryContextSwitchTo(oldcontext);
1096 edata = CopyErrorData();
1099 /* Abort the inner transaction */
1100 RollbackAndReleaseCurrentSubTransaction();
1101 MemoryContextSwitchTo(oldcontext);
1102 CurrentResourceOwner = oldowner;
1104 /* Revert to outer eval_econtext */
1105 estate->eval_econtext = old_eval_econtext;
1108 * If AtEOSubXact_SPI() popped any SPI context of the subxact, it
1109 * will have left us in a disconnected state. We need this hack
1110 * to return to connected state.
1112 SPI_restore_connection();
1114 /* Look for a matching exception handler */
1115 foreach(e, block->exceptions->exc_list)
1117 PLpgSQL_exception *exception = (PLpgSQL_exception *) lfirst(e);
1119 if (exception_matches_conditions(edata, exception->conditions))
1122 * Initialize the magic SQLSTATE and SQLERRM variables for
1123 * the exception block. We needn't do this until we have
1124 * found a matching exception.
1126 PLpgSQL_var *state_var;
1127 PLpgSQL_var *errm_var;
1129 state_var = (PLpgSQL_var *)
1130 estate->datums[block->exceptions->sqlstate_varno];
1131 errm_var = (PLpgSQL_var *)
1132 estate->datums[block->exceptions->sqlerrm_varno];
1134 assign_text_var(state_var,
1135 unpack_sql_state(edata->sqlerrcode));
1136 assign_text_var(errm_var, edata->message);
1138 estate->err_text = NULL;
1140 rc = exec_stmts(estate, exception->action);
1142 free_var(state_var);
1143 state_var->value = (Datum) 0;
1144 state_var->isnull = true;
1146 errm_var->value = (Datum) 0;
1147 errm_var->isnull = true;
1149 /* re-throw error if requested by handler */
1150 if (rc == PLPGSQL_RC_RERAISE)
1151 ReThrowError(edata);
1157 /* If no match found, re-throw the error */
1159 ReThrowError(edata);
1161 FreeErrorData(edata);
1168 * Just execute the statements in the block's body
1170 estate->err_text = NULL;
1172 rc = exec_stmts(estate, block->body);
1175 estate->err_text = NULL;
1178 * Handle the return code.
1183 case PLPGSQL_RC_RETURN:
1184 case PLPGSQL_RC_CONTINUE:
1185 case PLPGSQL_RC_RERAISE:
1188 case PLPGSQL_RC_EXIT:
1191 * This is intentionally different from the handling of RC_EXIT
1192 * for loops: to match a block, we require a match by label.
1194 if (estate->exitlabel == NULL)
1195 return PLPGSQL_RC_EXIT;
1196 if (block->label == NULL)
1197 return PLPGSQL_RC_EXIT;
1198 if (strcmp(block->label, estate->exitlabel) != 0)
1199 return PLPGSQL_RC_EXIT;
1200 estate->exitlabel = NULL;
1201 return PLPGSQL_RC_OK;
1204 elog(ERROR, "unrecognized rc: %d", rc);
1207 return PLPGSQL_RC_OK;
1212 * exec_stmts Iterate over a list of statements
1213 * as long as their return code is OK
1217 exec_stmts(PLpgSQL_execstate *estate, List *stmts)
1224 * Ensure we do a CHECK_FOR_INTERRUPTS() even though there is no
1225 * statement. This prevents hangup in a tight loop if, for instance,
1226 * there is a LOOP construct with an empty body.
1228 CHECK_FOR_INTERRUPTS();
1229 return PLPGSQL_RC_OK;
1234 PLpgSQL_stmt *stmt = (PLpgSQL_stmt *) lfirst(s);
1235 int rc = exec_stmt(estate, stmt);
1237 if (rc != PLPGSQL_RC_OK)
1241 return PLPGSQL_RC_OK;
1246 * exec_stmt Distribute one statement to the statements
1247 * type specific execution function.
1251 exec_stmt(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
1253 PLpgSQL_stmt *save_estmt;
1256 save_estmt = estate->err_stmt;
1257 estate->err_stmt = stmt;
1259 /* Let the plugin know that we are about to execute this statement */
1260 if (*plugin_ptr && (*plugin_ptr)->stmt_beg)
1261 ((*plugin_ptr)->stmt_beg) (estate, stmt);
1263 CHECK_FOR_INTERRUPTS();
1265 switch ((enum PLpgSQL_stmt_types) stmt->cmd_type)
1267 case PLPGSQL_STMT_BLOCK:
1268 rc = exec_stmt_block(estate, (PLpgSQL_stmt_block *) stmt);
1271 case PLPGSQL_STMT_ASSIGN:
1272 rc = exec_stmt_assign(estate, (PLpgSQL_stmt_assign *) stmt);
1275 case PLPGSQL_STMT_PERFORM:
1276 rc = exec_stmt_perform(estate, (PLpgSQL_stmt_perform *) stmt);
1279 case PLPGSQL_STMT_GETDIAG:
1280 rc = exec_stmt_getdiag(estate, (PLpgSQL_stmt_getdiag *) stmt);
1283 case PLPGSQL_STMT_IF:
1284 rc = exec_stmt_if(estate, (PLpgSQL_stmt_if *) stmt);
1287 case PLPGSQL_STMT_CASE:
1288 rc = exec_stmt_case(estate, (PLpgSQL_stmt_case *) stmt);
1291 case PLPGSQL_STMT_LOOP:
1292 rc = exec_stmt_loop(estate, (PLpgSQL_stmt_loop *) stmt);
1295 case PLPGSQL_STMT_WHILE:
1296 rc = exec_stmt_while(estate, (PLpgSQL_stmt_while *) stmt);
1299 case PLPGSQL_STMT_FORI:
1300 rc = exec_stmt_fori(estate, (PLpgSQL_stmt_fori *) stmt);
1303 case PLPGSQL_STMT_FORS:
1304 rc = exec_stmt_fors(estate, (PLpgSQL_stmt_fors *) stmt);
1307 case PLPGSQL_STMT_FORC:
1308 rc = exec_stmt_forc(estate, (PLpgSQL_stmt_forc *) stmt);
1311 case PLPGSQL_STMT_EXIT:
1312 rc = exec_stmt_exit(estate, (PLpgSQL_stmt_exit *) stmt);
1315 case PLPGSQL_STMT_RETURN:
1316 rc = exec_stmt_return(estate, (PLpgSQL_stmt_return *) stmt);
1319 case PLPGSQL_STMT_RETURN_NEXT:
1320 rc = exec_stmt_return_next(estate, (PLpgSQL_stmt_return_next *) stmt);
1323 case PLPGSQL_STMT_RETURN_QUERY:
1324 rc = exec_stmt_return_query(estate, (PLpgSQL_stmt_return_query *) stmt);
1327 case PLPGSQL_STMT_RAISE:
1328 rc = exec_stmt_raise(estate, (PLpgSQL_stmt_raise *) stmt);
1331 case PLPGSQL_STMT_EXECSQL:
1332 rc = exec_stmt_execsql(estate, (PLpgSQL_stmt_execsql *) stmt);
1335 case PLPGSQL_STMT_DYNEXECUTE:
1336 rc = exec_stmt_dynexecute(estate, (PLpgSQL_stmt_dynexecute *) stmt);
1339 case PLPGSQL_STMT_DYNFORS:
1340 rc = exec_stmt_dynfors(estate, (PLpgSQL_stmt_dynfors *) stmt);
1343 case PLPGSQL_STMT_OPEN:
1344 rc = exec_stmt_open(estate, (PLpgSQL_stmt_open *) stmt);
1347 case PLPGSQL_STMT_FETCH:
1348 rc = exec_stmt_fetch(estate, (PLpgSQL_stmt_fetch *) stmt);
1351 case PLPGSQL_STMT_CLOSE:
1352 rc = exec_stmt_close(estate, (PLpgSQL_stmt_close *) stmt);
1356 estate->err_stmt = save_estmt;
1357 elog(ERROR, "unrecognized cmdtype: %d", stmt->cmd_type);
1360 /* Let the plugin know that we have finished executing this statement */
1361 if (*plugin_ptr && (*plugin_ptr)->stmt_end)
1362 ((*plugin_ptr)->stmt_end) (estate, stmt);
1364 estate->err_stmt = save_estmt;
1371 * exec_stmt_assign Evaluate an expression and
1372 * put the result into a variable.
1376 exec_stmt_assign(PLpgSQL_execstate *estate, PLpgSQL_stmt_assign *stmt)
1378 Assert(stmt->varno >= 0);
1380 exec_assign_expr(estate, estate->datums[stmt->varno], stmt->expr);
1382 return PLPGSQL_RC_OK;
1386 * exec_stmt_perform Evaluate query and discard result (but set
1387 * FOUND depending on whether at least one row
1392 exec_stmt_perform(PLpgSQL_execstate *estate, PLpgSQL_stmt_perform *stmt)
1394 PLpgSQL_expr *expr = stmt->expr;
1396 (void) exec_run_select(estate, expr, 0, NULL);
1397 exec_set_found(estate, (estate->eval_processed != 0));
1398 exec_eval_cleanup(estate);
1400 return PLPGSQL_RC_OK;
1404 * exec_stmt_getdiag Put internal PG information into
1405 * specified variables.
1409 exec_stmt_getdiag(PLpgSQL_execstate *estate, PLpgSQL_stmt_getdiag *stmt)
1413 foreach(lc, stmt->diag_items)
1415 PLpgSQL_diag_item *diag_item = (PLpgSQL_diag_item *) lfirst(lc);
1417 bool isnull = false;
1419 if (diag_item->target <= 0)
1422 var = estate->datums[diag_item->target];
1427 switch (diag_item->kind)
1429 case PLPGSQL_GETDIAG_ROW_COUNT:
1431 exec_assign_value(estate, var,
1432 UInt32GetDatum(estate->eval_processed),
1436 case PLPGSQL_GETDIAG_RESULT_OID:
1438 exec_assign_value(estate, var,
1439 ObjectIdGetDatum(estate->eval_lastoid),
1444 elog(ERROR, "unrecognized attribute request: %d",
1449 return PLPGSQL_RC_OK;
1453 * exec_stmt_if Evaluate a bool expression and
1454 * execute the true or false body
1459 exec_stmt_if(PLpgSQL_execstate *estate, PLpgSQL_stmt_if *stmt)
1464 value = exec_eval_boolean(estate, stmt->cond, &isnull);
1465 exec_eval_cleanup(estate);
1467 if (!isnull && value)
1469 if (stmt->true_body != NIL)
1470 return exec_stmts(estate, stmt->true_body);
1474 if (stmt->false_body != NIL)
1475 return exec_stmts(estate, stmt->false_body);
1478 return PLPGSQL_RC_OK;
1487 exec_stmt_case(PLpgSQL_execstate *estate, PLpgSQL_stmt_case *stmt)
1489 PLpgSQL_var *t_var = NULL;
1493 if (stmt->t_expr != NULL)
1499 t_val = exec_eval_expr(estate, stmt->t_expr, &isnull, &t_oid);
1501 t_var = (PLpgSQL_var *) estate->datums[stmt->t_varno];
1504 * When expected datatype is different from real, change it. Note that
1505 * what we're modifying here is an execution copy of the datum, so
1506 * this doesn't affect the originally stored function parse tree.
1508 if (t_var->datatype->typoid != t_oid)
1509 t_var->datatype = plpgsql_build_datatype(t_oid, -1);
1511 /* now we can assign to the variable */
1512 exec_assign_value(estate,
1513 (PLpgSQL_datum *) t_var,
1518 exec_eval_cleanup(estate);
1521 /* Now search for a successful WHEN clause */
1522 foreach(l, stmt->case_when_list)
1524 PLpgSQL_case_when *cwt = (PLpgSQL_case_when *) lfirst(l);
1527 value = exec_eval_boolean(estate, cwt->expr, &isnull);
1528 exec_eval_cleanup(estate);
1529 if (!isnull && value)
1533 /* We can now discard any value we had for the temp variable */
1537 t_var->value = (Datum) 0;
1538 t_var->isnull = true;
1541 /* Evaluate the statement(s), and we're done */
1542 return exec_stmts(estate, cwt->stmts);
1546 /* We can now discard any value we had for the temp variable */
1550 t_var->value = (Datum) 0;
1551 t_var->isnull = true;
1554 /* SQL2003 mandates this error if there was no ELSE clause */
1555 if (!stmt->have_else)
1557 (errcode(ERRCODE_CASE_NOT_FOUND),
1558 errmsg("case not found"),
1559 errhint("CASE statement is missing ELSE part.")));
1561 /* Evaluate the ELSE statements, and we're done */
1562 return exec_stmts(estate, stmt->else_stmts);
1567 * exec_stmt_loop Loop over statements until
1572 exec_stmt_loop(PLpgSQL_execstate *estate, PLpgSQL_stmt_loop *stmt)
1576 int rc = exec_stmts(estate, stmt->body);
1583 case PLPGSQL_RC_EXIT:
1584 if (estate->exitlabel == NULL)
1585 return PLPGSQL_RC_OK;
1586 if (stmt->label == NULL)
1587 return PLPGSQL_RC_EXIT;
1588 if (strcmp(stmt->label, estate->exitlabel) != 0)
1589 return PLPGSQL_RC_EXIT;
1590 estate->exitlabel = NULL;
1591 return PLPGSQL_RC_OK;
1593 case PLPGSQL_RC_CONTINUE:
1594 if (estate->exitlabel == NULL)
1595 /* anonymous continue, so re-run the loop */
1597 else if (stmt->label != NULL &&
1598 strcmp(stmt->label, estate->exitlabel) == 0)
1599 /* label matches named continue, so re-run loop */
1600 estate->exitlabel = NULL;
1602 /* label doesn't match named continue, so propagate upward */
1603 return PLPGSQL_RC_CONTINUE;
1606 case PLPGSQL_RC_RETURN:
1607 case PLPGSQL_RC_RERAISE:
1611 elog(ERROR, "unrecognized rc: %d", rc);
1615 return PLPGSQL_RC_OK;
1620 * exec_stmt_while Loop over statements as long
1621 * as an expression evaluates to
1622 * true or an exit occurs.
1626 exec_stmt_while(PLpgSQL_execstate *estate, PLpgSQL_stmt_while *stmt)
1634 value = exec_eval_boolean(estate, stmt->cond, &isnull);
1635 exec_eval_cleanup(estate);
1637 if (isnull || !value)
1640 rc = exec_stmts(estate, stmt->body);
1647 case PLPGSQL_RC_EXIT:
1648 if (estate->exitlabel == NULL)
1649 return PLPGSQL_RC_OK;
1650 if (stmt->label == NULL)
1651 return PLPGSQL_RC_EXIT;
1652 if (strcmp(stmt->label, estate->exitlabel) != 0)
1653 return PLPGSQL_RC_EXIT;
1654 estate->exitlabel = NULL;
1655 return PLPGSQL_RC_OK;
1657 case PLPGSQL_RC_CONTINUE:
1658 if (estate->exitlabel == NULL)
1659 /* anonymous continue, so re-run loop */
1661 else if (stmt->label != NULL &&
1662 strcmp(stmt->label, estate->exitlabel) == 0)
1663 /* label matches named continue, so re-run loop */
1664 estate->exitlabel = NULL;
1666 /* label doesn't match named continue, propagate upward */
1667 return PLPGSQL_RC_CONTINUE;
1670 case PLPGSQL_RC_RETURN:
1671 case PLPGSQL_RC_RERAISE:
1675 elog(ERROR, "unrecognized rc: %d", rc);
1679 return PLPGSQL_RC_OK;
1684 * exec_stmt_fori Iterate an integer variable
1685 * from a lower to an upper value
1686 * incrementing or decrementing by the BY value
1690 exec_stmt_fori(PLpgSQL_execstate *estate, PLpgSQL_stmt_fori *stmt)
1700 int rc = PLPGSQL_RC_OK;
1702 var = (PLpgSQL_var *) (estate->datums[stmt->var->dno]);
1705 * Get the value of the lower bound
1707 value = exec_eval_expr(estate, stmt->lower, &isnull, &valtype);
1708 value = exec_cast_value(value, valtype, var->datatype->typoid,
1709 &(var->datatype->typinput),
1710 var->datatype->typioparam,
1711 var->datatype->atttypmod, isnull);
1714 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1715 errmsg("lower bound of FOR loop cannot be null")));
1716 loop_value = DatumGetInt32(value);
1717 exec_eval_cleanup(estate);
1720 * Get the value of the upper bound
1722 value = exec_eval_expr(estate, stmt->upper, &isnull, &valtype);
1723 value = exec_cast_value(value, valtype, var->datatype->typoid,
1724 &(var->datatype->typinput),
1725 var->datatype->typioparam,
1726 var->datatype->atttypmod, isnull);
1729 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1730 errmsg("upper bound of FOR loop cannot be null")));
1731 end_value = DatumGetInt32(value);
1732 exec_eval_cleanup(estate);
1735 * Get the step value
1739 value = exec_eval_expr(estate, stmt->step, &isnull, &valtype);
1740 value = exec_cast_value(value, valtype, var->datatype->typoid,
1741 &(var->datatype->typinput),
1742 var->datatype->typioparam,
1743 var->datatype->atttypmod, isnull);
1746 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1747 errmsg("BY value of FOR loop cannot be null")));
1748 step_value = DatumGetInt32(value);
1749 exec_eval_cleanup(estate);
1750 if (step_value <= 0)
1752 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1753 errmsg("BY value of FOR loop must be greater than zero")));
1764 * Check against upper bound
1768 if (loop_value < end_value)
1773 if (loop_value > end_value)
1777 found = true; /* looped at least once */
1780 * Assign current value to loop var
1782 var->value = Int32GetDatum(loop_value);
1783 var->isnull = false;
1786 * Execute the statements
1788 rc = exec_stmts(estate, stmt->body);
1790 if (rc == PLPGSQL_RC_RETURN ||
1791 rc == PLPGSQL_RC_RERAISE)
1792 break; /* break out of the loop */
1793 else if (rc == PLPGSQL_RC_EXIT)
1795 if (estate->exitlabel == NULL)
1796 /* unlabelled exit, finish the current loop */
1798 else if (stmt->label != NULL &&
1799 strcmp(stmt->label, estate->exitlabel) == 0)
1801 /* labelled exit, matches the current stmt's label */
1802 estate->exitlabel = NULL;
1807 * otherwise, this is a labelled exit that does not match the
1808 * current statement's label, if any: return RC_EXIT so that the
1809 * EXIT continues to propagate up the stack.
1813 else if (rc == PLPGSQL_RC_CONTINUE)
1815 if (estate->exitlabel == NULL)
1816 /* unlabelled continue, so re-run the current loop */
1818 else if (stmt->label != NULL &&
1819 strcmp(stmt->label, estate->exitlabel) == 0)
1821 /* label matches named continue, so re-run loop */
1822 estate->exitlabel = NULL;
1828 * otherwise, this is a named continue that does not match the
1829 * current statement's label, if any: return RC_CONTINUE so
1830 * that the CONTINUE will propagate up the stack.
1837 * Increase/decrease loop value, unless it would overflow, in which
1838 * case exit the loop.
1842 if ((int32) (loop_value - step_value) > loop_value)
1844 loop_value -= step_value;
1848 if ((int32) (loop_value + step_value) < loop_value)
1850 loop_value += step_value;
1855 * Set the FOUND variable to indicate the result of executing the loop
1856 * (namely, whether we looped one or more times). This must be set here so
1857 * that it does not interfere with the value of the FOUND variable inside
1858 * the loop processing itself.
1860 exec_set_found(estate, found);
1867 * exec_stmt_fors Execute a query, assign each
1868 * tuple to a record or row and
1869 * execute a group of statements
1874 exec_stmt_fors(PLpgSQL_execstate *estate, PLpgSQL_stmt_fors *stmt)
1880 * Open the implicit cursor for the statement using exec_run_select
1882 exec_run_select(estate, stmt->query, 0, &portal);
1887 rc = exec_for_query(estate, (PLpgSQL_stmt_forq *) stmt, portal, true);
1890 * Close the implicit cursor
1892 SPI_cursor_close(portal);
1899 * exec_stmt_forc Execute a loop for each row from a cursor.
1903 exec_stmt_forc(PLpgSQL_execstate *estate, PLpgSQL_stmt_forc *stmt)
1905 PLpgSQL_var *curvar;
1906 char *curname = NULL;
1907 PLpgSQL_expr *query;
1908 ParamListInfo paramLI;
1913 * Get the cursor variable and if it has an assigned name, check
1914 * that it's not in use currently.
1917 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
1918 if (!curvar->isnull)
1920 curname = TextDatumGetCString(curvar->value);
1921 if (SPI_cursor_find(curname) != NULL)
1923 (errcode(ERRCODE_DUPLICATE_CURSOR),
1924 errmsg("cursor \"%s\" already in use", curname)));
1928 * Open the cursor just like an OPEN command
1930 * Note: parser should already have checked that statement supplies
1931 * args iff cursor needs them, but we check again to be safe.
1934 if (stmt->argquery != NULL)
1937 * OPEN CURSOR with args. We fake a SELECT ... INTO ...
1938 * statement to evaluate the args and put 'em into the
1942 PLpgSQL_stmt_execsql set_args;
1944 if (curvar->cursor_explicit_argrow < 0)
1946 (errcode(ERRCODE_SYNTAX_ERROR),
1947 errmsg("arguments given for cursor without arguments")));
1949 memset(&set_args, 0, sizeof(set_args));
1950 set_args.cmd_type = PLPGSQL_STMT_EXECSQL;
1951 set_args.lineno = stmt->lineno;
1952 set_args.sqlstmt = stmt->argquery;
1953 set_args.into = true;
1954 /* XXX historically this has not been STRICT */
1955 set_args.row = (PLpgSQL_row *)
1956 (estate->datums[curvar->cursor_explicit_argrow]);
1958 if (exec_stmt_execsql(estate, &set_args) != PLPGSQL_RC_OK)
1959 elog(ERROR, "open cursor failed during argument processing");
1963 if (curvar->cursor_explicit_argrow >= 0)
1965 (errcode(ERRCODE_SYNTAX_ERROR),
1966 errmsg("arguments required for cursor")));
1969 query = curvar->cursor_explicit_expr;
1972 if (query->plan == NULL)
1973 exec_prepare_plan(estate, query, curvar->cursor_options);
1976 * Set up ParamListInfo (note this is only carrying a hook function,
1977 * not any actual data values, at this point)
1979 paramLI = setup_param_list(estate, query);
1982 * Open the cursor (the paramlist will get copied into the portal)
1984 portal = SPI_cursor_open_with_paramlist(curname, query->plan,
1986 estate->readonly_func);
1988 elog(ERROR, "could not open cursor: %s",
1989 SPI_result_code_string(SPI_result));
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 MemoryContext oldcxt;
2182 HeapTuple tuple = NULL;
2183 bool free_tuple = false;
2185 if (!estate->retisset)
2187 (errcode(ERRCODE_SYNTAX_ERROR),
2188 errmsg("cannot use RETURN NEXT in a non-SETOF function")));
2190 if (estate->tuple_store == NULL)
2191 exec_init_tuple_store(estate);
2193 /* rettupdesc will be filled by exec_init_tuple_store */
2194 tupdesc = estate->rettupdesc;
2195 natts = tupdesc->natts;
2197 if (stmt->retvarno >= 0)
2199 PLpgSQL_datum *retvar = estate->datums[stmt->retvarno];
2201 switch (retvar->dtype)
2203 case PLPGSQL_DTYPE_VAR:
2205 PLpgSQL_var *var = (PLpgSQL_var *) retvar;
2206 Datum retval = var->value;
2207 bool isNull = var->isnull;
2211 (errcode(ERRCODE_DATATYPE_MISMATCH),
2212 errmsg("wrong result type supplied in RETURN NEXT")));
2214 /* coerce type if needed */
2215 retval = exec_simple_cast_value(retval,
2216 var->datatype->typoid,
2217 tupdesc->attrs[0]->atttypid,
2218 tupdesc->attrs[0]->atttypmod,
2221 oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
2222 tuplestore_putvalues(estate->tuple_store, tupdesc,
2224 MemoryContextSwitchTo(oldcxt);
2228 case PLPGSQL_DTYPE_REC:
2230 PLpgSQL_rec *rec = (PLpgSQL_rec *) retvar;
2231 TupleConversionMap *tupmap;
2233 if (!HeapTupleIsValid(rec->tup))
2235 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2236 errmsg("record \"%s\" is not assigned yet",
2238 errdetail("The tuple structure of a not-yet-assigned"
2239 " record is indeterminate.")));
2240 tupmap = convert_tuples_by_position(rec->tupdesc,
2242 gettext_noop("wrong record type supplied in RETURN NEXT"));
2244 /* it might need conversion */
2247 tuple = do_convert_tuple(tuple, tupmap);
2248 free_conversion_map(tupmap);
2253 case PLPGSQL_DTYPE_ROW:
2255 PLpgSQL_row *row = (PLpgSQL_row *) retvar;
2257 tuple = make_tuple_from_row(estate, row, tupdesc);
2260 (errcode(ERRCODE_DATATYPE_MISMATCH),
2261 errmsg("wrong record type supplied in RETURN NEXT")));
2267 elog(ERROR, "unrecognized dtype: %d", retvar->dtype);
2271 else if (stmt->expr)
2279 (errcode(ERRCODE_DATATYPE_MISMATCH),
2280 errmsg("wrong result type supplied in RETURN NEXT")));
2282 retval = exec_eval_expr(estate,
2287 /* coerce type if needed */
2288 retval = exec_simple_cast_value(retval,
2290 tupdesc->attrs[0]->atttypid,
2291 tupdesc->attrs[0]->atttypmod,
2294 oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
2295 tuplestore_putvalues(estate->tuple_store, tupdesc,
2297 MemoryContextSwitchTo(oldcxt);
2299 exec_eval_cleanup(estate);
2304 (errcode(ERRCODE_SYNTAX_ERROR),
2305 errmsg("RETURN NEXT must have a parameter")));
2308 if (HeapTupleIsValid(tuple))
2310 oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
2311 tuplestore_puttuple(estate->tuple_store, tuple);
2312 MemoryContextSwitchTo(oldcxt);
2315 heap_freetuple(tuple);
2318 return PLPGSQL_RC_OK;
2322 * exec_stmt_return_query Evaluate a query and add it to the
2323 * list of tuples returned by the current
2328 exec_stmt_return_query(PLpgSQL_execstate *estate,
2329 PLpgSQL_stmt_return_query *stmt)
2332 uint32 processed = 0;
2333 TupleConversionMap *tupmap;
2335 if (!estate->retisset)
2337 (errcode(ERRCODE_SYNTAX_ERROR),
2338 errmsg("cannot use RETURN QUERY in a non-SETOF function")));
2340 if (estate->tuple_store == NULL)
2341 exec_init_tuple_store(estate);
2343 if (stmt->query != NULL)
2346 exec_run_select(estate, stmt->query, 0, &portal);
2350 /* RETURN QUERY EXECUTE */
2351 Assert(stmt->dynquery != NULL);
2352 portal = exec_dynquery_with_params(estate, stmt->dynquery,
2356 tupmap = convert_tuples_by_position(portal->tupDesc,
2358 gettext_noop("structure of query does not match function result type"));
2362 MemoryContext old_cxt;
2365 SPI_cursor_fetch(portal, true, 50);
2366 if (SPI_processed == 0)
2369 old_cxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
2370 for (i = 0; i < SPI_processed; i++)
2372 HeapTuple tuple = SPI_tuptable->vals[i];
2375 tuple = do_convert_tuple(tuple, tupmap);
2376 tuplestore_puttuple(estate->tuple_store, tuple);
2378 heap_freetuple(tuple);
2381 MemoryContextSwitchTo(old_cxt);
2383 SPI_freetuptable(SPI_tuptable);
2387 free_conversion_map(tupmap);
2389 SPI_freetuptable(SPI_tuptable);
2390 SPI_cursor_close(portal);
2392 estate->eval_processed = processed;
2393 exec_set_found(estate, processed != 0);
2395 return PLPGSQL_RC_OK;
2399 exec_init_tuple_store(PLpgSQL_execstate *estate)
2401 ReturnSetInfo *rsi = estate->rsi;
2402 MemoryContext oldcxt;
2405 * Check caller can handle a set result in the way we want
2407 if (!rsi || !IsA(rsi, ReturnSetInfo) ||
2408 (rsi->allowedModes & SFRM_Materialize) == 0 ||
2409 rsi->expectedDesc == NULL)
2411 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2412 errmsg("set-valued function called in context that cannot accept a set")));
2414 estate->tuple_store_cxt = rsi->econtext->ecxt_per_query_memory;
2416 oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
2417 estate->tuple_store =
2418 tuplestore_begin_heap(rsi->allowedModes & SFRM_Materialize_Random,
2420 MemoryContextSwitchTo(oldcxt);
2422 estate->rettupdesc = rsi->expectedDesc;
2426 * exec_stmt_raise Build a message and throw it with elog()
2430 exec_stmt_raise(PLpgSQL_execstate *estate, PLpgSQL_stmt_raise *stmt)
2433 char *condname = NULL;
2434 char *err_message = NULL;
2435 char *err_detail = NULL;
2436 char *err_hint = NULL;
2439 /* RAISE with no parameters: re-throw current exception */
2440 if (stmt->condname == NULL && stmt->message == NULL &&
2441 stmt->options == NIL)
2442 return PLPGSQL_RC_RERAISE;
2446 err_code = plpgsql_recognize_err_condition(stmt->condname, true);
2447 condname = pstrdup(stmt->condname);
2453 ListCell *current_param;
2456 initStringInfo(&ds);
2457 current_param = list_head(stmt->params);
2459 for (cp = stmt->message; *cp; cp++)
2462 * Occurrences of a single % are replaced by the next parameter's
2463 * external representation. Double %'s are converted to one %.
2474 appendStringInfoChar(&ds, '%');
2479 if (current_param == NULL)
2481 (errcode(ERRCODE_SYNTAX_ERROR),
2482 errmsg("too few parameters specified for RAISE")));
2484 paramvalue = exec_eval_expr(estate,
2485 (PLpgSQL_expr *) lfirst(current_param),
2492 extval = convert_value_to_string(paramvalue, paramtypeid);
2493 appendStringInfoString(&ds, extval);
2494 current_param = lnext(current_param);
2495 exec_eval_cleanup(estate);
2498 appendStringInfoChar(&ds, cp[0]);
2502 * If more parameters were specified than were required to process the
2503 * format string, throw an error
2505 if (current_param != NULL)
2507 (errcode(ERRCODE_SYNTAX_ERROR),
2508 errmsg("too many parameters specified for RAISE")));
2510 err_message = ds.data;
2511 /* No pfree(ds.data), the pfree(err_message) does it */
2514 foreach(lc, stmt->options)
2516 PLpgSQL_raise_option *opt = (PLpgSQL_raise_option *) lfirst(lc);
2522 optionvalue = exec_eval_expr(estate, opt->expr,
2527 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2528 errmsg("RAISE statement option cannot be null")));
2530 extval = convert_value_to_string(optionvalue, optiontypeid);
2532 switch (opt->opt_type)
2534 case PLPGSQL_RAISEOPTION_ERRCODE:
2537 (errcode(ERRCODE_SYNTAX_ERROR),
2538 errmsg("RAISE option already specified: %s",
2540 err_code = plpgsql_recognize_err_condition(extval, true);
2541 condname = pstrdup(extval);
2543 case PLPGSQL_RAISEOPTION_MESSAGE:
2546 (errcode(ERRCODE_SYNTAX_ERROR),
2547 errmsg("RAISE option already specified: %s",
2549 err_message = pstrdup(extval);
2551 case PLPGSQL_RAISEOPTION_DETAIL:
2554 (errcode(ERRCODE_SYNTAX_ERROR),
2555 errmsg("RAISE option already specified: %s",
2557 err_detail = pstrdup(extval);
2559 case PLPGSQL_RAISEOPTION_HINT:
2562 (errcode(ERRCODE_SYNTAX_ERROR),
2563 errmsg("RAISE option already specified: %s",
2565 err_hint = pstrdup(extval);
2568 elog(ERROR, "unrecognized raise option: %d", opt->opt_type);
2571 exec_eval_cleanup(estate);
2574 /* Default code if nothing specified */
2575 if (err_code == 0 && stmt->elog_level >= ERROR)
2576 err_code = ERRCODE_RAISE_EXCEPTION;
2578 /* Default error message if nothing specified */
2579 if (err_message == NULL)
2583 err_message = condname;
2587 err_message = pstrdup(unpack_sql_state(err_code));
2591 * Throw the error (may or may not come back)
2593 estate->err_text = raise_skip_msg; /* suppress traceback of raise */
2595 ereport(stmt->elog_level,
2596 (err_code ? errcode(err_code) : 0,
2597 errmsg_internal("%s", err_message),
2598 (err_detail != NULL) ? errdetail("%s", err_detail) : 0,
2599 (err_hint != NULL) ? errhint("%s", err_hint) : 0));
2601 estate->err_text = NULL; /* un-suppress... */
2603 if (condname != NULL)
2605 if (err_message != NULL)
2607 if (err_detail != NULL)
2609 if (err_hint != NULL)
2612 return PLPGSQL_RC_OK;
2617 * Initialize a mostly empty execution state
2621 plpgsql_estate_setup(PLpgSQL_execstate *estate,
2622 PLpgSQL_function *func,
2625 /* this link will be restored at exit from plpgsql_call_handler */
2626 func->cur_estate = estate;
2628 estate->func = func;
2630 estate->retval = (Datum) 0;
2631 estate->retisnull = true;
2632 estate->rettype = InvalidOid;
2634 estate->fn_rettype = func->fn_rettype;
2635 estate->retistuple = func->fn_retistuple;
2636 estate->retisset = func->fn_retset;
2638 estate->readonly_func = func->fn_readonly;
2640 estate->rettupdesc = NULL;
2641 estate->exitlabel = NULL;
2643 estate->tuple_store = NULL;
2644 estate->tuple_store_cxt = NULL;
2647 estate->found_varno = func->found_varno;
2648 estate->ndatums = func->ndatums;
2649 estate->datums = palloc(sizeof(PLpgSQL_datum *) * estate->ndatums);
2650 /* caller is expected to fill the datums array */
2652 estate->eval_tuptable = NULL;
2653 estate->eval_processed = 0;
2654 estate->eval_lastoid = InvalidOid;
2655 estate->eval_econtext = NULL;
2656 estate->cur_expr = NULL;
2658 estate->err_stmt = NULL;
2659 estate->err_text = NULL;
2661 estate->plugin_info = NULL;
2664 * Create an EState and ExprContext for evaluation of simple expressions.
2666 plpgsql_create_econtext(estate);
2669 * Let the plugin see this function before we initialize any local
2670 * PL/pgSQL variables - note that we also give the plugin a few function
2671 * pointers so it can call back into PL/pgSQL for doing things like
2672 * variable assignments and stack traces
2676 (*plugin_ptr)->error_callback = plpgsql_exec_error_callback;
2677 (*plugin_ptr)->assign_expr = exec_assign_expr;
2679 if ((*plugin_ptr)->func_setup)
2680 ((*plugin_ptr)->func_setup) (estate, func);
2685 * Release temporary memory used by expression/subselect evaluation
2687 * NB: the result of the evaluation is no longer valid after this is done,
2688 * unless it is a pass-by-value datatype.
2692 exec_eval_cleanup(PLpgSQL_execstate *estate)
2694 /* Clear result of a full SPI_execute */
2695 if (estate->eval_tuptable != NULL)
2696 SPI_freetuptable(estate->eval_tuptable);
2697 estate->eval_tuptable = NULL;
2699 /* Clear result of exec_eval_simple_expr (but keep the econtext) */
2700 if (estate->eval_econtext != NULL)
2701 ResetExprContext(estate->eval_econtext);
2706 * Generate a prepared plan
2710 exec_prepare_plan(PLpgSQL_execstate *estate,
2711 PLpgSQL_expr *expr, int cursorOptions)
2716 * The grammar can't conveniently set expr->func while building the
2717 * parse tree, so make sure it's set before parser hooks need it.
2719 expr->func = estate->func;
2722 * Generate and save the plan
2724 plan = SPI_prepare_params(expr->query,
2725 (ParserSetupHook) plpgsql_parser_setup,
2730 /* Some SPI errors deserve specific error messages */
2733 case SPI_ERROR_COPY:
2735 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2736 errmsg("cannot COPY to/from client in PL/pgSQL")));
2737 case SPI_ERROR_TRANSACTION:
2739 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2740 errmsg("cannot begin/end transactions in PL/pgSQL"),
2741 errhint("Use a BEGIN block with an EXCEPTION clause instead.")));
2743 elog(ERROR, "SPI_prepare_params failed for \"%s\": %s",
2744 expr->query, SPI_result_code_string(SPI_result));
2747 expr->plan = SPI_saveplan(plan);
2749 exec_simple_check_plan(expr);
2754 * exec_stmt_execsql Execute an SQL statement (possibly with INTO).
2758 exec_stmt_execsql(PLpgSQL_execstate *estate,
2759 PLpgSQL_stmt_execsql *stmt)
2761 ParamListInfo paramLI;
2764 PLpgSQL_expr *expr = stmt->sqlstmt;
2767 * On the first call for this statement generate the plan, and detect
2768 * whether the statement is INSERT/UPDATE/DELETE
2770 if (expr->plan == NULL)
2774 exec_prepare_plan(estate, expr, 0);
2775 stmt->mod_stmt = false;
2776 foreach(l, expr->plan->plancache_list)
2778 CachedPlanSource *plansource = (CachedPlanSource *) lfirst(l);
2781 foreach(l2, plansource->plan->stmt_list)
2783 PlannedStmt *p = (PlannedStmt *) lfirst(l2);
2785 if (IsA(p, PlannedStmt) &&
2788 if (p->commandType == CMD_INSERT ||
2789 p->commandType == CMD_UPDATE ||
2790 p->commandType == CMD_DELETE)
2791 stmt->mod_stmt = true;
2798 * Set up ParamListInfo (note this is only carrying a hook function,
2799 * not any actual data values, at this point)
2801 paramLI = setup_param_list(estate, expr);
2804 * If we have INTO, then we only need one row back ... but if we have INTO
2805 * STRICT, ask for two rows, so that we can verify the statement returns
2806 * only one. INSERT/UPDATE/DELETE are always treated strictly. Without
2807 * INTO, just run the statement to completion (tcount = 0).
2809 * We could just ask for two rows always when using INTO, but there are
2810 * some cases where demanding the extra row costs significant time, eg by
2811 * forcing completion of a sequential scan. So don't do it unless we need
2812 * to enforce strictness.
2816 if (stmt->strict || stmt->mod_stmt)
2827 rc = SPI_execute_plan_with_paramlist(expr->plan, paramLI,
2828 estate->readonly_func, tcount);
2831 * Check for error, and set FOUND if appropriate (for historical reasons
2832 * we set FOUND only for certain query types). Also Assert that we
2833 * identified the statement type the same as SPI did.
2838 Assert(!stmt->mod_stmt);
2839 exec_set_found(estate, (SPI_processed != 0));
2845 case SPI_OK_INSERT_RETURNING:
2846 case SPI_OK_UPDATE_RETURNING:
2847 case SPI_OK_DELETE_RETURNING:
2848 Assert(stmt->mod_stmt);
2849 exec_set_found(estate, (SPI_processed != 0));
2852 case SPI_OK_SELINTO:
2853 case SPI_OK_UTILITY:
2854 Assert(!stmt->mod_stmt);
2857 case SPI_OK_REWRITTEN:
2858 Assert(!stmt->mod_stmt);
2861 * The command was rewritten into another kind of command. It's
2862 * not clear what FOUND would mean in that case (and SPI doesn't
2863 * return the row count either), so just set it to false.
2865 exec_set_found(estate, false);
2869 elog(ERROR, "SPI_execute_plan_with_paramlist failed executing query \"%s\": %s",
2870 expr->query, SPI_result_code_string(rc));
2873 /* All variants should save result info for GET DIAGNOSTICS */
2874 estate->eval_processed = SPI_processed;
2875 estate->eval_lastoid = SPI_lastoid;
2877 /* Process INTO if present */
2880 SPITupleTable *tuptab = SPI_tuptable;
2881 uint32 n = SPI_processed;
2882 PLpgSQL_rec *rec = NULL;
2883 PLpgSQL_row *row = NULL;
2885 /* If the statement did not return a tuple table, complain */
2888 (errcode(ERRCODE_SYNTAX_ERROR),
2889 errmsg("INTO used with a command that cannot return data")));
2891 /* Determine if we assign to a record or a row */
2892 if (stmt->rec != NULL)
2893 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->dno]);
2894 else if (stmt->row != NULL)
2895 row = (PLpgSQL_row *) (estate->datums[stmt->row->dno]);
2897 elog(ERROR, "unsupported target");
2900 * If SELECT ... INTO specified STRICT, and the query didn't find
2901 * exactly one row, throw an error. If STRICT was not specified, then
2902 * allow the query to find any number of rows.
2908 (errcode(ERRCODE_NO_DATA_FOUND),
2909 errmsg("query returned no rows")));
2910 /* set the target to NULL(s) */
2911 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
2915 if (n > 1 && (stmt->strict || stmt->mod_stmt))
2917 (errcode(ERRCODE_TOO_MANY_ROWS),
2918 errmsg("query returned more than one row")));
2919 /* Put the first result row into the target */
2920 exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
2924 SPI_freetuptable(SPI_tuptable);
2928 /* If the statement returned a tuple table, complain */
2929 if (SPI_tuptable != NULL)
2931 (errcode(ERRCODE_SYNTAX_ERROR),
2932 errmsg("query has no destination for result data"),
2933 (rc == SPI_OK_SELECT) ? errhint("If you want to discard the results of a SELECT, use PERFORM instead.") : 0));
2939 return PLPGSQL_RC_OK;
2944 * exec_stmt_dynexecute Execute a dynamic SQL query
2945 * (possibly with INTO).
2949 exec_stmt_dynexecute(PLpgSQL_execstate *estate,
2950 PLpgSQL_stmt_dynexecute *stmt)
2953 bool isnull = false;
2959 * First we evaluate the string expression after the EXECUTE keyword. Its
2960 * result is the querystring we have to execute.
2962 query = exec_eval_expr(estate, stmt->query, &isnull, &restype);
2965 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2966 errmsg("query string argument of EXECUTE is null")));
2968 /* Get the C-String representation */
2969 querystr = convert_value_to_string(query, restype);
2971 exec_eval_cleanup(estate);
2974 * Execute the query without preparing a saved plan.
2978 PreparedParamsData *ppd;
2980 ppd = exec_eval_using_params(estate, stmt->params);
2981 exec_res = SPI_execute_with_args(querystr,
2982 ppd->nargs, ppd->types,
2983 ppd->values, ppd->nulls,
2984 estate->readonly_func, 0);
2985 free_params_data(ppd);
2988 exec_res = SPI_execute(querystr, estate->readonly_func, 0);
2996 case SPI_OK_INSERT_RETURNING:
2997 case SPI_OK_UPDATE_RETURNING:
2998 case SPI_OK_DELETE_RETURNING:
2999 case SPI_OK_UTILITY:
3000 case SPI_OK_REWRITTEN:
3006 * Also allow a zero return, which implies the querystring
3007 * contained no commands.
3011 case SPI_OK_SELINTO:
3014 * We want to disallow SELECT INTO for now, because its behavior
3015 * is not consistent with SELECT INTO in a normal plpgsql context.
3016 * (We need to reimplement EXECUTE to parse the string as a
3017 * plpgsql command, not just feed it to SPI_execute.) However,
3018 * CREATE AS should be allowed ... and since it produces the same
3019 * parsetree as SELECT INTO, there's no way to tell the difference
3020 * except to look at the source text. Wotta kluge!
3025 for (ptr = querystr; *ptr; ptr++)
3026 if (!scanner_isspace(*ptr))
3028 if (*ptr == 'S' || *ptr == 's')
3030 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3031 errmsg("EXECUTE of SELECT ... INTO is not implemented")));
3035 /* Some SPI errors deserve specific error messages */
3036 case SPI_ERROR_COPY:
3038 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3039 errmsg("cannot COPY to/from client in PL/pgSQL")));
3040 case SPI_ERROR_TRANSACTION:
3042 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3043 errmsg("cannot begin/end transactions in PL/pgSQL"),
3044 errhint("Use a BEGIN block with an EXCEPTION clause instead.")));
3047 elog(ERROR, "SPI_execute failed executing query \"%s\": %s",
3048 querystr, SPI_result_code_string(exec_res));
3052 /* Save result info for GET DIAGNOSTICS */
3053 estate->eval_processed = SPI_processed;
3054 estate->eval_lastoid = SPI_lastoid;
3056 /* Process INTO if present */
3059 SPITupleTable *tuptab = SPI_tuptable;
3060 uint32 n = SPI_processed;
3061 PLpgSQL_rec *rec = NULL;
3062 PLpgSQL_row *row = NULL;
3064 /* If the statement did not return a tuple table, complain */
3067 (errcode(ERRCODE_SYNTAX_ERROR),
3068 errmsg("INTO used with a command that cannot return data")));
3070 /* Determine if we assign to a record or a row */
3071 if (stmt->rec != NULL)
3072 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->dno]);
3073 else if (stmt->row != NULL)
3074 row = (PLpgSQL_row *) (estate->datums[stmt->row->dno]);
3076 elog(ERROR, "unsupported target");
3079 * If SELECT ... INTO specified STRICT, and the query didn't find
3080 * exactly one row, throw an error. If STRICT was not specified, then
3081 * allow the query to find any number of rows.
3087 (errcode(ERRCODE_NO_DATA_FOUND),
3088 errmsg("query returned no rows")));
3089 /* set the target to NULL(s) */
3090 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
3094 if (n > 1 && stmt->strict)
3096 (errcode(ERRCODE_TOO_MANY_ROWS),
3097 errmsg("query returned more than one row")));
3098 /* Put the first result row into the target */
3099 exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
3105 * It might be a good idea to raise an error if the query returned
3106 * tuples that are being ignored, but historically we have not done
3111 /* Release any result from SPI_execute, as well as the querystring */
3112 SPI_freetuptable(SPI_tuptable);
3115 return PLPGSQL_RC_OK;
3120 * exec_stmt_dynfors Execute a dynamic query, assign each
3121 * tuple to a record or row and
3122 * execute a group of statements
3127 exec_stmt_dynfors(PLpgSQL_execstate *estate, PLpgSQL_stmt_dynfors *stmt)
3132 portal = exec_dynquery_with_params(estate, stmt->query, stmt->params);
3137 rc = exec_for_query(estate, (PLpgSQL_stmt_forq *) stmt, portal, true);
3140 * Close the implicit cursor
3142 SPI_cursor_close(portal);
3149 * exec_stmt_open Execute an OPEN cursor statement
3153 exec_stmt_open(PLpgSQL_execstate *estate, PLpgSQL_stmt_open *stmt)
3155 PLpgSQL_var *curvar;
3156 char *curname = NULL;
3157 PLpgSQL_expr *query;
3159 ParamListInfo paramLI;
3163 * Get the cursor variable and if it has an assigned name, check
3164 * that it's not in use currently.
3167 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
3168 if (!curvar->isnull)
3170 curname = TextDatumGetCString(curvar->value);
3171 if (SPI_cursor_find(curname) != NULL)
3173 (errcode(ERRCODE_DUPLICATE_CURSOR),
3174 errmsg("cursor \"%s\" already in use", curname)));
3178 * Process the OPEN according to it's type.
3181 if (stmt->query != NULL)
3184 * This is an OPEN refcursor FOR SELECT ...
3186 * We just make sure the query is planned. The real work is
3190 query = stmt->query;
3191 if (query->plan == NULL)
3192 exec_prepare_plan(estate, query, stmt->cursor_options);
3194 else if (stmt->dynquery != NULL)
3197 * This is an OPEN refcursor FOR EXECUTE ...
3206 * We evaluate the string expression after the
3207 * EXECUTE keyword. It's result is the querystring we have
3211 queryD = exec_eval_expr(estate, stmt->dynquery, &isnull, &restype);
3214 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3215 errmsg("query string argument of EXECUTE is null")));
3217 /* Get the C-String representation */
3218 querystr = convert_value_to_string(queryD, restype);
3220 exec_eval_cleanup(estate);
3223 * Now we prepare a query plan for it and open a cursor
3226 curplan = SPI_prepare_cursor(querystr, 0, NULL, stmt->cursor_options);
3227 if (curplan == NULL)
3228 elog(ERROR, "SPI_prepare_cursor failed for \"%s\": %s",
3229 querystr, SPI_result_code_string(SPI_result));
3230 portal = SPI_cursor_open(curname, curplan, NULL, NULL,
3231 estate->readonly_func);
3233 elog(ERROR, "could not open cursor for query \"%s\": %s",
3234 querystr, SPI_result_code_string(SPI_result));
3236 SPI_freeplan(curplan);
3239 * If cursor variable was NULL, store the generated portal name in it
3241 if (curname == NULL)
3242 assign_text_var(curvar, portal->name);
3244 return PLPGSQL_RC_OK;
3249 * This is an OPEN cursor
3251 * Note: parser should already have checked that statement supplies
3252 * args iff cursor needs them, but we check again to be safe.
3255 if (stmt->argquery != NULL)
3258 * OPEN CURSOR with args. We fake a SELECT ... INTO ...
3259 * statement to evaluate the args and put 'em into the
3263 PLpgSQL_stmt_execsql set_args;
3265 if (curvar->cursor_explicit_argrow < 0)
3267 (errcode(ERRCODE_SYNTAX_ERROR),
3268 errmsg("arguments given for cursor without arguments")));
3270 memset(&set_args, 0, sizeof(set_args));
3271 set_args.cmd_type = PLPGSQL_STMT_EXECSQL;
3272 set_args.lineno = stmt->lineno;
3273 set_args.sqlstmt = stmt->argquery;
3274 set_args.into = true;
3275 /* XXX historically this has not been STRICT */
3276 set_args.row = (PLpgSQL_row *)
3277 (estate->datums[curvar->cursor_explicit_argrow]);
3279 if (exec_stmt_execsql(estate, &set_args) != PLPGSQL_RC_OK)
3280 elog(ERROR, "open cursor failed during argument processing");
3284 if (curvar->cursor_explicit_argrow >= 0)
3286 (errcode(ERRCODE_SYNTAX_ERROR),
3287 errmsg("arguments required for cursor")));
3290 query = curvar->cursor_explicit_expr;
3291 if (query->plan == NULL)
3292 exec_prepare_plan(estate, query, curvar->cursor_options);
3296 * Set up ParamListInfo (note this is only carrying a hook function,
3297 * not any actual data values, at this point)
3299 paramLI = setup_param_list(estate, query);
3304 portal = SPI_cursor_open_with_paramlist(curname, query->plan,
3306 estate->readonly_func);
3308 elog(ERROR, "could not open cursor: %s",
3309 SPI_result_code_string(SPI_result));
3312 * If cursor variable was NULL, store the generated portal name in it
3314 if (curname == NULL)
3315 assign_text_var(curvar, portal->name);
3322 return PLPGSQL_RC_OK;
3327 * exec_stmt_fetch Fetch from a cursor into a target, or just
3328 * move the current position of the cursor
3332 exec_stmt_fetch(PLpgSQL_execstate *estate, PLpgSQL_stmt_fetch *stmt)
3334 PLpgSQL_var *curvar = NULL;
3335 PLpgSQL_rec *rec = NULL;
3336 PLpgSQL_row *row = NULL;
3337 long how_many = stmt->how_many;
3338 SPITupleTable *tuptab;
3344 * Get the portal of the cursor by name
3347 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
3350 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3351 errmsg("cursor variable \"%s\" is null", curvar->refname)));
3352 curname = TextDatumGetCString(curvar->value);
3354 portal = SPI_cursor_find(curname);
3357 (errcode(ERRCODE_UNDEFINED_CURSOR),
3358 errmsg("cursor \"%s\" does not exist", curname)));
3361 /* Calculate position for FETCH_RELATIVE or FETCH_ABSOLUTE */
3366 /* XXX should be doing this in LONG not INT width */
3367 how_many = exec_eval_integer(estate, stmt->expr, &isnull);
3371 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3372 errmsg("relative or absolute cursor position is null")));
3374 exec_eval_cleanup(estate);
3380 * Determine if we fetch into a record or a row
3383 if (stmt->rec != NULL)
3384 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->dno]);
3385 else if (stmt->row != NULL)
3386 row = (PLpgSQL_row *) (estate->datums[stmt->row->dno]);
3388 elog(ERROR, "unsupported target");
3391 * Fetch 1 tuple from the cursor
3394 SPI_scroll_cursor_fetch(portal, stmt->direction, how_many);
3395 tuptab = SPI_tuptable;
3399 * Set the target appropriately.
3403 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
3405 exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
3407 SPI_freetuptable(tuptab);
3411 /* Move the cursor */
3412 SPI_scroll_cursor_move(portal, stmt->direction, how_many);
3416 /* Set the ROW_COUNT and the global FOUND variable appropriately. */
3417 estate->eval_processed = n;
3418 exec_set_found(estate, n != 0);
3420 return PLPGSQL_RC_OK;
3424 * exec_stmt_close Close a cursor
3428 exec_stmt_close(PLpgSQL_execstate *estate, PLpgSQL_stmt_close *stmt)
3430 PLpgSQL_var *curvar = NULL;
3435 * Get the portal of the cursor by name
3438 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
3441 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3442 errmsg("cursor variable \"%s\" is null", curvar->refname)));
3443 curname = TextDatumGetCString(curvar->value);
3445 portal = SPI_cursor_find(curname);
3448 (errcode(ERRCODE_UNDEFINED_CURSOR),
3449 errmsg("cursor \"%s\" does not exist", curname)));
3456 SPI_cursor_close(portal);
3458 return PLPGSQL_RC_OK;
3463 * exec_assign_expr Put an expression's result into
3468 exec_assign_expr(PLpgSQL_execstate *estate, PLpgSQL_datum *target,
3473 bool isnull = false;
3475 value = exec_eval_expr(estate, expr, &isnull, &valtype);
3476 exec_assign_value(estate, target, value, valtype, &isnull);
3477 exec_eval_cleanup(estate);
3482 * exec_assign_value Put a value into a target field
3486 exec_assign_value(PLpgSQL_execstate *estate,
3487 PLpgSQL_datum *target,
3488 Datum value, Oid valtype, bool *isNull)
3490 switch (target->dtype)
3492 case PLPGSQL_DTYPE_VAR:
3495 * Target is a variable
3497 PLpgSQL_var *var = (PLpgSQL_var *) target;
3500 newvalue = exec_cast_value(value, valtype, var->datatype->typoid,
3501 &(var->datatype->typinput),
3502 var->datatype->typioparam,
3503 var->datatype->atttypmod,
3506 if (*isNull && var->notnull)
3508 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3509 errmsg("null value cannot be assigned to variable \"%s\" declared NOT NULL",
3513 * If type is by-reference, make sure we have a freshly
3514 * palloc'd copy; the originally passed value may not live as
3515 * long as the variable! But we don't need to re-copy if
3516 * exec_cast_value performed a conversion; its output must
3517 * already be palloc'd.
3519 if (!var->datatype->typbyval && !*isNull)
3521 if (newvalue == value)
3522 newvalue = datumCopy(newvalue,
3524 var->datatype->typlen);
3528 * Now free the old value. (We can't do this any earlier
3529 * because of the possibility that we are assigning the var's
3530 * old value to it, eg "foo := foo". We could optimize out
3531 * the assignment altogether in such cases, but it's too
3532 * infrequent to be worth testing for.)
3536 var->value = newvalue;
3537 var->isnull = *isNull;
3538 if (!var->datatype->typbyval && !*isNull)
3539 var->freeval = true;
3543 case PLPGSQL_DTYPE_ROW:
3546 * Target is a row variable
3548 PLpgSQL_row *row = (PLpgSQL_row *) target;
3550 /* Source must be of RECORD or composite type */
3551 if (!type_is_rowtype(valtype))
3553 (errcode(ERRCODE_DATATYPE_MISMATCH),
3554 errmsg("cannot assign non-composite value to a row variable")));
3557 /* If source is null, just assign nulls to the row */
3558 exec_move_row(estate, NULL, row, NULL, NULL);
3566 HeapTupleData tmptup;
3568 /* Else source is a tuple Datum, safe to do this: */
3569 td = DatumGetHeapTupleHeader(value);
3570 /* Extract rowtype info and find a tupdesc */
3571 tupType = HeapTupleHeaderGetTypeId(td);
3572 tupTypmod = HeapTupleHeaderGetTypMod(td);
3573 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
3574 /* Build a temporary HeapTuple control structure */
3575 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
3576 ItemPointerSetInvalid(&(tmptup.t_self));
3577 tmptup.t_tableOid = InvalidOid;
3579 exec_move_row(estate, NULL, row, &tmptup, tupdesc);
3580 ReleaseTupleDesc(tupdesc);
3585 case PLPGSQL_DTYPE_REC:
3588 * Target is a record variable
3590 PLpgSQL_rec *rec = (PLpgSQL_rec *) target;
3592 /* Source must be of RECORD or composite type */
3593 if (!type_is_rowtype(valtype))
3595 (errcode(ERRCODE_DATATYPE_MISMATCH),
3596 errmsg("cannot assign non-composite value to a record variable")));
3599 /* If source is null, just assign nulls to the record */
3600 exec_move_row(estate, rec, NULL, NULL, NULL);
3608 HeapTupleData tmptup;
3610 /* Else source is a tuple Datum, safe to do this: */
3611 td = DatumGetHeapTupleHeader(value);
3612 /* Extract rowtype info and find a tupdesc */
3613 tupType = HeapTupleHeaderGetTypeId(td);
3614 tupTypmod = HeapTupleHeaderGetTypMod(td);
3615 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
3616 /* Build a temporary HeapTuple control structure */
3617 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
3618 ItemPointerSetInvalid(&(tmptup.t_self));
3619 tmptup.t_tableOid = InvalidOid;
3621 exec_move_row(estate, rec, NULL, &tmptup, tupdesc);
3622 ReleaseTupleDesc(tupdesc);
3627 case PLPGSQL_DTYPE_RECFIELD:
3630 * Target is a field of a record
3632 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) target;
3645 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
3648 * Check that there is already a tuple in the record. We need
3649 * that because records don't have any predefined field
3652 if (!HeapTupleIsValid(rec->tup))
3654 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3655 errmsg("record \"%s\" is not assigned yet",
3657 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
3660 * Get the number of the records field to change and the
3661 * number of attributes in the tuple. Note: disallow system
3662 * column names because the code below won't cope.
3664 fno = SPI_fnumber(rec->tupdesc, recfield->fieldname);
3667 (errcode(ERRCODE_UNDEFINED_COLUMN),
3668 errmsg("record \"%s\" has no field \"%s\"",
3669 rec->refname, recfield->fieldname)));
3671 natts = rec->tupdesc->natts;
3674 * Set up values/control arrays for heap_modify_tuple. For all
3675 * the attributes except the one we want to replace, use the
3676 * value that's in the old tuple.
3678 values = palloc(sizeof(Datum) * natts);
3679 nulls = palloc(sizeof(bool) * natts);
3680 replaces = palloc(sizeof(bool) * natts);
3682 memset(replaces, false, sizeof(bool) * natts);
3683 replaces[fno] = true;
3686 * Now insert the new value, being careful to cast it to the
3689 atttype = SPI_gettypeid(rec->tupdesc, fno + 1);
3690 atttypmod = rec->tupdesc->attrs[fno]->atttypmod;
3691 attisnull = *isNull;
3692 values[fno] = exec_simple_cast_value(value,
3697 nulls[fno] = attisnull;
3700 * Avoid leaking the result of exec_simple_cast_value, if it
3701 * performed a conversion to a pass-by-ref type.
3703 if (!attisnull && values[fno] != value && !get_typbyval(atttype))
3704 mustfree = DatumGetPointer(values[fno]);
3709 * Now call heap_modify_tuple() to create a new tuple that
3710 * replaces the old one in the record.
3712 newtup = heap_modify_tuple(rec->tup, rec->tupdesc,
3713 values, nulls, replaces);
3716 heap_freetuple(rec->tup);
3719 rec->freetup = true;
3730 case PLPGSQL_DTYPE_ARRAYELEM:
3734 PLpgSQL_expr *subscripts[MAXDIM];
3735 int subscriptvals[MAXDIM];
3736 bool oldarrayisnull;
3743 Datum oldarraydatum,
3745 ArrayType *oldarrayval;
3746 ArrayType *newarrayval;
3749 * Target is an element of an array
3751 * To handle constructs like x[1][2] := something, we have to
3752 * be prepared to deal with a chain of arrayelem datums. Chase
3753 * back to find the base array datum, and save the subscript
3754 * expressions as we go. (We are scanning right to left here,
3755 * but want to evaluate the subscripts left-to-right to
3756 * minimize surprises.)
3761 PLpgSQL_arrayelem *arrayelem = (PLpgSQL_arrayelem *) target;
3763 if (nsubscripts >= MAXDIM)
3765 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
3766 errmsg("number of array dimensions (%d) exceeds the maximum allowed (%d)",
3767 nsubscripts, MAXDIM)));
3768 subscripts[nsubscripts++] = arrayelem->subscript;
3769 target = estate->datums[arrayelem->arrayparentno];
3770 } while (target->dtype == PLPGSQL_DTYPE_ARRAYELEM);
3772 /* Fetch current value of array datum */
3773 exec_eval_datum(estate, target,
3774 &arraytypeid, &oldarraydatum, &oldarrayisnull);
3776 arrayelemtypeid = get_element_type(arraytypeid);
3777 if (!OidIsValid(arrayelemtypeid))
3779 (errcode(ERRCODE_DATATYPE_MISMATCH),
3780 errmsg("subscripted object is not an array")));
3782 get_typlenbyvalalign(arrayelemtypeid,
3786 arraytyplen = get_typlen(arraytypeid);
3789 * Evaluate the subscripts, switch into left-to-right order.
3790 * Like ExecEvalArrayRef(), complain if any subscript is null.
3792 for (i = 0; i < nsubscripts; i++)
3797 exec_eval_integer(estate,
3798 subscripts[nsubscripts - 1 - i],
3802 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3803 errmsg("array subscript in assignment must not be null")));
3806 /* Coerce source value to match array element type. */
3807 coerced_value = exec_simple_cast_value(value,
3814 * If the original array is null, cons up an empty array so
3815 * that the assignment can proceed; we'll end with a
3816 * one-element array containing just the assigned-to
3817 * subscript. This only works for varlena arrays, though; for
3818 * fixed-length array types we skip the assignment. We can't
3819 * support assignment of a null entry into a fixed-length
3820 * array, either, so that's a no-op too. This is all ugly but
3821 * corresponds to the current behavior of ExecEvalArrayRef().
3823 if (arraytyplen > 0 && /* fixed-length array? */
3824 (oldarrayisnull || *isNull))
3828 oldarrayval = construct_empty_array(arrayelemtypeid);
3830 oldarrayval = (ArrayType *) DatumGetPointer(oldarraydatum);
3833 * Build the modified array value.
3835 newarrayval = array_set(oldarrayval,
3846 * Avoid leaking the result of exec_simple_cast_value, if it
3847 * performed a conversion to a pass-by-ref type.
3849 if (!*isNull && coerced_value != value && !elemtypbyval)
3850 pfree(DatumGetPointer(coerced_value));
3853 * Assign the new array to the base variable. It's never NULL
3857 exec_assign_value(estate, target,
3858 PointerGetDatum(newarrayval),
3859 arraytypeid, isNull);
3862 * Avoid leaking the modified array value, too.
3869 elog(ERROR, "unrecognized dtype: %d", target->dtype);
3874 * exec_eval_datum Get current value of a PLpgSQL_datum
3876 * The type oid, value in Datum format, and null flag are returned.
3878 * At present this doesn't handle PLpgSQL_expr or PLpgSQL_arrayelem datums.
3880 * NOTE: caller must not modify the returned value, since it points right
3881 * at the stored value in the case of pass-by-reference datatypes. In some
3882 * cases we have to palloc a return value, and in such cases we put it into
3883 * the estate's short-term memory context.
3886 exec_eval_datum(PLpgSQL_execstate *estate,
3887 PLpgSQL_datum *datum,
3892 MemoryContext oldcontext;
3894 switch (datum->dtype)
3896 case PLPGSQL_DTYPE_VAR:
3898 PLpgSQL_var *var = (PLpgSQL_var *) datum;
3900 *typeid = var->datatype->typoid;
3901 *value = var->value;
3902 *isnull = var->isnull;
3906 case PLPGSQL_DTYPE_ROW:
3908 PLpgSQL_row *row = (PLpgSQL_row *) datum;
3911 if (!row->rowtupdesc) /* should not happen */
3912 elog(ERROR, "row variable has no tupdesc");
3913 /* Make sure we have a valid type/typmod setting */
3914 BlessTupleDesc(row->rowtupdesc);
3915 oldcontext = MemoryContextSwitchTo(estate->eval_econtext->ecxt_per_tuple_memory);
3916 tup = make_tuple_from_row(estate, row, row->rowtupdesc);
3917 if (tup == NULL) /* should not happen */
3918 elog(ERROR, "row not compatible with its own tupdesc");
3919 MemoryContextSwitchTo(oldcontext);
3920 *typeid = row->rowtupdesc->tdtypeid;
3921 *value = HeapTupleGetDatum(tup);
3926 case PLPGSQL_DTYPE_REC:
3928 PLpgSQL_rec *rec = (PLpgSQL_rec *) datum;
3929 HeapTupleData worktup;
3931 if (!HeapTupleIsValid(rec->tup))
3933 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3934 errmsg("record \"%s\" is not assigned yet",
3936 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
3937 Assert(rec->tupdesc != NULL);
3938 /* Make sure we have a valid type/typmod setting */
3939 BlessTupleDesc(rec->tupdesc);
3942 * In a trigger, the NEW and OLD parameters are likely to be
3943 * on-disk tuples that don't have the desired Datum fields.
3944 * Copy the tuple body and insert the right values.
3946 oldcontext = MemoryContextSwitchTo(estate->eval_econtext->ecxt_per_tuple_memory);
3947 heap_copytuple_with_tuple(rec->tup, &worktup);
3948 HeapTupleHeaderSetDatumLength(worktup.t_data, worktup.t_len);
3949 HeapTupleHeaderSetTypeId(worktup.t_data, rec->tupdesc->tdtypeid);
3950 HeapTupleHeaderSetTypMod(worktup.t_data, rec->tupdesc->tdtypmod);
3951 MemoryContextSwitchTo(oldcontext);
3952 *typeid = rec->tupdesc->tdtypeid;
3953 *value = HeapTupleGetDatum(&worktup);
3958 case PLPGSQL_DTYPE_RECFIELD:
3960 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) datum;
3964 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
3965 if (!HeapTupleIsValid(rec->tup))
3967 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3968 errmsg("record \"%s\" is not assigned yet",
3970 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
3971 fno = SPI_fnumber(rec->tupdesc, recfield->fieldname);
3972 if (fno == SPI_ERROR_NOATTRIBUTE)
3974 (errcode(ERRCODE_UNDEFINED_COLUMN),
3975 errmsg("record \"%s\" has no field \"%s\"",
3976 rec->refname, recfield->fieldname)));
3977 *typeid = SPI_gettypeid(rec->tupdesc, fno);
3978 *value = SPI_getbinval(rec->tup, rec->tupdesc, fno, isnull);
3983 elog(ERROR, "unrecognized dtype: %d", datum->dtype);
3988 * exec_get_datum_type Get datatype of a PLpgSQL_datum
3990 * This is the same logic as in exec_eval_datum, except that it can handle
3991 * some cases where exec_eval_datum has to fail; specifically, we may have
3992 * a tupdesc but no row value for a record variable. (This currently can
3993 * happen only for a trigger's NEW/OLD records.)
3996 exec_get_datum_type(PLpgSQL_execstate *estate,
3997 PLpgSQL_datum *datum)
4001 switch (datum->dtype)
4003 case PLPGSQL_DTYPE_VAR:
4005 PLpgSQL_var *var = (PLpgSQL_var *) datum;
4007 typeid = var->datatype->typoid;
4011 case PLPGSQL_DTYPE_ROW:
4013 PLpgSQL_row *row = (PLpgSQL_row *) datum;
4015 if (!row->rowtupdesc) /* should not happen */
4016 elog(ERROR, "row variable has no tupdesc");
4017 /* Make sure we have a valid type/typmod setting */
4018 BlessTupleDesc(row->rowtupdesc);
4019 typeid = row->rowtupdesc->tdtypeid;
4023 case PLPGSQL_DTYPE_REC:
4025 PLpgSQL_rec *rec = (PLpgSQL_rec *) datum;
4027 if (rec->tupdesc == NULL)
4029 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4030 errmsg("record \"%s\" is not assigned yet",
4032 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
4033 /* Make sure we have a valid type/typmod setting */
4034 BlessTupleDesc(rec->tupdesc);
4035 typeid = rec->tupdesc->tdtypeid;
4039 case PLPGSQL_DTYPE_RECFIELD:
4041 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) datum;
4045 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
4046 if (rec->tupdesc == NULL)
4048 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4049 errmsg("record \"%s\" is not assigned yet",
4051 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
4052 fno = SPI_fnumber(rec->tupdesc, recfield->fieldname);
4053 if (fno == SPI_ERROR_NOATTRIBUTE)
4055 (errcode(ERRCODE_UNDEFINED_COLUMN),
4056 errmsg("record \"%s\" has no field \"%s\"",
4057 rec->refname, recfield->fieldname)));
4058 typeid = SPI_gettypeid(rec->tupdesc, fno);
4063 elog(ERROR, "unrecognized dtype: %d", datum->dtype);
4064 typeid = InvalidOid; /* keep compiler quiet */
4072 * exec_eval_integer Evaluate an expression, coerce result to int4
4074 * Note we do not do exec_eval_cleanup here; the caller must do it at
4075 * some later point. (We do this because the caller may be holding the
4076 * results of other, pass-by-reference, expression evaluations, such as
4077 * an array value to be subscripted. Also see notes in exec_eval_simple_expr
4078 * about allocation of the parameter array.)
4082 exec_eval_integer(PLpgSQL_execstate *estate,
4089 exprdatum = exec_eval_expr(estate, expr, isNull, &exprtypeid);
4090 exprdatum = exec_simple_cast_value(exprdatum, exprtypeid,
4093 return DatumGetInt32(exprdatum);
4097 * exec_eval_boolean Evaluate an expression, coerce result to bool
4099 * Note we do not do exec_eval_cleanup here; the caller must do it at
4104 exec_eval_boolean(PLpgSQL_execstate *estate,
4111 exprdatum = exec_eval_expr(estate, expr, isNull, &exprtypeid);
4112 exprdatum = exec_simple_cast_value(exprdatum, exprtypeid,
4115 return DatumGetBool(exprdatum);
4119 * exec_eval_expr Evaluate an expression and return
4122 * NOTE: caller must do exec_eval_cleanup when done with the Datum.
4126 exec_eval_expr(PLpgSQL_execstate *estate,
4135 * If first time through, create a plan for this expression.
4137 if (expr->plan == NULL)
4138 exec_prepare_plan(estate, expr, 0);
4141 * If this is a simple expression, bypass SPI and use the executor
4144 if (exec_eval_simple_expr(estate, expr, &result, isNull, rettype))
4148 * Else do it the hard way via exec_run_select
4150 rc = exec_run_select(estate, expr, 2, NULL);
4151 if (rc != SPI_OK_SELECT)
4153 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
4154 errmsg("query \"%s\" did not return data", expr->query)));
4157 * If there are no rows selected, the result is NULL.
4159 if (estate->eval_processed == 0)
4166 * Check that the expression returned one single Datum
4168 if (estate->eval_processed > 1)
4170 (errcode(ERRCODE_CARDINALITY_VIOLATION),
4171 errmsg("query \"%s\" returned more than one row",
4173 if (estate->eval_tuptable->tupdesc->natts != 1)
4175 (errcode(ERRCODE_SYNTAX_ERROR),
4176 errmsg_plural("query \"%s\" returned %d column",
4177 "query \"%s\" returned %d columns",
4178 estate->eval_tuptable->tupdesc->natts,
4180 estate->eval_tuptable->tupdesc->natts)));
4183 * Return the result and its type
4185 *rettype = SPI_gettypeid(estate->eval_tuptable->tupdesc, 1);
4186 return SPI_getbinval(estate->eval_tuptable->vals[0],
4187 estate->eval_tuptable->tupdesc, 1, isNull);
4192 * exec_run_select Execute a select query
4196 exec_run_select(PLpgSQL_execstate *estate,
4197 PLpgSQL_expr *expr, long maxtuples, Portal *portalP)
4199 ParamListInfo paramLI;
4203 * On the first call for this expression generate the plan
4205 if (expr->plan == NULL)
4206 exec_prepare_plan(estate, expr, 0);
4209 * Set up ParamListInfo (note this is only carrying a hook function,
4210 * not any actual data values, at this point)
4212 paramLI = setup_param_list(estate, expr);
4215 * If a portal was requested, put the query into the portal
4217 if (portalP != NULL)
4219 *portalP = SPI_cursor_open_with_paramlist(NULL, expr->plan,
4221 estate->readonly_func);
4222 if (*portalP == NULL)
4223 elog(ERROR, "could not open implicit cursor for query \"%s\": %s",
4224 expr->query, SPI_result_code_string(SPI_result));
4227 return SPI_OK_CURSOR;
4233 rc = SPI_execute_plan_with_paramlist(expr->plan, paramLI,
4234 estate->readonly_func, maxtuples);
4235 if (rc != SPI_OK_SELECT)
4237 (errcode(ERRCODE_SYNTAX_ERROR),
4238 errmsg("query \"%s\" is not a SELECT", expr->query)));
4240 /* Save query results for eventual cleanup */
4241 Assert(estate->eval_tuptable == NULL);
4242 estate->eval_tuptable = SPI_tuptable;
4243 estate->eval_processed = SPI_processed;
4244 estate->eval_lastoid = SPI_lastoid;
4254 * exec_for_query --- execute body of FOR loop for each row from a portal
4256 * Used by exec_stmt_fors, exec_stmt_forc and exec_stmt_dynfors
4259 exec_for_query(PLpgSQL_execstate *estate, PLpgSQL_stmt_forq *stmt,
4260 Portal portal, bool prefetch_ok)
4262 PLpgSQL_rec *rec = NULL;
4263 PLpgSQL_row *row = NULL;
4264 SPITupleTable *tuptab;
4266 int rc = PLPGSQL_RC_OK;
4270 * Determine if we assign to a record or a row
4272 if (stmt->rec != NULL)
4273 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->dno]);
4274 else if (stmt->row != NULL)
4275 row = (PLpgSQL_row *) (estate->datums[stmt->row->dno]);
4277 elog(ERROR, "unsupported target");
4280 * Fetch the initial tuple(s). If prefetching is allowed then we grab a
4281 * few more rows to avoid multiple trips through executor startup
4284 SPI_cursor_fetch(portal, true, prefetch_ok ? 10 : 1);
4285 tuptab = SPI_tuptable;
4289 * If the query didn't return any rows, set the target to NULL and fall
4290 * through with found = false.
4293 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
4295 found = true; /* processed at least one tuple */
4304 for (i = 0; i < n; i++)
4307 * Assign the tuple to the target
4309 exec_move_row(estate, rec, row, tuptab->vals[i], tuptab->tupdesc);
4312 * Execute the statements
4314 rc = exec_stmts(estate, stmt->body);
4316 if (rc != PLPGSQL_RC_OK)
4318 if (rc == PLPGSQL_RC_EXIT)
4320 if (estate->exitlabel == NULL)
4322 /* unlabelled exit, so exit the current loop */
4325 else if (stmt->label != NULL &&
4326 strcmp(stmt->label, estate->exitlabel) == 0)
4328 /* label matches this loop, so exit loop */
4329 estate->exitlabel = NULL;
4334 * otherwise, we processed a labelled exit that does not
4335 * match the current statement's label, if any; return
4336 * RC_EXIT so that the EXIT continues to recurse upward.
4339 else if (rc == PLPGSQL_RC_CONTINUE)
4341 if (estate->exitlabel == NULL)
4343 /* unlabelled continue, so re-run the current loop */
4347 else if (stmt->label != NULL &&
4348 strcmp(stmt->label, estate->exitlabel) == 0)
4350 /* label matches this loop, so re-run loop */
4351 estate->exitlabel = NULL;
4357 * otherwise, we process a labelled continue that does not
4358 * match the current statement's label, if any; return
4359 * RC_CONTINUE so that the CONTINUE will propagate up the
4365 * We're aborting the loop. Need a goto to get out of two
4372 SPI_freetuptable(tuptab);
4375 * Fetch more tuples. If prefetching is allowed, grab 50 at a time.
4377 SPI_cursor_fetch(portal, true, prefetch_ok ? 50 : 1);
4378 tuptab = SPI_tuptable;
4385 * Release last group of tuples (if any)
4387 SPI_freetuptable(tuptab);
4390 * Set the FOUND variable to indicate the result of executing the loop
4391 * (namely, whether we looped one or more times). This must be set last so
4392 * that it does not interfere with the value of the FOUND variable inside
4393 * the loop processing itself.
4395 exec_set_found(estate, found);
4402 * exec_eval_simple_expr - Evaluate a simple expression returning
4403 * a Datum by directly calling ExecEvalExpr().
4405 * If successful, store results into *result, *isNull, *rettype and return
4406 * TRUE. If the expression is not simple (any more), return FALSE.
4408 * It is possible though unlikely for a simple expression to become non-simple
4409 * (consider for example redefining a trivial view). We must handle that for
4410 * correctness; fortunately it's normally inexpensive to do
4411 * RevalidateCachedPlan on a simple expression. We do not consider the other
4412 * direction (non-simple expression becoming simple) because we'll still give
4413 * correct results if that happens, and it's unlikely to be worth the cycles
4416 * Note: if pass-by-reference, the result is in the eval_econtext's
4417 * temporary memory context. It will be freed when exec_eval_cleanup
4422 exec_eval_simple_expr(PLpgSQL_execstate *estate,
4428 ExprContext *econtext = estate->eval_econtext;
4429 LocalTransactionId curlxid = MyProc->lxid;
4430 CachedPlanSource *plansource;
4432 ParamListInfo paramLI;
4433 PLpgSQL_expr *save_cur_expr;
4434 MemoryContext oldcontext;
4437 * Forget it if expression wasn't simple before.
4439 if (expr->expr_simple_expr == NULL)
4443 * Revalidate cached plan, so that we will notice if it became stale. (We
4444 * also need to hold a refcount while using the plan.) Note that even if
4445 * replanning occurs, the length of plancache_list can't change, since it
4446 * is a property of the raw parsetree generated from the query text.
4448 Assert(list_length(expr->plan->plancache_list) == 1);
4449 plansource = (CachedPlanSource *) linitial(expr->plan->plancache_list);
4450 cplan = RevalidateCachedPlan(plansource, true);
4451 if (cplan->generation != expr->expr_simple_generation)
4453 /* It got replanned ... is it still simple? */
4454 exec_simple_check_plan(expr);
4455 if (expr->expr_simple_expr == NULL)
4457 /* Ooops, release refcount and fail */
4458 ReleaseCachedPlan(cplan, true);
4464 * Pass back previously-determined result type.
4466 *rettype = expr->expr_simple_type;
4469 * Prepare the expression for execution, if it's not been done already in
4470 * the current transaction. (This will be forced to happen if we called
4471 * exec_simple_check_plan above.)
4473 if (expr->expr_simple_lxid != curlxid)
4475 expr->expr_simple_state = ExecPrepareExpr(expr->expr_simple_expr,
4476 simple_eval_estate);
4477 expr->expr_simple_lxid = curlxid;
4481 * We have to do some of the things SPI_execute_plan would do, in
4482 * particular advance the snapshot if we are in a non-read-only function.
4483 * Without this, stable functions within the expression would fail to see
4484 * updates made so far by our own function.
4488 oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
4489 if (!estate->readonly_func)
4491 CommandCounterIncrement();
4492 PushActiveSnapshot(GetTransactionSnapshot());
4496 * Create the param list in econtext's temporary memory context.
4497 * We won't need to free it explicitly, since it will go away at the
4498 * next reset of that context.
4500 * XXX think about avoiding repeated palloc's for param lists? It should
4501 * be possible --- this routine isn't re-entrant anymore.
4503 * Just for paranoia's sake, save and restore the prior value of
4504 * estate->cur_expr, which setup_param_list() sets.
4506 save_cur_expr = estate->cur_expr;
4508 paramLI = setup_param_list(estate, expr);
4509 econtext->ecxt_param_list_info = paramLI;
4512 * Finally we can call the executor to evaluate the expression
4514 *result = ExecEvalExpr(expr->expr_simple_state,
4519 /* Assorted cleanup */
4520 estate->cur_expr = save_cur_expr;
4522 if (!estate->readonly_func)
4523 PopActiveSnapshot();
4525 MemoryContextSwitchTo(oldcontext);
4530 * Now we can release our refcount on the cached plan.
4532 ReleaseCachedPlan(cplan, true);
4542 * Create a ParamListInfo to pass to SPI
4544 * The ParamListInfo array is initially all zeroes, in particular the
4545 * ptype values are all InvalidOid. This causes the executor to call the
4546 * paramFetch hook each time it wants a value. We thus evaluate only the
4547 * parameters actually demanded.
4549 * The result is a locally palloc'd array that should be pfree'd after use;
4550 * but note it can be NULL.
4552 static ParamListInfo
4553 setup_param_list(PLpgSQL_execstate *estate, PLpgSQL_expr *expr)
4555 ParamListInfo paramLI;
4558 * Could we re-use these arrays instead of palloc'ing a new one each
4559 * time? However, we'd have to zero the array each time anyway,
4560 * since new values might have been assigned to the variables.
4562 if (estate->ndatums > 0)
4564 /* sizeof(ParamListInfoData) includes the first array element */
4565 paramLI = (ParamListInfo)
4566 palloc0(sizeof(ParamListInfoData) +
4567 (estate->ndatums - 1) * sizeof(ParamExternData));
4568 paramLI->paramFetch = plpgsql_param_fetch;
4569 paramLI->paramFetchArg = (void *) estate;
4570 paramLI->parserSetup = (ParserSetupHook) plpgsql_parser_setup;
4571 paramLI->parserSetupArg = (void *) expr;
4572 paramLI->numParams = estate->ndatums;
4575 * Set up link to active expr where the hook functions can find it.
4576 * Callers must save and restore cur_expr if there is any chance
4577 * that they are interrupting an active use of parameters.
4579 estate->cur_expr = expr;
4582 * Also make sure this is set before parser hooks need it. There
4583 * is no need to save and restore, since the value is always correct
4586 expr->func = estate->func;
4594 * plpgsql_parser_setup set up parser hooks for dynamic parameters
4597 plpgsql_parser_setup(ParseState *pstate, PLpgSQL_expr *expr)
4599 pstate->p_ref_hook_state = (void *) expr;
4600 pstate->p_paramref_hook = plpgsql_param_ref;
4601 /* no need to use p_coerce_param_hook */
4605 * plpgsql_param_ref parser callback for ParamRefs ($n symbols)
4608 plpgsql_param_ref(ParseState *pstate, ParamRef *pref)
4610 int paramno = pref->number;
4611 PLpgSQL_expr *expr = (PLpgSQL_expr *) pstate->p_ref_hook_state;
4612 PLpgSQL_execstate *estate;
4615 /* Let's just check parameter number is in range */
4616 if (!bms_is_member(paramno-1, expr->paramnos))
4620 * We use the function's current estate to resolve parameter data types.
4621 * This is really pretty bogus because there is no provision for updating
4622 * plans when those types change ...
4624 estate = expr->func->cur_estate;
4625 Assert(paramno <= estate->ndatums);
4627 param = makeNode(Param);
4628 param->paramkind = PARAM_EXTERN;
4629 param->paramid = paramno;
4630 param->paramtype = exec_get_datum_type(estate,
4631 estate->datums[paramno-1]);
4632 param->paramtypmod = -1;
4633 param->location = pref->location;
4635 return (Node *) param;
4639 * plpgsql_param_fetch paramFetch callback for dynamic parameter fetch
4642 plpgsql_param_fetch(ParamListInfo params, int paramid)
4645 PLpgSQL_execstate *estate;
4647 PLpgSQL_datum *datum;
4648 ParamExternData *prm;
4650 /* paramid's are 1-based, but dnos are 0-based */
4652 Assert(dno >= 0 && dno < params->numParams);
4654 /* fetch back the hook data */
4655 estate = (PLpgSQL_execstate *) params->paramFetchArg;
4656 expr = estate->cur_expr;
4657 Assert(params->numParams == estate->ndatums);
4660 * Do nothing if asked for a value that's not supposed to be used by
4661 * this SQL expression. This avoids unwanted evaluations when functions
4662 * such as copyParamList try to materialize all the values.
4664 if (!bms_is_member(dno, expr->paramnos))
4667 /* OK, evaluate the value and store into the appropriate paramlist slot */
4668 datum = estate->datums[dno];
4669 prm = ¶ms->params[dno];
4670 exec_eval_datum(estate, datum,
4671 &prm->ptype, &prm->value, &prm->isnull);
4676 * exec_move_row Move one tuple's values into a record or row
4680 exec_move_row(PLpgSQL_execstate *estate,
4683 HeapTuple tup, TupleDesc tupdesc)
4686 * Record is simple - just copy the tuple and its descriptor into the
4692 * Copy input first, just in case it is pointing at variable's value
4694 if (HeapTupleIsValid(tup))
4695 tup = heap_copytuple(tup);
4698 /* If we have a tupdesc but no data, form an all-nulls tuple */
4701 nulls = (bool *) palloc(tupdesc->natts * sizeof(bool));
4702 memset(nulls, true, tupdesc->natts * sizeof(bool));
4704 tup = heap_form_tuple(tupdesc, NULL, nulls);
4710 tupdesc = CreateTupleDescCopy(tupdesc);
4712 /* Free the old value ... */
4715 heap_freetuple(rec->tup);
4716 rec->freetup = false;
4718 if (rec->freetupdesc)
4720 FreeTupleDesc(rec->tupdesc);
4721 rec->freetupdesc = false;
4724 /* ... and install the new */
4725 if (HeapTupleIsValid(tup))
4728 rec->freetup = true;
4735 rec->tupdesc = tupdesc;
4736 rec->freetupdesc = true;
4739 rec->tupdesc = NULL;
4745 * Row is a bit more complicated in that we assign the individual
4746 * attributes of the tuple to the variables the row points to.
4748 * NOTE: this code used to demand row->nfields ==
4749 * HeapTupleHeaderGetNatts(tup->t_data), but that's wrong. The tuple
4750 * might have more fields than we expected if it's from an
4751 * inheritance-child table of the current table, or it might have fewer if
4752 * the table has had columns added by ALTER TABLE. Ignore extra columns
4753 * and assume NULL for missing columns, the same as heap_getattr would do.
4754 * We also have to skip over dropped columns in either the source or
4757 * If we have no tuple data at all, we'll assign NULL to all columns of
4762 int td_natts = tupdesc ? tupdesc->natts : 0;
4767 if (HeapTupleIsValid(tup))
4768 t_natts = HeapTupleHeaderGetNatts(tup->t_data);
4773 for (fnum = 0; fnum < row->nfields; fnum++)
4780 if (row->varnos[fnum] < 0)
4781 continue; /* skip dropped column in row struct */
4783 var = (PLpgSQL_var *) (estate->datums[row->varnos[fnum]]);
4785 while (anum < td_natts && tupdesc->attrs[anum]->attisdropped)
4786 anum++; /* skip dropped column in tuple */
4788 if (anum < td_natts)
4791 value = SPI_getbinval(tup, tupdesc, anum + 1, &isnull);
4797 valtype = SPI_gettypeid(tupdesc, anum + 1);
4804 valtype = InvalidOid;
4807 exec_assign_value(estate, (PLpgSQL_datum *) var,
4808 value, valtype, &isnull);
4814 elog(ERROR, "unsupported target");
4818 * make_tuple_from_row Make a tuple from the values of a row object
4820 * A NULL return indicates rowtype mismatch; caller must raise suitable error
4824 make_tuple_from_row(PLpgSQL_execstate *estate,
4828 int natts = tupdesc->natts;
4834 if (natts != row->nfields)
4837 dvalues = (Datum *) palloc0(natts * sizeof(Datum));
4838 nulls = (bool *) palloc(natts * sizeof(bool));
4840 for (i = 0; i < natts; i++)
4844 if (tupdesc->attrs[i]->attisdropped)
4846 nulls[i] = true; /* leave the column as null */
4849 if (row->varnos[i] < 0) /* should not happen */
4850 elog(ERROR, "dropped rowtype entry for non-dropped column");
4852 exec_eval_datum(estate, estate->datums[row->varnos[i]],
4853 &fieldtypeid, &dvalues[i], &nulls[i]);
4854 if (fieldtypeid != tupdesc->attrs[i]->atttypid)
4858 tuple = heap_form_tuple(tupdesc, dvalues, nulls);
4867 * convert_value_to_string Convert a non-null Datum to C string
4869 * Note: callers generally assume that the result is a palloc'd string and
4870 * should be pfree'd. This is not all that safe an assumption ...
4872 * Note: not caching the conversion function lookup is bad for performance.
4876 convert_value_to_string(Datum value, Oid valtype)
4881 getTypeOutputInfo(valtype, &typoutput, &typIsVarlena);
4882 return OidOutputFunctionCall(typoutput, value);
4886 * exec_cast_value Cast a value if required
4890 exec_cast_value(Datum value, Oid valtype,
4898 * If the type of the queries return value isn't that of the variable,
4901 if (valtype != reqtype || reqtypmod != -1)
4907 extval = convert_value_to_string(value, valtype);
4908 value = InputFunctionCall(reqinput, extval,
4909 reqtypioparam, reqtypmod);
4914 value = InputFunctionCall(reqinput, NULL,
4915 reqtypioparam, reqtypmod);
4923 * exec_simple_cast_value Cast a value if required
4925 * As above, but need not supply details about target type. Note that this
4926 * is slower than exec_cast_value with cached type info, and so should be
4927 * avoided in heavily used code paths.
4931 exec_simple_cast_value(Datum value, Oid valtype,
4932 Oid reqtype, int32 reqtypmod,
4935 if (valtype != reqtype || reqtypmod != -1)
4939 FmgrInfo finfo_input;
4941 getTypeInputInfo(reqtype, &typinput, &typioparam);
4943 fmgr_info(typinput, &finfo_input);
4945 value = exec_cast_value(value,
4959 * exec_simple_check_node - Recursively check if an expression
4960 * is made only of simple things we can
4961 * hand out directly to ExecEvalExpr()
4962 * instead of calling SPI.
4966 exec_simple_check_node(Node *node)
4971 switch (nodeTag(node))
4981 ArrayRef *expr = (ArrayRef *) node;
4983 if (!exec_simple_check_node((Node *) expr->refupperindexpr))
4985 if (!exec_simple_check_node((Node *) expr->reflowerindexpr))
4987 if (!exec_simple_check_node((Node *) expr->refexpr))
4989 if (!exec_simple_check_node((Node *) expr->refassgnexpr))
4997 FuncExpr *expr = (FuncExpr *) node;
4999 if (expr->funcretset)
5001 if (!exec_simple_check_node((Node *) expr->args))
5009 OpExpr *expr = (OpExpr *) node;
5013 if (!exec_simple_check_node((Node *) expr->args))
5019 case T_DistinctExpr:
5021 DistinctExpr *expr = (DistinctExpr *) node;
5025 if (!exec_simple_check_node((Node *) expr->args))
5031 case T_ScalarArrayOpExpr:
5033 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
5035 if (!exec_simple_check_node((Node *) expr->args))
5043 BoolExpr *expr = (BoolExpr *) node;
5045 if (!exec_simple_check_node((Node *) expr->args))
5052 return exec_simple_check_node((Node *) ((FieldSelect *) node)->arg);
5056 FieldStore *expr = (FieldStore *) node;
5058 if (!exec_simple_check_node((Node *) expr->arg))
5060 if (!exec_simple_check_node((Node *) expr->newvals))
5067 return exec_simple_check_node((Node *) ((RelabelType *) node)->arg);
5070 return exec_simple_check_node((Node *) ((CoerceViaIO *) node)->arg);
5072 case T_ArrayCoerceExpr:
5073 return exec_simple_check_node((Node *) ((ArrayCoerceExpr *) node)->arg);
5075 case T_ConvertRowtypeExpr:
5076 return exec_simple_check_node((Node *) ((ConvertRowtypeExpr *) node)->arg);
5080 CaseExpr *expr = (CaseExpr *) node;
5082 if (!exec_simple_check_node((Node *) expr->arg))
5084 if (!exec_simple_check_node((Node *) expr->args))
5086 if (!exec_simple_check_node((Node *) expr->defresult))
5094 CaseWhen *when = (CaseWhen *) node;
5096 if (!exec_simple_check_node((Node *) when->expr))
5098 if (!exec_simple_check_node((Node *) when->result))
5104 case T_CaseTestExpr:
5109 ArrayExpr *expr = (ArrayExpr *) node;
5111 if (!exec_simple_check_node((Node *) expr->elements))
5119 RowExpr *expr = (RowExpr *) node;
5121 if (!exec_simple_check_node((Node *) expr->args))
5127 case T_RowCompareExpr:
5129 RowCompareExpr *expr = (RowCompareExpr *) node;
5131 if (!exec_simple_check_node((Node *) expr->largs))
5133 if (!exec_simple_check_node((Node *) expr->rargs))
5139 case T_CoalesceExpr:
5141 CoalesceExpr *expr = (CoalesceExpr *) node;
5143 if (!exec_simple_check_node((Node *) expr->args))
5151 MinMaxExpr *expr = (MinMaxExpr *) node;
5153 if (!exec_simple_check_node((Node *) expr->args))
5161 XmlExpr *expr = (XmlExpr *) node;
5163 if (!exec_simple_check_node((Node *) expr->named_args))
5165 if (!exec_simple_check_node((Node *) expr->args))
5173 NullIfExpr *expr = (NullIfExpr *) node;
5177 if (!exec_simple_check_node((Node *) expr->args))
5184 return exec_simple_check_node((Node *) ((NullTest *) node)->arg);
5187 return exec_simple_check_node((Node *) ((BooleanTest *) node)->arg);
5189 case T_CoerceToDomain:
5190 return exec_simple_check_node((Node *) ((CoerceToDomain *) node)->arg);
5192 case T_CoerceToDomainValue:
5197 List *expr = (List *) node;
5202 if (!exec_simple_check_node(lfirst(l)))
5216 * exec_simple_check_plan - Check if a plan is simple enough to
5217 * be evaluated by ExecEvalExpr() instead
5222 exec_simple_check_plan(PLpgSQL_expr *expr)
5224 CachedPlanSource *plansource;
5230 * Initialize to "not simple", and remember the plan generation number we
5231 * last checked. (If the query produces more or less than one parsetree
5232 * we just leave expr_simple_generation set to 0.)
5234 expr->expr_simple_expr = NULL;
5235 expr->expr_simple_generation = 0;
5238 * 1. We can only evaluate queries that resulted in one single execution
5241 if (list_length(expr->plan->plancache_list) != 1)
5243 plansource = (CachedPlanSource *) linitial(expr->plan->plancache_list);
5244 expr->expr_simple_generation = plansource->generation;
5245 if (list_length(plansource->plan->stmt_list) != 1)
5248 stmt = (PlannedStmt *) linitial(plansource->plan->stmt_list);
5251 * 2. It must be a RESULT plan --> no scan's required
5253 if (!IsA(stmt, PlannedStmt))
5255 plan = stmt->planTree;
5256 if (!IsA(plan, Result))
5260 * 3. Can't have any subplan or qual clause, either
5262 if (plan->lefttree != NULL ||
5263 plan->righttree != NULL ||
5264 plan->initPlan != NULL ||
5265 plan->qual != NULL ||
5266 ((Result *) plan)->resconstantqual != NULL)
5270 * 4. The plan must have a single attribute as result
5272 if (list_length(plan->targetlist) != 1)
5275 tle = (TargetEntry *) linitial(plan->targetlist);
5278 * 5. Check that all the nodes in the expression are non-scary.
5280 if (!exec_simple_check_node((Node *) tle->expr))
5284 * Yes - this is a simple expression. Mark it as such, and initialize
5285 * state to "not valid in current transaction".
5287 expr->expr_simple_expr = tle->expr;
5288 expr->expr_simple_state = NULL;
5289 expr->expr_simple_lxid = InvalidLocalTransactionId;
5290 /* Also stash away the expression result type */
5291 expr->expr_simple_type = exprType((Node *) tle->expr);
5295 * exec_set_found Set the global found variable
5300 exec_set_found(PLpgSQL_execstate *estate, bool state)
5304 var = (PLpgSQL_var *) (estate->datums[estate->found_varno]);
5305 var->value = PointerGetDatum(state);
5306 var->isnull = false;
5310 * plpgsql_create_econtext --- create an eval_econtext for the current function
5312 * We may need to create a new simple_eval_estate too, if there's not one
5313 * already for the current transaction. The EState will be cleaned up at
5317 plpgsql_create_econtext(PLpgSQL_execstate *estate)
5319 SimpleEcontextStackEntry *entry;
5322 * Create an EState for evaluation of simple expressions, if there's not
5323 * one already in the current transaction. The EState is made a child of
5324 * TopTransactionContext so it will have the right lifespan.
5326 if (simple_eval_estate == NULL)
5328 MemoryContext oldcontext;
5330 oldcontext = MemoryContextSwitchTo(TopTransactionContext);
5331 simple_eval_estate = CreateExecutorState();
5332 MemoryContextSwitchTo(oldcontext);
5336 * Create a child econtext for the current function.
5338 estate->eval_econtext = CreateExprContext(simple_eval_estate);
5341 * Make a stack entry so we can clean up the econtext at subxact end.
5342 * Stack entries are kept in TopTransactionContext for simplicity.
5344 entry = (SimpleEcontextStackEntry *)
5345 MemoryContextAlloc(TopTransactionContext,
5346 sizeof(SimpleEcontextStackEntry));
5348 entry->stack_econtext = estate->eval_econtext;
5349 entry->xact_subxid = GetCurrentSubTransactionId();
5351 entry->next = simple_econtext_stack;
5352 simple_econtext_stack = entry;
5356 * plpgsql_destroy_econtext --- destroy function's econtext
5358 * We check that it matches the top stack entry, and destroy the stack
5359 * entry along with the context.
5362 plpgsql_destroy_econtext(PLpgSQL_execstate *estate)
5364 SimpleEcontextStackEntry *next;
5366 Assert(simple_econtext_stack != NULL);
5367 Assert(simple_econtext_stack->stack_econtext == estate->eval_econtext);
5369 next = simple_econtext_stack->next;
5370 pfree(simple_econtext_stack);
5371 simple_econtext_stack = next;
5373 FreeExprContext(estate->eval_econtext, true);
5374 estate->eval_econtext = NULL;
5378 * plpgsql_xact_cb --- post-transaction-commit-or-abort cleanup
5380 * If a simple-expression EState was created in the current transaction,
5381 * it has to be cleaned up.
5384 plpgsql_xact_cb(XactEvent event, void *arg)
5387 * If we are doing a clean transaction shutdown, free the EState (so that
5388 * any remaining resources will be released correctly). In an abort, we
5389 * expect the regular abort recovery procedures to release everything of
5392 if (event != XACT_EVENT_ABORT)
5394 /* Shouldn't be any econtext stack entries left at commit */
5395 Assert(simple_econtext_stack == NULL);
5397 if (simple_eval_estate)
5398 FreeExecutorState(simple_eval_estate);
5399 simple_eval_estate = NULL;
5403 simple_econtext_stack = NULL;
5404 simple_eval_estate = NULL;
5409 * plpgsql_subxact_cb --- post-subtransaction-commit-or-abort cleanup
5411 * Make sure any simple-expression econtexts created in the current
5412 * subtransaction get cleaned up. We have to do this explicitly because
5413 * no other code knows which child econtexts of simple_eval_estate belong
5414 * to which level of subxact.
5417 plpgsql_subxact_cb(SubXactEvent event, SubTransactionId mySubid,
5418 SubTransactionId parentSubid, void *arg)
5420 if (event == SUBXACT_EVENT_START_SUB)
5423 while (simple_econtext_stack != NULL &&
5424 simple_econtext_stack->xact_subxid == mySubid)
5426 SimpleEcontextStackEntry *next;
5428 FreeExprContext(simple_econtext_stack->stack_econtext,
5429 (event == SUBXACT_EVENT_COMMIT_SUB));
5430 next = simple_econtext_stack->next;
5431 pfree(simple_econtext_stack);
5432 simple_econtext_stack = next;
5437 * free_var --- pfree any pass-by-reference value of the variable.
5439 * This should always be followed by some assignment to var->value,
5440 * as it leaves a dangling pointer.
5443 free_var(PLpgSQL_var *var)
5447 pfree(DatumGetPointer(var->value));
5448 var->freeval = false;
5453 * free old value of a text variable and assign new value from C string
5456 assign_text_var(PLpgSQL_var *var, const char *str)
5459 var->value = CStringGetTextDatum(str);
5460 var->isnull = false;
5461 var->freeval = true;
5465 * exec_eval_using_params --- evaluate params of USING clause
5467 static PreparedParamsData *
5468 exec_eval_using_params(PLpgSQL_execstate *estate, List *params)
5470 PreparedParamsData *ppd;
5475 ppd = (PreparedParamsData *) palloc(sizeof(PreparedParamsData));
5476 nargs = list_length(params);
5479 ppd->types = (Oid *) palloc(nargs * sizeof(Oid));
5480 ppd->values = (Datum *) palloc(nargs * sizeof(Datum));
5481 ppd->nulls = (char *) palloc(nargs * sizeof(char));
5482 ppd->freevals = (bool *) palloc(nargs * sizeof(bool));
5487 PLpgSQL_expr *param = (PLpgSQL_expr *) lfirst(lc);
5490 ppd->values[i] = exec_eval_expr(estate, param,
5493 ppd->nulls[i] = isnull ? 'n' : ' ';
5494 ppd->freevals[i] = false;
5496 /* pass-by-ref non null values must be copied into plpgsql context */
5502 get_typlenbyval(ppd->types[i], &typLen, &typByVal);
5505 ppd->values[i] = datumCopy(ppd->values[i], typByVal, typLen);
5506 ppd->freevals[i] = true;
5510 exec_eval_cleanup(estate);
5519 * free_params_data --- pfree all pass-by-reference values used in USING clause
5522 free_params_data(PreparedParamsData *ppd)
5526 for (i = 0; i < ppd->nargs; i++)
5528 if (ppd->freevals[i])
5529 pfree(DatumGetPointer(ppd->values[i]));
5535 pfree(ppd->freevals);
5541 * Open portal for dynamic query
5544 exec_dynquery_with_params(PLpgSQL_execstate *estate, PLpgSQL_expr *dynquery,
5554 * Evaluate the string expression after the EXECUTE keyword. Its result is
5555 * the querystring we have to execute.
5557 query = exec_eval_expr(estate, dynquery, &isnull, &restype);
5560 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
5561 errmsg("query string argument of EXECUTE is null")));
5563 /* Get the C-String representation */
5564 querystr = convert_value_to_string(query, restype);
5566 exec_eval_cleanup(estate);
5569 * Open an implicit cursor for the query. We use
5570 * SPI_cursor_open_with_args even when there are no params, because this
5571 * avoids making and freeing one copy of the plan.
5575 PreparedParamsData *ppd;
5577 ppd = exec_eval_using_params(estate, params);
5578 portal = SPI_cursor_open_with_args(NULL,
5580 ppd->nargs, ppd->types,
5581 ppd->values, ppd->nulls,
5582 estate->readonly_func, 0);
5583 free_params_data(ppd);
5587 portal = SPI_cursor_open_with_args(NULL,
5591 estate->readonly_func, 0);
5595 elog(ERROR, "could not open implicit cursor for query \"%s\": %s",
5596 querystr, SPI_result_code_string(SPI_result));