1 /*-------------------------------------------------------------------------
3 * pl_exec.c - Executor for the PL/pgSQL
6 * Portions Copyright (c) 1996-2014, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/pl/plpgsql/src/pl_exec.c
13 *-------------------------------------------------------------------------
20 #include "access/htup_details.h"
21 #include "access/transam.h"
22 #include "access/tupconvert.h"
23 #include "catalog/pg_proc.h"
24 #include "catalog/pg_type.h"
25 #include "executor/spi.h"
27 #include "miscadmin.h"
28 #include "nodes/nodeFuncs.h"
29 #include "parser/scansup.h"
30 #include "storage/proc.h"
31 #include "tcop/tcopprot.h"
32 #include "utils/array.h"
33 #include "utils/builtins.h"
34 #include "utils/datum.h"
35 #include "utils/lsyscache.h"
36 #include "utils/memutils.h"
37 #include "utils/rel.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 * However, there's no value in trying to amortize simple expression setup
71 * across multiple executions of a DO block (inline code block), since there
72 * can never be any. If we use the shared EState for a DO block, the expr
73 * state trees are effectively leaked till end of transaction, and that can
74 * add up if the user keeps on submitting DO blocks. Therefore, each DO block
75 * has its own simple-expression EState, which is cleaned up at exit from
76 * plpgsql_inline_handler(). DO blocks still use the simple_econtext_stack,
77 * though, so that subxact abort cleanup does the right thing.
79 typedef struct SimpleEcontextStackEntry
81 ExprContext *stack_econtext; /* a stacked econtext */
82 SubTransactionId xact_subxid; /* ID for current subxact */
83 struct SimpleEcontextStackEntry *next; /* next stack entry up */
84 } SimpleEcontextStackEntry;
86 static EState *shared_simple_eval_estate = NULL;
87 static SimpleEcontextStackEntry *simple_econtext_stack = NULL;
89 /************************************************************
90 * Local function forward declarations
91 ************************************************************/
92 static void plpgsql_exec_error_callback(void *arg);
93 static PLpgSQL_datum *copy_plpgsql_datum(PLpgSQL_datum *datum);
95 static int exec_stmt_block(PLpgSQL_execstate *estate,
96 PLpgSQL_stmt_block *block);
97 static int exec_stmts(PLpgSQL_execstate *estate,
99 static int exec_stmt(PLpgSQL_execstate *estate,
101 static int exec_stmt_assign(PLpgSQL_execstate *estate,
102 PLpgSQL_stmt_assign *stmt);
103 static int exec_stmt_perform(PLpgSQL_execstate *estate,
104 PLpgSQL_stmt_perform *stmt);
105 static int exec_stmt_getdiag(PLpgSQL_execstate *estate,
106 PLpgSQL_stmt_getdiag *stmt);
107 static int exec_stmt_if(PLpgSQL_execstate *estate,
108 PLpgSQL_stmt_if *stmt);
109 static int exec_stmt_case(PLpgSQL_execstate *estate,
110 PLpgSQL_stmt_case *stmt);
111 static int exec_stmt_loop(PLpgSQL_execstate *estate,
112 PLpgSQL_stmt_loop *stmt);
113 static int exec_stmt_while(PLpgSQL_execstate *estate,
114 PLpgSQL_stmt_while *stmt);
115 static int exec_stmt_fori(PLpgSQL_execstate *estate,
116 PLpgSQL_stmt_fori *stmt);
117 static int exec_stmt_fors(PLpgSQL_execstate *estate,
118 PLpgSQL_stmt_fors *stmt);
119 static int exec_stmt_forc(PLpgSQL_execstate *estate,
120 PLpgSQL_stmt_forc *stmt);
121 static int exec_stmt_foreach_a(PLpgSQL_execstate *estate,
122 PLpgSQL_stmt_foreach_a *stmt);
123 static int exec_stmt_open(PLpgSQL_execstate *estate,
124 PLpgSQL_stmt_open *stmt);
125 static int exec_stmt_fetch(PLpgSQL_execstate *estate,
126 PLpgSQL_stmt_fetch *stmt);
127 static int exec_stmt_close(PLpgSQL_execstate *estate,
128 PLpgSQL_stmt_close *stmt);
129 static int exec_stmt_exit(PLpgSQL_execstate *estate,
130 PLpgSQL_stmt_exit *stmt);
131 static int exec_stmt_return(PLpgSQL_execstate *estate,
132 PLpgSQL_stmt_return *stmt);
133 static int exec_stmt_return_next(PLpgSQL_execstate *estate,
134 PLpgSQL_stmt_return_next *stmt);
135 static int exec_stmt_return_query(PLpgSQL_execstate *estate,
136 PLpgSQL_stmt_return_query *stmt);
137 static int exec_stmt_raise(PLpgSQL_execstate *estate,
138 PLpgSQL_stmt_raise *stmt);
139 static int exec_stmt_execsql(PLpgSQL_execstate *estate,
140 PLpgSQL_stmt_execsql *stmt);
141 static int exec_stmt_dynexecute(PLpgSQL_execstate *estate,
142 PLpgSQL_stmt_dynexecute *stmt);
143 static int exec_stmt_dynfors(PLpgSQL_execstate *estate,
144 PLpgSQL_stmt_dynfors *stmt);
146 static void plpgsql_estate_setup(PLpgSQL_execstate *estate,
147 PLpgSQL_function *func,
149 EState *simple_eval_estate);
150 static void exec_eval_cleanup(PLpgSQL_execstate *estate);
152 static void exec_prepare_plan(PLpgSQL_execstate *estate,
153 PLpgSQL_expr *expr, int cursorOptions);
154 static bool exec_simple_check_node(Node *node);
155 static void exec_simple_check_plan(PLpgSQL_expr *expr);
156 static void exec_simple_recheck_plan(PLpgSQL_expr *expr, CachedPlan *cplan);
157 static bool exec_eval_simple_expr(PLpgSQL_execstate *estate,
163 static void exec_assign_expr(PLpgSQL_execstate *estate,
164 PLpgSQL_datum *target,
166 static void exec_assign_c_string(PLpgSQL_execstate *estate,
167 PLpgSQL_datum *target,
169 static void exec_assign_value(PLpgSQL_execstate *estate,
170 PLpgSQL_datum *target,
171 Datum value, Oid valtype, bool *isNull);
172 static void exec_eval_datum(PLpgSQL_execstate *estate,
173 PLpgSQL_datum *datum,
178 static int exec_eval_integer(PLpgSQL_execstate *estate,
181 static bool exec_eval_boolean(PLpgSQL_execstate *estate,
184 static Datum exec_eval_expr(PLpgSQL_execstate *estate,
188 static int exec_run_select(PLpgSQL_execstate *estate,
189 PLpgSQL_expr *expr, long maxtuples, Portal *portalP);
190 static int exec_for_query(PLpgSQL_execstate *estate, PLpgSQL_stmt_forq *stmt,
191 Portal portal, bool prefetch_ok);
192 static ParamListInfo setup_param_list(PLpgSQL_execstate *estate,
194 static void plpgsql_param_fetch(ParamListInfo params, int paramid);
195 static void exec_move_row(PLpgSQL_execstate *estate,
198 HeapTuple tup, TupleDesc tupdesc);
199 static HeapTuple make_tuple_from_row(PLpgSQL_execstate *estate,
202 static HeapTuple get_tuple_from_datum(Datum value);
203 static TupleDesc get_tupdesc_from_datum(Datum value);
204 static void exec_move_row_from_datum(PLpgSQL_execstate *estate,
208 static char *convert_value_to_string(PLpgSQL_execstate *estate,
209 Datum value, Oid valtype);
210 static Datum exec_cast_value(PLpgSQL_execstate *estate,
211 Datum value, Oid valtype,
217 static Datum exec_simple_cast_value(PLpgSQL_execstate *estate,
218 Datum value, Oid valtype,
219 Oid reqtype, int32 reqtypmod,
221 static void exec_init_tuple_store(PLpgSQL_execstate *estate);
222 static void exec_set_found(PLpgSQL_execstate *estate, bool state);
223 static void plpgsql_create_econtext(PLpgSQL_execstate *estate);
224 static void plpgsql_destroy_econtext(PLpgSQL_execstate *estate);
225 static void free_var(PLpgSQL_var *var);
226 static void assign_text_var(PLpgSQL_var *var, const char *str);
227 static PreparedParamsData *exec_eval_using_params(PLpgSQL_execstate *estate,
229 static void free_params_data(PreparedParamsData *ppd);
230 static Portal exec_dynquery_with_params(PLpgSQL_execstate *estate,
231 PLpgSQL_expr *dynquery, List *params,
232 const char *portalname, int cursorOptions);
234 static char *format_expr_params(PLpgSQL_execstate *estate,
235 const PLpgSQL_expr *expr);
236 static char *format_preparedparamsdata(PLpgSQL_execstate *estate,
237 const PreparedParamsData *ppd);
241 * plpgsql_exec_function Called by the call handler for
242 * function execution.
244 * This is also used to execute inline code blocks (DO blocks). The only
245 * difference that this code is aware of is that for a DO block, we want
246 * to use a private simple_eval_estate, which is created and passed in by
247 * the caller. For regular functions, pass NULL, which implies using
248 * shared_simple_eval_estate.
252 plpgsql_exec_function(PLpgSQL_function *func, FunctionCallInfo fcinfo,
253 EState *simple_eval_estate)
255 PLpgSQL_execstate estate;
256 ErrorContextCallback plerrcontext;
261 * Setup the execution state
263 plpgsql_estate_setup(&estate, func, (ReturnSetInfo *) fcinfo->resultinfo,
267 * Setup error traceback support for ereport()
269 plerrcontext.callback = plpgsql_exec_error_callback;
270 plerrcontext.arg = &estate;
271 plerrcontext.previous = error_context_stack;
272 error_context_stack = &plerrcontext;
275 * Make local execution copies of all the datums
277 estate.err_text = gettext_noop("during initialization of execution state");
278 for (i = 0; i < estate.ndatums; i++)
279 estate.datums[i] = copy_plpgsql_datum(func->datums[i]);
282 * Store the actual call argument values into the appropriate variables
284 estate.err_text = gettext_noop("while storing call arguments into local variables");
285 for (i = 0; i < func->fn_nargs; i++)
287 int n = func->fn_argvarnos[i];
289 switch (estate.datums[n]->dtype)
291 case PLPGSQL_DTYPE_VAR:
293 PLpgSQL_var *var = (PLpgSQL_var *) estate.datums[n];
295 var->value = fcinfo->arg[i];
296 var->isnull = fcinfo->argnull[i];
297 var->freeval = false;
301 case PLPGSQL_DTYPE_ROW:
303 PLpgSQL_row *row = (PLpgSQL_row *) estate.datums[n];
305 if (!fcinfo->argnull[i])
307 /* Assign row value from composite datum */
308 exec_move_row_from_datum(&estate, NULL, row,
313 /* If arg is null, treat it as an empty row */
314 exec_move_row(&estate, NULL, row, NULL, NULL);
316 /* clean up after exec_move_row() */
317 exec_eval_cleanup(&estate);
322 elog(ERROR, "unrecognized dtype: %d", func->datums[i]->dtype);
326 estate.err_text = gettext_noop("during function entry");
329 * Set the magic variable FOUND to false
331 exec_set_found(&estate, false);
334 * Let the instrumentation plugin peek at this function
336 if (*plugin_ptr && (*plugin_ptr)->func_beg)
337 ((*plugin_ptr)->func_beg) (&estate, func);
340 * Now call the toplevel block of statements
342 estate.err_text = NULL;
343 estate.err_stmt = (PLpgSQL_stmt *) (func->action);
344 rc = exec_stmt_block(&estate, func->action);
345 if (rc != PLPGSQL_RC_RETURN)
347 estate.err_stmt = NULL;
348 estate.err_text = NULL;
351 * Provide a more helpful message if a CONTINUE or RAISE has been used
352 * outside the context it can work in.
354 if (rc == PLPGSQL_RC_CONTINUE)
356 (errcode(ERRCODE_SYNTAX_ERROR),
357 errmsg("CONTINUE cannot be used outside a loop")));
360 (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
361 errmsg("control reached end of function without RETURN")));
365 * We got a return value - process it
367 estate.err_stmt = NULL;
368 estate.err_text = gettext_noop("while casting return value to function's return type");
370 fcinfo->isnull = estate.retisnull;
374 ReturnSetInfo *rsi = estate.rsi;
376 /* Check caller can handle a set result */
377 if (!rsi || !IsA(rsi, ReturnSetInfo) ||
378 (rsi->allowedModes & SFRM_Materialize) == 0)
380 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
381 errmsg("set-valued function called in context that cannot accept a set")));
382 rsi->returnMode = SFRM_Materialize;
384 /* If we produced any tuples, send back the result */
385 if (estate.tuple_store)
387 rsi->setResult = estate.tuple_store;
388 if (estate.rettupdesc)
390 MemoryContext oldcxt;
392 oldcxt = MemoryContextSwitchTo(estate.tuple_store_cxt);
393 rsi->setDesc = CreateTupleDescCopy(estate.rettupdesc);
394 MemoryContextSwitchTo(oldcxt);
397 estate.retval = (Datum) 0;
398 fcinfo->isnull = true;
400 else if (!estate.retisnull)
402 if (estate.retistuple)
405 * We have to check that the returned tuple actually matches the
406 * expected result type. XXX would be better to cache the tupdesc
407 * instead of repeating get_call_result_type()
409 HeapTuple rettup = (HeapTuple) DatumGetPointer(estate.retval);
411 TupleConversionMap *tupmap;
413 switch (get_call_result_type(fcinfo, NULL, &tupdesc))
415 case TYPEFUNC_COMPOSITE:
416 /* got the expected result rowtype, now check it */
417 tupmap = convert_tuples_by_position(estate.rettupdesc,
419 gettext_noop("returned record type does not match expected record type"));
420 /* it might need conversion */
422 rettup = do_convert_tuple(rettup, tupmap);
423 /* no need to free map, we're about to return anyway */
425 case TYPEFUNC_RECORD:
428 * Failed to determine actual type of RECORD. We could
429 * raise an error here, but what this means in practice is
430 * that the caller is expecting any old generic rowtype,
431 * so we don't really need to be restrictive. Pass back
432 * the generated result type, instead.
434 tupdesc = estate.rettupdesc;
435 if (tupdesc == NULL) /* shouldn't happen */
436 elog(ERROR, "return type must be a row type");
439 /* shouldn't get here if retistuple is true ... */
440 elog(ERROR, "return type must be a row type");
445 * Copy tuple to upper executor memory, as a tuple Datum. Make
446 * sure it is labeled with the caller-supplied tuple type.
448 estate.retval = PointerGetDatum(SPI_returntuple(rettup, tupdesc));
452 /* Cast value to proper type */
453 estate.retval = exec_cast_value(&estate,
457 &(func->fn_retinput),
458 func->fn_rettypioparam,
463 * If the function's return type isn't by value, copy the value
464 * into upper executor memory context.
466 if (!fcinfo->isnull && !func->fn_retbyval)
471 len = datumGetSize(estate.retval, false, func->fn_rettyplen);
472 tmp = SPI_palloc(len);
473 memcpy(tmp, DatumGetPointer(estate.retval), len);
474 estate.retval = PointerGetDatum(tmp);
479 estate.err_text = gettext_noop("during function exit");
482 * Let the instrumentation plugin peek at this function
484 if (*plugin_ptr && (*plugin_ptr)->func_end)
485 ((*plugin_ptr)->func_end) (&estate, func);
487 /* Clean up any leftover temporary memory */
488 plpgsql_destroy_econtext(&estate);
489 exec_eval_cleanup(&estate);
492 * Pop the error context stack
494 error_context_stack = plerrcontext.previous;
497 * Return the function's result
499 return estate.retval;
504 * plpgsql_exec_trigger Called by the call handler for
509 plpgsql_exec_trigger(PLpgSQL_function *func,
510 TriggerData *trigdata)
512 PLpgSQL_execstate estate;
513 ErrorContextCallback plerrcontext;
517 PLpgSQL_rec *rec_new,
522 * Setup the execution state
524 plpgsql_estate_setup(&estate, func, NULL, NULL);
527 * Setup error traceback support for ereport()
529 plerrcontext.callback = plpgsql_exec_error_callback;
530 plerrcontext.arg = &estate;
531 plerrcontext.previous = error_context_stack;
532 error_context_stack = &plerrcontext;
535 * Make local execution copies of all the datums
537 estate.err_text = gettext_noop("during initialization of execution state");
538 for (i = 0; i < estate.ndatums; i++)
539 estate.datums[i] = copy_plpgsql_datum(func->datums[i]);
542 * Put the OLD and NEW tuples into record variables
544 * We make the tupdescs available in both records even though only one may
545 * have a value. This allows parsing of record references to succeed in
546 * functions that are used for multiple trigger types. For example, we
547 * might have a test like "if (TG_OP = 'INSERT' and NEW.foo = 'xyz')",
548 * which should parse regardless of the current trigger type.
550 rec_new = (PLpgSQL_rec *) (estate.datums[func->new_varno]);
551 rec_new->freetup = false;
552 rec_new->tupdesc = trigdata->tg_relation->rd_att;
553 rec_new->freetupdesc = false;
554 rec_old = (PLpgSQL_rec *) (estate.datums[func->old_varno]);
555 rec_old->freetup = false;
556 rec_old->tupdesc = trigdata->tg_relation->rd_att;
557 rec_old->freetupdesc = false;
559 if (!TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
562 * Per-statement triggers don't use OLD/NEW variables
567 else if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
569 rec_new->tup = trigdata->tg_trigtuple;
572 else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
574 rec_new->tup = trigdata->tg_newtuple;
575 rec_old->tup = trigdata->tg_trigtuple;
577 else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
580 rec_old->tup = trigdata->tg_trigtuple;
583 elog(ERROR, "unrecognized trigger action: not INSERT, DELETE, or UPDATE");
586 * Assign the special tg_ variables
589 var = (PLpgSQL_var *) (estate.datums[func->tg_op_varno]);
590 if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
591 var->value = CStringGetTextDatum("INSERT");
592 else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
593 var->value = CStringGetTextDatum("UPDATE");
594 else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
595 var->value = CStringGetTextDatum("DELETE");
596 else if (TRIGGER_FIRED_BY_TRUNCATE(trigdata->tg_event))
597 var->value = CStringGetTextDatum("TRUNCATE");
599 elog(ERROR, "unrecognized trigger action: not INSERT, DELETE, UPDATE, or TRUNCATE");
603 var = (PLpgSQL_var *) (estate.datums[func->tg_name_varno]);
604 var->value = DirectFunctionCall1(namein,
605 CStringGetDatum(trigdata->tg_trigger->tgname));
609 var = (PLpgSQL_var *) (estate.datums[func->tg_when_varno]);
610 if (TRIGGER_FIRED_BEFORE(trigdata->tg_event))
611 var->value = CStringGetTextDatum("BEFORE");
612 else if (TRIGGER_FIRED_AFTER(trigdata->tg_event))
613 var->value = CStringGetTextDatum("AFTER");
614 else if (TRIGGER_FIRED_INSTEAD(trigdata->tg_event))
615 var->value = CStringGetTextDatum("INSTEAD OF");
617 elog(ERROR, "unrecognized trigger execution time: not BEFORE, AFTER, or INSTEAD OF");
621 var = (PLpgSQL_var *) (estate.datums[func->tg_level_varno]);
622 if (TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
623 var->value = CStringGetTextDatum("ROW");
624 else if (TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
625 var->value = CStringGetTextDatum("STATEMENT");
627 elog(ERROR, "unrecognized trigger event type: not ROW or STATEMENT");
631 var = (PLpgSQL_var *) (estate.datums[func->tg_relid_varno]);
632 var->value = ObjectIdGetDatum(trigdata->tg_relation->rd_id);
634 var->freeval = false;
636 var = (PLpgSQL_var *) (estate.datums[func->tg_relname_varno]);
637 var->value = DirectFunctionCall1(namein,
638 CStringGetDatum(RelationGetRelationName(trigdata->tg_relation)));
642 var = (PLpgSQL_var *) (estate.datums[func->tg_table_name_varno]);
643 var->value = DirectFunctionCall1(namein,
644 CStringGetDatum(RelationGetRelationName(trigdata->tg_relation)));
648 var = (PLpgSQL_var *) (estate.datums[func->tg_table_schema_varno]);
649 var->value = DirectFunctionCall1(namein,
652 RelationGetNamespace(
653 trigdata->tg_relation))));
657 var = (PLpgSQL_var *) (estate.datums[func->tg_nargs_varno]);
658 var->value = Int16GetDatum(trigdata->tg_trigger->tgnargs);
660 var->freeval = false;
662 var = (PLpgSQL_var *) (estate.datums[func->tg_argv_varno]);
663 if (trigdata->tg_trigger->tgnargs > 0)
666 * For historical reasons, tg_argv[] subscripts start at zero not one.
667 * So we can't use construct_array().
669 int nelems = trigdata->tg_trigger->tgnargs;
674 elems = palloc(sizeof(Datum) * nelems);
675 for (i = 0; i < nelems; i++)
676 elems[i] = CStringGetTextDatum(trigdata->tg_trigger->tgargs[i]);
680 var->value = PointerGetDatum(construct_md_array(elems, NULL,
689 var->value = (Datum) 0;
691 var->freeval = false;
694 estate.err_text = gettext_noop("during function entry");
697 * Set the magic variable FOUND to false
699 exec_set_found(&estate, false);
702 * Let the instrumentation plugin peek at this function
704 if (*plugin_ptr && (*plugin_ptr)->func_beg)
705 ((*plugin_ptr)->func_beg) (&estate, func);
708 * Now call the toplevel block of statements
710 estate.err_text = NULL;
711 estate.err_stmt = (PLpgSQL_stmt *) (func->action);
712 rc = exec_stmt_block(&estate, func->action);
713 if (rc != PLPGSQL_RC_RETURN)
715 estate.err_stmt = NULL;
716 estate.err_text = NULL;
719 * Provide a more helpful message if a CONTINUE or RAISE has been used
720 * outside the context it can work in.
722 if (rc == PLPGSQL_RC_CONTINUE)
724 (errcode(ERRCODE_SYNTAX_ERROR),
725 errmsg("CONTINUE cannot be used outside a loop")));
728 (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
729 errmsg("control reached end of trigger procedure without RETURN")));
732 estate.err_stmt = NULL;
733 estate.err_text = gettext_noop("during function exit");
737 (errcode(ERRCODE_DATATYPE_MISMATCH),
738 errmsg("trigger procedure cannot return a set")));
741 * Check that the returned tuple structure has the same attributes, the
742 * relation that fired the trigger has. A per-statement trigger always
743 * needs to return NULL, so we ignore any return value the function itself
744 * produces (XXX: is this a good idea?)
746 * XXX This way it is possible, that the trigger returns a tuple where
747 * attributes don't have the correct atttypmod's length. It's up to the
748 * trigger's programmer to ensure that this doesn't happen. Jan
750 if (estate.retisnull || !TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
754 TupleConversionMap *tupmap;
756 rettup = (HeapTuple) DatumGetPointer(estate.retval);
757 /* check rowtype compatibility */
758 tupmap = convert_tuples_by_position(estate.rettupdesc,
759 trigdata->tg_relation->rd_att,
760 gettext_noop("returned row structure does not match the structure of the triggering table"));
761 /* it might need conversion */
763 rettup = do_convert_tuple(rettup, tupmap);
764 /* no need to free map, we're about to return anyway */
766 /* Copy tuple to upper executor memory */
767 rettup = SPI_copytuple(rettup);
771 * Let the instrumentation plugin peek at this function
773 if (*plugin_ptr && (*plugin_ptr)->func_end)
774 ((*plugin_ptr)->func_end) (&estate, func);
776 /* Clean up any leftover temporary memory */
777 plpgsql_destroy_econtext(&estate);
778 exec_eval_cleanup(&estate);
781 * Pop the error context stack
783 error_context_stack = plerrcontext.previous;
786 * Return the trigger's result
792 plpgsql_exec_event_trigger(PLpgSQL_function *func, EventTriggerData *trigdata)
794 PLpgSQL_execstate estate;
795 ErrorContextCallback plerrcontext;
801 * Setup the execution state
803 plpgsql_estate_setup(&estate, func, NULL, NULL);
806 * Setup error traceback support for ereport()
808 plerrcontext.callback = plpgsql_exec_error_callback;
809 plerrcontext.arg = &estate;
810 plerrcontext.previous = error_context_stack;
811 error_context_stack = &plerrcontext;
814 * Make local execution copies of all the datums
816 estate.err_text = gettext_noop("during initialization of execution state");
817 for (i = 0; i < estate.ndatums; i++)
818 estate.datums[i] = copy_plpgsql_datum(func->datums[i]);
821 * Assign the special tg_ variables
823 var = (PLpgSQL_var *) (estate.datums[func->tg_event_varno]);
824 var->value = CStringGetTextDatum(trigdata->event);
828 var = (PLpgSQL_var *) (estate.datums[func->tg_tag_varno]);
829 var->value = CStringGetTextDatum(trigdata->tag);
834 * Let the instrumentation plugin peek at this function
836 if (*plugin_ptr && (*plugin_ptr)->func_beg)
837 ((*plugin_ptr)->func_beg) (&estate, func);
840 * Now call the toplevel block of statements
842 estate.err_text = NULL;
843 estate.err_stmt = (PLpgSQL_stmt *) (func->action);
844 rc = exec_stmt_block(&estate, func->action);
845 if (rc != PLPGSQL_RC_RETURN)
847 estate.err_stmt = NULL;
848 estate.err_text = NULL;
851 * Provide a more helpful message if a CONTINUE or RAISE has been used
852 * outside the context it can work in.
854 if (rc == PLPGSQL_RC_CONTINUE)
856 (errcode(ERRCODE_SYNTAX_ERROR),
857 errmsg("CONTINUE cannot be used outside a loop")));
860 (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
861 errmsg("control reached end of trigger procedure without RETURN")));
864 estate.err_stmt = NULL;
865 estate.err_text = gettext_noop("during function exit");
868 * Let the instrumentation plugin peek at this function
870 if (*plugin_ptr && (*plugin_ptr)->func_end)
871 ((*plugin_ptr)->func_end) (&estate, func);
873 /* Clean up any leftover temporary memory */
874 plpgsql_destroy_econtext(&estate);
875 exec_eval_cleanup(&estate);
878 * Pop the error context stack
880 error_context_stack = plerrcontext.previous;
886 * error context callback to let us supply a call-stack traceback
889 plpgsql_exec_error_callback(void *arg)
891 PLpgSQL_execstate *estate = (PLpgSQL_execstate *) arg;
893 /* if we are doing RAISE, don't report its location */
894 if (estate->err_text == raise_skip_msg)
897 if (estate->err_text != NULL)
900 * We don't expend the cycles to run gettext() on err_text unless we
901 * actually need it. Therefore, places that set up err_text should
902 * use gettext_noop() to ensure the strings get recorded in the
903 * message dictionary.
905 * If both err_text and err_stmt are set, use the err_text as
906 * description, but report the err_stmt's line number. When err_stmt
907 * is not set, we're in function entry/exit, or some such place not
908 * attached to a specific line number.
910 if (estate->err_stmt != NULL)
913 * translator: last %s is a phrase such as "during statement block
914 * local variable initialization"
916 errcontext("PL/pgSQL function %s line %d %s",
917 estate->func->fn_signature,
918 estate->err_stmt->lineno,
919 _(estate->err_text));
924 * translator: last %s is a phrase such as "while storing call
925 * arguments into local variables"
927 errcontext("PL/pgSQL function %s %s",
928 estate->func->fn_signature,
929 _(estate->err_text));
932 else if (estate->err_stmt != NULL)
934 /* translator: last %s is a plpgsql statement type name */
935 errcontext("PL/pgSQL function %s line %d at %s",
936 estate->func->fn_signature,
937 estate->err_stmt->lineno,
938 plpgsql_stmt_typename(estate->err_stmt));
941 errcontext("PL/pgSQL function %s",
942 estate->func->fn_signature);
947 * Support function for initializing local execution variables
950 static PLpgSQL_datum *
951 copy_plpgsql_datum(PLpgSQL_datum *datum)
953 PLpgSQL_datum *result;
955 switch (datum->dtype)
957 case PLPGSQL_DTYPE_VAR:
959 PLpgSQL_var *new = palloc(sizeof(PLpgSQL_var));
961 memcpy(new, datum, sizeof(PLpgSQL_var));
962 /* Ensure the value is null (possibly not needed?) */
965 new->freeval = false;
967 result = (PLpgSQL_datum *) new;
971 case PLPGSQL_DTYPE_REC:
973 PLpgSQL_rec *new = palloc(sizeof(PLpgSQL_rec));
975 memcpy(new, datum, sizeof(PLpgSQL_rec));
976 /* Ensure the value is null (possibly not needed?) */
979 new->freetup = false;
980 new->freetupdesc = false;
982 result = (PLpgSQL_datum *) new;
986 case PLPGSQL_DTYPE_ROW:
987 case PLPGSQL_DTYPE_RECFIELD:
988 case PLPGSQL_DTYPE_ARRAYELEM:
991 * These datum records are read-only at runtime, so no need to
992 * copy them (well, ARRAYELEM contains some cached type data, but
993 * we'd just as soon centralize the caching anyway)
999 elog(ERROR, "unrecognized dtype: %d", datum->dtype);
1000 result = NULL; /* keep compiler quiet */
1009 exception_matches_conditions(ErrorData *edata, PLpgSQL_condition *cond)
1011 for (; cond != NULL; cond = cond->next)
1013 int sqlerrstate = cond->sqlerrstate;
1016 * OTHERS matches everything *except* query-canceled; if you're
1017 * foolish enough, you can match that explicitly.
1019 if (sqlerrstate == 0)
1021 if (edata->sqlerrcode != ERRCODE_QUERY_CANCELED)
1025 else if (edata->sqlerrcode == sqlerrstate)
1027 /* Category match? */
1028 else if (ERRCODE_IS_CATEGORY(sqlerrstate) &&
1029 ERRCODE_TO_CATEGORY(edata->sqlerrcode) == sqlerrstate)
1037 * exec_stmt_block Execute a block of statements
1041 exec_stmt_block(PLpgSQL_execstate *estate, PLpgSQL_stmt_block *block)
1043 volatile int rc = -1;
1048 * First initialize all variables declared in this block
1050 estate->err_text = gettext_noop("during statement block local variable initialization");
1052 for (i = 0; i < block->n_initvars; i++)
1054 n = block->initvarnos[i];
1056 switch (estate->datums[n]->dtype)
1058 case PLPGSQL_DTYPE_VAR:
1060 PLpgSQL_var *var = (PLpgSQL_var *) (estate->datums[n]);
1062 /* free any old value, in case re-entering block */
1065 /* Initially it contains a NULL */
1066 var->value = (Datum) 0;
1069 if (var->default_val == NULL)
1072 * If needed, give the datatype a chance to reject
1073 * NULLs, by assigning a NULL to the variable. We
1074 * claim the value is of type UNKNOWN, not the var's
1075 * datatype, else coercion will be skipped. (Do this
1076 * before the notnull check to be consistent with
1077 * exec_assign_value.)
1079 if (!var->datatype->typinput.fn_strict)
1081 bool valIsNull = true;
1083 exec_assign_value(estate,
1084 (PLpgSQL_datum *) var,
1091 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1092 errmsg("variable \"%s\" declared NOT NULL cannot default to NULL",
1097 exec_assign_expr(estate, (PLpgSQL_datum *) var,
1103 case PLPGSQL_DTYPE_REC:
1105 PLpgSQL_rec *rec = (PLpgSQL_rec *) (estate->datums[n]);
1109 heap_freetuple(rec->tup);
1110 rec->freetup = false;
1112 if (rec->freetupdesc)
1114 FreeTupleDesc(rec->tupdesc);
1115 rec->freetupdesc = false;
1118 rec->tupdesc = NULL;
1122 case PLPGSQL_DTYPE_RECFIELD:
1123 case PLPGSQL_DTYPE_ARRAYELEM:
1127 elog(ERROR, "unrecognized dtype: %d",
1128 estate->datums[n]->dtype);
1132 if (block->exceptions)
1135 * Execute the statements in the block's body inside a sub-transaction
1137 MemoryContext oldcontext = CurrentMemoryContext;
1138 ResourceOwner oldowner = CurrentResourceOwner;
1139 ExprContext *old_eval_econtext = estate->eval_econtext;
1140 ErrorData *save_cur_error = estate->cur_error;
1142 estate->err_text = gettext_noop("during statement block entry");
1144 BeginInternalSubTransaction(NULL);
1145 /* Want to run statements inside function's memory context */
1146 MemoryContextSwitchTo(oldcontext);
1151 * We need to run the block's statements with a new eval_econtext
1152 * that belongs to the current subtransaction; if we try to use
1153 * the outer econtext then ExprContext shutdown callbacks will be
1154 * called at the wrong times.
1156 plpgsql_create_econtext(estate);
1158 estate->err_text = NULL;
1160 /* Run the block's statements */
1161 rc = exec_stmts(estate, block->body);
1163 estate->err_text = gettext_noop("during statement block exit");
1166 * If the block ended with RETURN, we may need to copy the return
1167 * value out of the subtransaction eval_context. This is
1168 * currently only needed for scalar result types --- rowtype
1169 * values will always exist in the function's own memory context.
1171 if (rc == PLPGSQL_RC_RETURN &&
1172 !estate->retisset &&
1173 !estate->retisnull &&
1174 estate->rettupdesc == NULL)
1179 get_typlenbyval(estate->rettype, &resTypLen, &resTypByVal);
1180 estate->retval = datumCopy(estate->retval,
1181 resTypByVal, resTypLen);
1184 /* Commit the inner transaction, return to outer xact context */
1185 ReleaseCurrentSubTransaction();
1186 MemoryContextSwitchTo(oldcontext);
1187 CurrentResourceOwner = oldowner;
1190 * Revert to outer eval_econtext. (The inner one was
1191 * automatically cleaned up during subxact exit.)
1193 estate->eval_econtext = old_eval_econtext;
1196 * AtEOSubXact_SPI() should not have popped any SPI context, but
1197 * just in case it did, make sure we remain connected.
1199 SPI_restore_connection();
1206 estate->err_text = gettext_noop("during exception cleanup");
1208 /* Save error info */
1209 MemoryContextSwitchTo(oldcontext);
1210 edata = CopyErrorData();
1213 /* Abort the inner transaction */
1214 RollbackAndReleaseCurrentSubTransaction();
1215 MemoryContextSwitchTo(oldcontext);
1216 CurrentResourceOwner = oldowner;
1218 /* Revert to outer eval_econtext */
1219 estate->eval_econtext = old_eval_econtext;
1222 * If AtEOSubXact_SPI() popped any SPI context of the subxact, it
1223 * will have left us in a disconnected state. We need this hack
1224 * to return to connected state.
1226 SPI_restore_connection();
1229 * Must clean up the econtext too. However, any tuple table made
1230 * in the subxact will have been thrown away by SPI during subxact
1231 * abort, so we don't need to (and mustn't try to) free the
1234 estate->eval_tuptable = NULL;
1235 exec_eval_cleanup(estate);
1237 /* Look for a matching exception handler */
1238 foreach(e, block->exceptions->exc_list)
1240 PLpgSQL_exception *exception = (PLpgSQL_exception *) lfirst(e);
1242 if (exception_matches_conditions(edata, exception->conditions))
1245 * Initialize the magic SQLSTATE and SQLERRM variables for
1246 * the exception block. We needn't do this until we have
1247 * found a matching exception.
1249 PLpgSQL_var *state_var;
1250 PLpgSQL_var *errm_var;
1252 state_var = (PLpgSQL_var *)
1253 estate->datums[block->exceptions->sqlstate_varno];
1254 errm_var = (PLpgSQL_var *)
1255 estate->datums[block->exceptions->sqlerrm_varno];
1257 assign_text_var(state_var,
1258 unpack_sql_state(edata->sqlerrcode));
1259 assign_text_var(errm_var, edata->message);
1262 * Also set up cur_error so the error data is accessible
1263 * inside the handler.
1265 estate->cur_error = edata;
1267 estate->err_text = NULL;
1269 rc = exec_stmts(estate, exception->action);
1271 free_var(state_var);
1272 state_var->value = (Datum) 0;
1273 state_var->isnull = true;
1275 errm_var->value = (Datum) 0;
1276 errm_var->isnull = true;
1283 * Restore previous state of cur_error, whether or not we executed
1284 * a handler. This is needed in case an error got thrown from
1285 * some inner block's exception handler.
1287 estate->cur_error = save_cur_error;
1289 /* If no match found, re-throw the error */
1291 ReThrowError(edata);
1293 FreeErrorData(edata);
1297 Assert(save_cur_error == estate->cur_error);
1302 * Just execute the statements in the block's body
1304 estate->err_text = NULL;
1306 rc = exec_stmts(estate, block->body);
1309 estate->err_text = NULL;
1312 * Handle the return code.
1317 case PLPGSQL_RC_RETURN:
1318 case PLPGSQL_RC_CONTINUE:
1321 case PLPGSQL_RC_EXIT:
1324 * This is intentionally different from the handling of RC_EXIT
1325 * for loops: to match a block, we require a match by label.
1327 if (estate->exitlabel == NULL)
1328 return PLPGSQL_RC_EXIT;
1329 if (block->label == NULL)
1330 return PLPGSQL_RC_EXIT;
1331 if (strcmp(block->label, estate->exitlabel) != 0)
1332 return PLPGSQL_RC_EXIT;
1333 estate->exitlabel = NULL;
1334 return PLPGSQL_RC_OK;
1337 elog(ERROR, "unrecognized rc: %d", rc);
1340 return PLPGSQL_RC_OK;
1345 * exec_stmts Iterate over a list of statements
1346 * as long as their return code is OK
1350 exec_stmts(PLpgSQL_execstate *estate, List *stmts)
1357 * Ensure we do a CHECK_FOR_INTERRUPTS() even though there is no
1358 * statement. This prevents hangup in a tight loop if, for instance,
1359 * there is a LOOP construct with an empty body.
1361 CHECK_FOR_INTERRUPTS();
1362 return PLPGSQL_RC_OK;
1367 PLpgSQL_stmt *stmt = (PLpgSQL_stmt *) lfirst(s);
1368 int rc = exec_stmt(estate, stmt);
1370 if (rc != PLPGSQL_RC_OK)
1374 return PLPGSQL_RC_OK;
1379 * exec_stmt Distribute one statement to the statements
1380 * type specific execution function.
1384 exec_stmt(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
1386 PLpgSQL_stmt *save_estmt;
1389 save_estmt = estate->err_stmt;
1390 estate->err_stmt = stmt;
1392 /* Let the plugin know that we are about to execute this statement */
1393 if (*plugin_ptr && (*plugin_ptr)->stmt_beg)
1394 ((*plugin_ptr)->stmt_beg) (estate, stmt);
1396 CHECK_FOR_INTERRUPTS();
1398 switch ((enum PLpgSQL_stmt_types) stmt->cmd_type)
1400 case PLPGSQL_STMT_BLOCK:
1401 rc = exec_stmt_block(estate, (PLpgSQL_stmt_block *) stmt);
1404 case PLPGSQL_STMT_ASSIGN:
1405 rc = exec_stmt_assign(estate, (PLpgSQL_stmt_assign *) stmt);
1408 case PLPGSQL_STMT_PERFORM:
1409 rc = exec_stmt_perform(estate, (PLpgSQL_stmt_perform *) stmt);
1412 case PLPGSQL_STMT_GETDIAG:
1413 rc = exec_stmt_getdiag(estate, (PLpgSQL_stmt_getdiag *) stmt);
1416 case PLPGSQL_STMT_IF:
1417 rc = exec_stmt_if(estate, (PLpgSQL_stmt_if *) stmt);
1420 case PLPGSQL_STMT_CASE:
1421 rc = exec_stmt_case(estate, (PLpgSQL_stmt_case *) stmt);
1424 case PLPGSQL_STMT_LOOP:
1425 rc = exec_stmt_loop(estate, (PLpgSQL_stmt_loop *) stmt);
1428 case PLPGSQL_STMT_WHILE:
1429 rc = exec_stmt_while(estate, (PLpgSQL_stmt_while *) stmt);
1432 case PLPGSQL_STMT_FORI:
1433 rc = exec_stmt_fori(estate, (PLpgSQL_stmt_fori *) stmt);
1436 case PLPGSQL_STMT_FORS:
1437 rc = exec_stmt_fors(estate, (PLpgSQL_stmt_fors *) stmt);
1440 case PLPGSQL_STMT_FORC:
1441 rc = exec_stmt_forc(estate, (PLpgSQL_stmt_forc *) stmt);
1444 case PLPGSQL_STMT_FOREACH_A:
1445 rc = exec_stmt_foreach_a(estate, (PLpgSQL_stmt_foreach_a *) stmt);
1448 case PLPGSQL_STMT_EXIT:
1449 rc = exec_stmt_exit(estate, (PLpgSQL_stmt_exit *) stmt);
1452 case PLPGSQL_STMT_RETURN:
1453 rc = exec_stmt_return(estate, (PLpgSQL_stmt_return *) stmt);
1456 case PLPGSQL_STMT_RETURN_NEXT:
1457 rc = exec_stmt_return_next(estate, (PLpgSQL_stmt_return_next *) stmt);
1460 case PLPGSQL_STMT_RETURN_QUERY:
1461 rc = exec_stmt_return_query(estate, (PLpgSQL_stmt_return_query *) stmt);
1464 case PLPGSQL_STMT_RAISE:
1465 rc = exec_stmt_raise(estate, (PLpgSQL_stmt_raise *) stmt);
1468 case PLPGSQL_STMT_EXECSQL:
1469 rc = exec_stmt_execsql(estate, (PLpgSQL_stmt_execsql *) stmt);
1472 case PLPGSQL_STMT_DYNEXECUTE:
1473 rc = exec_stmt_dynexecute(estate, (PLpgSQL_stmt_dynexecute *) stmt);
1476 case PLPGSQL_STMT_DYNFORS:
1477 rc = exec_stmt_dynfors(estate, (PLpgSQL_stmt_dynfors *) stmt);
1480 case PLPGSQL_STMT_OPEN:
1481 rc = exec_stmt_open(estate, (PLpgSQL_stmt_open *) stmt);
1484 case PLPGSQL_STMT_FETCH:
1485 rc = exec_stmt_fetch(estate, (PLpgSQL_stmt_fetch *) stmt);
1488 case PLPGSQL_STMT_CLOSE:
1489 rc = exec_stmt_close(estate, (PLpgSQL_stmt_close *) stmt);
1493 estate->err_stmt = save_estmt;
1494 elog(ERROR, "unrecognized cmdtype: %d", stmt->cmd_type);
1497 /* Let the plugin know that we have finished executing this statement */
1498 if (*plugin_ptr && (*plugin_ptr)->stmt_end)
1499 ((*plugin_ptr)->stmt_end) (estate, stmt);
1501 estate->err_stmt = save_estmt;
1508 * exec_stmt_assign Evaluate an expression and
1509 * put the result into a variable.
1513 exec_stmt_assign(PLpgSQL_execstate *estate, PLpgSQL_stmt_assign *stmt)
1515 Assert(stmt->varno >= 0);
1517 exec_assign_expr(estate, estate->datums[stmt->varno], stmt->expr);
1519 return PLPGSQL_RC_OK;
1523 * exec_stmt_perform Evaluate query and discard result (but set
1524 * FOUND depending on whether at least one row
1529 exec_stmt_perform(PLpgSQL_execstate *estate, PLpgSQL_stmt_perform *stmt)
1531 PLpgSQL_expr *expr = stmt->expr;
1533 (void) exec_run_select(estate, expr, 0, NULL);
1534 exec_set_found(estate, (estate->eval_processed != 0));
1535 exec_eval_cleanup(estate);
1537 return PLPGSQL_RC_OK;
1541 * exec_stmt_getdiag Put internal PG information into
1542 * specified variables.
1546 exec_stmt_getdiag(PLpgSQL_execstate *estate, PLpgSQL_stmt_getdiag *stmt)
1551 * GET STACKED DIAGNOSTICS is only valid inside an exception handler.
1553 * Note: we trust the grammar to have disallowed the relevant item kinds
1554 * if not is_stacked, otherwise we'd dump core below.
1556 if (stmt->is_stacked && estate->cur_error == NULL)
1558 (errcode(ERRCODE_STACKED_DIAGNOSTICS_ACCESSED_WITHOUT_ACTIVE_HANDLER),
1559 errmsg("GET STACKED DIAGNOSTICS cannot be used outside an exception handler")));
1561 foreach(lc, stmt->diag_items)
1563 PLpgSQL_diag_item *diag_item = (PLpgSQL_diag_item *) lfirst(lc);
1564 PLpgSQL_datum *var = estate->datums[diag_item->target];
1565 bool isnull = false;
1567 switch (diag_item->kind)
1569 case PLPGSQL_GETDIAG_ROW_COUNT:
1570 exec_assign_value(estate, var,
1571 UInt32GetDatum(estate->eval_processed),
1575 case PLPGSQL_GETDIAG_RESULT_OID:
1576 exec_assign_value(estate, var,
1577 ObjectIdGetDatum(estate->eval_lastoid),
1581 case PLPGSQL_GETDIAG_ERROR_CONTEXT:
1582 exec_assign_c_string(estate, var,
1583 estate->cur_error->context);
1586 case PLPGSQL_GETDIAG_ERROR_DETAIL:
1587 exec_assign_c_string(estate, var,
1588 estate->cur_error->detail);
1591 case PLPGSQL_GETDIAG_ERROR_HINT:
1592 exec_assign_c_string(estate, var,
1593 estate->cur_error->hint);
1596 case PLPGSQL_GETDIAG_RETURNED_SQLSTATE:
1597 exec_assign_c_string(estate, var,
1598 unpack_sql_state(estate->cur_error->sqlerrcode));
1601 case PLPGSQL_GETDIAG_COLUMN_NAME:
1602 exec_assign_c_string(estate, var,
1603 estate->cur_error->column_name);
1606 case PLPGSQL_GETDIAG_CONSTRAINT_NAME:
1607 exec_assign_c_string(estate, var,
1608 estate->cur_error->constraint_name);
1611 case PLPGSQL_GETDIAG_DATATYPE_NAME:
1612 exec_assign_c_string(estate, var,
1613 estate->cur_error->datatype_name);
1616 case PLPGSQL_GETDIAG_MESSAGE_TEXT:
1617 exec_assign_c_string(estate, var,
1618 estate->cur_error->message);
1621 case PLPGSQL_GETDIAG_TABLE_NAME:
1622 exec_assign_c_string(estate, var,
1623 estate->cur_error->table_name);
1626 case PLPGSQL_GETDIAG_SCHEMA_NAME:
1627 exec_assign_c_string(estate, var,
1628 estate->cur_error->schema_name);
1631 case PLPGSQL_GETDIAG_CONTEXT:
1633 char *contextstackstr = GetErrorContextStack();
1635 exec_assign_c_string(estate, var, contextstackstr);
1637 pfree(contextstackstr);
1642 elog(ERROR, "unrecognized diagnostic item kind: %d",
1647 return PLPGSQL_RC_OK;
1651 * exec_stmt_if Evaluate a bool expression and
1652 * execute the true or false body
1657 exec_stmt_if(PLpgSQL_execstate *estate, PLpgSQL_stmt_if *stmt)
1663 value = exec_eval_boolean(estate, stmt->cond, &isnull);
1664 exec_eval_cleanup(estate);
1665 if (!isnull && value)
1666 return exec_stmts(estate, stmt->then_body);
1668 foreach(lc, stmt->elsif_list)
1670 PLpgSQL_if_elsif *elif = (PLpgSQL_if_elsif *) lfirst(lc);
1672 value = exec_eval_boolean(estate, elif->cond, &isnull);
1673 exec_eval_cleanup(estate);
1674 if (!isnull && value)
1675 return exec_stmts(estate, elif->stmts);
1678 return exec_stmts(estate, stmt->else_body);
1687 exec_stmt_case(PLpgSQL_execstate *estate, PLpgSQL_stmt_case *stmt)
1689 PLpgSQL_var *t_var = NULL;
1693 if (stmt->t_expr != NULL)
1699 t_val = exec_eval_expr(estate, stmt->t_expr, &isnull, &t_oid);
1701 t_var = (PLpgSQL_var *) estate->datums[stmt->t_varno];
1704 * When expected datatype is different from real, change it. Note that
1705 * what we're modifying here is an execution copy of the datum, so
1706 * this doesn't affect the originally stored function parse tree.
1708 if (t_var->datatype->typoid != t_oid)
1709 t_var->datatype = plpgsql_build_datatype(t_oid,
1711 estate->func->fn_input_collation);
1713 /* now we can assign to the variable */
1714 exec_assign_value(estate,
1715 (PLpgSQL_datum *) t_var,
1720 exec_eval_cleanup(estate);
1723 /* Now search for a successful WHEN clause */
1724 foreach(l, stmt->case_when_list)
1726 PLpgSQL_case_when *cwt = (PLpgSQL_case_when *) lfirst(l);
1729 value = exec_eval_boolean(estate, cwt->expr, &isnull);
1730 exec_eval_cleanup(estate);
1731 if (!isnull && value)
1735 /* We can now discard any value we had for the temp variable */
1739 t_var->value = (Datum) 0;
1740 t_var->isnull = true;
1743 /* Evaluate the statement(s), and we're done */
1744 return exec_stmts(estate, cwt->stmts);
1748 /* We can now discard any value we had for the temp variable */
1752 t_var->value = (Datum) 0;
1753 t_var->isnull = true;
1756 /* SQL2003 mandates this error if there was no ELSE clause */
1757 if (!stmt->have_else)
1759 (errcode(ERRCODE_CASE_NOT_FOUND),
1760 errmsg("case not found"),
1761 errhint("CASE statement is missing ELSE part.")));
1763 /* Evaluate the ELSE statements, and we're done */
1764 return exec_stmts(estate, stmt->else_stmts);
1769 * exec_stmt_loop Loop over statements until
1774 exec_stmt_loop(PLpgSQL_execstate *estate, PLpgSQL_stmt_loop *stmt)
1778 int rc = exec_stmts(estate, stmt->body);
1785 case PLPGSQL_RC_EXIT:
1786 if (estate->exitlabel == NULL)
1787 return PLPGSQL_RC_OK;
1788 if (stmt->label == NULL)
1789 return PLPGSQL_RC_EXIT;
1790 if (strcmp(stmt->label, estate->exitlabel) != 0)
1791 return PLPGSQL_RC_EXIT;
1792 estate->exitlabel = NULL;
1793 return PLPGSQL_RC_OK;
1795 case PLPGSQL_RC_CONTINUE:
1796 if (estate->exitlabel == NULL)
1797 /* anonymous continue, so re-run the loop */
1799 else if (stmt->label != NULL &&
1800 strcmp(stmt->label, estate->exitlabel) == 0)
1801 /* label matches named continue, so re-run loop */
1802 estate->exitlabel = NULL;
1804 /* label doesn't match named continue, so propagate upward */
1805 return PLPGSQL_RC_CONTINUE;
1808 case PLPGSQL_RC_RETURN:
1812 elog(ERROR, "unrecognized rc: %d", rc);
1819 * exec_stmt_while Loop over statements as long
1820 * as an expression evaluates to
1821 * true or an exit occurs.
1825 exec_stmt_while(PLpgSQL_execstate *estate, PLpgSQL_stmt_while *stmt)
1833 value = exec_eval_boolean(estate, stmt->cond, &isnull);
1834 exec_eval_cleanup(estate);
1836 if (isnull || !value)
1839 rc = exec_stmts(estate, stmt->body);
1846 case PLPGSQL_RC_EXIT:
1847 if (estate->exitlabel == NULL)
1848 return PLPGSQL_RC_OK;
1849 if (stmt->label == NULL)
1850 return PLPGSQL_RC_EXIT;
1851 if (strcmp(stmt->label, estate->exitlabel) != 0)
1852 return PLPGSQL_RC_EXIT;
1853 estate->exitlabel = NULL;
1854 return PLPGSQL_RC_OK;
1856 case PLPGSQL_RC_CONTINUE:
1857 if (estate->exitlabel == NULL)
1858 /* anonymous continue, so re-run loop */
1860 else if (stmt->label != NULL &&
1861 strcmp(stmt->label, estate->exitlabel) == 0)
1862 /* label matches named continue, so re-run loop */
1863 estate->exitlabel = NULL;
1865 /* label doesn't match named continue, propagate upward */
1866 return PLPGSQL_RC_CONTINUE;
1869 case PLPGSQL_RC_RETURN:
1873 elog(ERROR, "unrecognized rc: %d", rc);
1877 return PLPGSQL_RC_OK;
1882 * exec_stmt_fori Iterate an integer variable
1883 * from a lower to an upper value
1884 * incrementing or decrementing by the BY value
1888 exec_stmt_fori(PLpgSQL_execstate *estate, PLpgSQL_stmt_fori *stmt)
1898 int rc = PLPGSQL_RC_OK;
1900 var = (PLpgSQL_var *) (estate->datums[stmt->var->dno]);
1903 * Get the value of the lower bound
1905 value = exec_eval_expr(estate, stmt->lower, &isnull, &valtype);
1906 value = exec_cast_value(estate, value, valtype, var->datatype->typoid,
1907 &(var->datatype->typinput),
1908 var->datatype->typioparam,
1909 var->datatype->atttypmod, isnull);
1912 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1913 errmsg("lower bound of FOR loop cannot be null")));
1914 loop_value = DatumGetInt32(value);
1915 exec_eval_cleanup(estate);
1918 * Get the value of the upper bound
1920 value = exec_eval_expr(estate, stmt->upper, &isnull, &valtype);
1921 value = exec_cast_value(estate, value, valtype, var->datatype->typoid,
1922 &(var->datatype->typinput),
1923 var->datatype->typioparam,
1924 var->datatype->atttypmod, isnull);
1927 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1928 errmsg("upper bound of FOR loop cannot be null")));
1929 end_value = DatumGetInt32(value);
1930 exec_eval_cleanup(estate);
1933 * Get the step value
1937 value = exec_eval_expr(estate, stmt->step, &isnull, &valtype);
1938 value = exec_cast_value(estate, value, valtype, var->datatype->typoid,
1939 &(var->datatype->typinput),
1940 var->datatype->typioparam,
1941 var->datatype->atttypmod, isnull);
1944 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1945 errmsg("BY value of FOR loop cannot be null")));
1946 step_value = DatumGetInt32(value);
1947 exec_eval_cleanup(estate);
1948 if (step_value <= 0)
1950 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1951 errmsg("BY value of FOR loop must be greater than zero")));
1962 * Check against upper bound
1966 if (loop_value < end_value)
1971 if (loop_value > end_value)
1975 found = true; /* looped at least once */
1978 * Assign current value to loop var
1980 var->value = Int32GetDatum(loop_value);
1981 var->isnull = false;
1984 * Execute the statements
1986 rc = exec_stmts(estate, stmt->body);
1988 if (rc == PLPGSQL_RC_RETURN)
1989 break; /* break out of the loop */
1990 else if (rc == PLPGSQL_RC_EXIT)
1992 if (estate->exitlabel == NULL)
1993 /* unlabelled exit, finish the current loop */
1995 else if (stmt->label != NULL &&
1996 strcmp(stmt->label, estate->exitlabel) == 0)
1998 /* labelled exit, matches the current stmt's label */
1999 estate->exitlabel = NULL;
2004 * otherwise, this is a labelled exit that does not match the
2005 * current statement's label, if any: return RC_EXIT so that the
2006 * EXIT continues to propagate up the stack.
2010 else if (rc == PLPGSQL_RC_CONTINUE)
2012 if (estate->exitlabel == NULL)
2013 /* unlabelled continue, so re-run the current loop */
2015 else if (stmt->label != NULL &&
2016 strcmp(stmt->label, estate->exitlabel) == 0)
2018 /* label matches named continue, so re-run loop */
2019 estate->exitlabel = NULL;
2025 * otherwise, this is a named continue that does not match the
2026 * current statement's label, if any: return RC_CONTINUE so
2027 * that the CONTINUE will propagate up the stack.
2034 * Increase/decrease loop value, unless it would overflow, in which
2035 * case exit the loop.
2039 if ((int32) (loop_value - step_value) > loop_value)
2041 loop_value -= step_value;
2045 if ((int32) (loop_value + step_value) < loop_value)
2047 loop_value += step_value;
2052 * Set the FOUND variable to indicate the result of executing the loop
2053 * (namely, whether we looped one or more times). This must be set here so
2054 * that it does not interfere with the value of the FOUND variable inside
2055 * the loop processing itself.
2057 exec_set_found(estate, found);
2064 * exec_stmt_fors Execute a query, assign each
2065 * tuple to a record or row and
2066 * execute a group of statements
2071 exec_stmt_fors(PLpgSQL_execstate *estate, PLpgSQL_stmt_fors *stmt)
2077 * Open the implicit cursor for the statement using exec_run_select
2079 exec_run_select(estate, stmt->query, 0, &portal);
2084 rc = exec_for_query(estate, (PLpgSQL_stmt_forq *) stmt, portal, true);
2087 * Close the implicit cursor
2089 SPI_cursor_close(portal);
2096 * exec_stmt_forc Execute a loop for each row from a cursor.
2100 exec_stmt_forc(PLpgSQL_execstate *estate, PLpgSQL_stmt_forc *stmt)
2102 PLpgSQL_var *curvar;
2103 char *curname = NULL;
2104 PLpgSQL_expr *query;
2105 ParamListInfo paramLI;
2110 * Get the cursor variable and if it has an assigned name, check
2111 * that it's not in use currently.
2114 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
2115 if (!curvar->isnull)
2117 curname = TextDatumGetCString(curvar->value);
2118 if (SPI_cursor_find(curname) != NULL)
2120 (errcode(ERRCODE_DUPLICATE_CURSOR),
2121 errmsg("cursor \"%s\" already in use", curname)));
2125 * Open the cursor just like an OPEN command
2127 * Note: parser should already have checked that statement supplies
2128 * args iff cursor needs them, but we check again to be safe.
2131 if (stmt->argquery != NULL)
2134 * OPEN CURSOR with args. We fake a SELECT ... INTO ...
2135 * statement to evaluate the args and put 'em into the
2139 PLpgSQL_stmt_execsql set_args;
2141 if (curvar->cursor_explicit_argrow < 0)
2143 (errcode(ERRCODE_SYNTAX_ERROR),
2144 errmsg("arguments given for cursor without arguments")));
2146 memset(&set_args, 0, sizeof(set_args));
2147 set_args.cmd_type = PLPGSQL_STMT_EXECSQL;
2148 set_args.lineno = stmt->lineno;
2149 set_args.sqlstmt = stmt->argquery;
2150 set_args.into = true;
2151 /* XXX historically this has not been STRICT */
2152 set_args.row = (PLpgSQL_row *)
2153 (estate->datums[curvar->cursor_explicit_argrow]);
2155 if (exec_stmt_execsql(estate, &set_args) != PLPGSQL_RC_OK)
2156 elog(ERROR, "open cursor failed during argument processing");
2160 if (curvar->cursor_explicit_argrow >= 0)
2162 (errcode(ERRCODE_SYNTAX_ERROR),
2163 errmsg("arguments required for cursor")));
2166 query = curvar->cursor_explicit_expr;
2169 if (query->plan == NULL)
2170 exec_prepare_plan(estate, query, curvar->cursor_options);
2173 * Set up ParamListInfo (hook function and possibly data values)
2175 paramLI = setup_param_list(estate, query);
2178 * Open the cursor (the paramlist will get copied into the portal)
2180 portal = SPI_cursor_open_with_paramlist(curname, query->plan,
2182 estate->readonly_func);
2184 elog(ERROR, "could not open cursor: %s",
2185 SPI_result_code_string(SPI_result));
2187 /* don't need paramlist any more */
2192 * If cursor variable was NULL, store the generated portal name in it
2194 if (curname == NULL)
2195 assign_text_var(curvar, portal->name);
2198 * Execute the loop. We can't prefetch because the cursor is accessible
2199 * to the user, for instance via UPDATE WHERE CURRENT OF within the loop.
2201 rc = exec_for_query(estate, (PLpgSQL_stmt_forq *) stmt, portal, false);
2204 * Close portal, and restore cursor variable if it was initially NULL.
2207 SPI_cursor_close(portal);
2209 if (curname == NULL)
2212 curvar->value = (Datum) 0;
2213 curvar->isnull = true;
2224 * exec_stmt_foreach_a Loop over elements or slices of an array
2226 * When looping over elements, the loop variable is the same type that the
2227 * array stores (eg: integer), when looping through slices, the loop variable
2228 * is an array of size and dimensions to match the size of the slice.
2232 exec_stmt_foreach_a(PLpgSQL_execstate *estate, PLpgSQL_stmt_foreach_a *stmt)
2236 PLpgSQL_datum *loop_var;
2237 Oid loop_var_elem_type;
2239 int rc = PLPGSQL_RC_OK;
2240 ArrayIterator array_iterator;
2241 Oid iterator_result_type;
2245 /* get the value of the array expression */
2246 value = exec_eval_expr(estate, stmt->expr, &isnull, &arrtype);
2249 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2250 errmsg("FOREACH expression must not be null")));
2252 /* check the type of the expression - must be an array */
2253 if (!OidIsValid(get_element_type(arrtype)))
2255 (errcode(ERRCODE_DATATYPE_MISMATCH),
2256 errmsg("FOREACH expression must yield an array, not type %s",
2257 format_type_be(arrtype))));
2260 * We must copy the array, else it will disappear in exec_eval_cleanup.
2261 * This is annoying, but cleanup will certainly happen while running the
2262 * loop body, so we have little choice.
2264 arr = DatumGetArrayTypePCopy(value);
2266 /* Clean up any leftover temporary memory */
2267 exec_eval_cleanup(estate);
2269 /* Slice dimension must be less than or equal to array dimension */
2270 if (stmt->slice < 0 || stmt->slice > ARR_NDIM(arr))
2272 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2273 errmsg("slice dimension (%d) is out of the valid range 0..%d",
2274 stmt->slice, ARR_NDIM(arr))));
2276 /* Set up the loop variable and see if it is of an array type */
2277 loop_var = estate->datums[stmt->varno];
2278 if (loop_var->dtype == PLPGSQL_DTYPE_REC ||
2279 loop_var->dtype == PLPGSQL_DTYPE_ROW)
2282 * Record/row variable is certainly not of array type, and might not
2283 * be initialized at all yet, so don't try to get its type
2285 loop_var_elem_type = InvalidOid;
2288 loop_var_elem_type = get_element_type(exec_get_datum_type(estate,
2292 * Sanity-check the loop variable type. We don't try very hard here, and
2293 * should not be too picky since it's possible that exec_assign_value can
2294 * coerce values of different types. But it seems worthwhile to complain
2295 * if the array-ness of the loop variable is not right.
2297 if (stmt->slice > 0 && loop_var_elem_type == InvalidOid)
2299 (errcode(ERRCODE_DATATYPE_MISMATCH),
2300 errmsg("FOREACH ... SLICE loop variable must be of an array type")));
2301 if (stmt->slice == 0 && loop_var_elem_type != InvalidOid)
2303 (errcode(ERRCODE_DATATYPE_MISMATCH),
2304 errmsg("FOREACH loop variable must not be of an array type")));
2306 /* Create an iterator to step through the array */
2307 array_iterator = array_create_iterator(arr, stmt->slice);
2309 /* Identify iterator result type */
2310 if (stmt->slice > 0)
2312 /* When slicing, nominal type of result is same as array type */
2313 iterator_result_type = arrtype;
2317 /* Without slicing, results are individual array elements */
2318 iterator_result_type = ARR_ELEMTYPE(arr);
2321 /* Iterate over the array elements or slices */
2322 while (array_iterate(array_iterator, &value, &isnull))
2324 found = true; /* looped at least once */
2326 /* Assign current element/slice to the loop variable */
2327 exec_assign_value(estate, loop_var, value, iterator_result_type,
2330 /* In slice case, value is temporary; must free it to avoid leakage */
2331 if (stmt->slice > 0)
2332 pfree(DatumGetPointer(value));
2335 * Execute the statements
2337 rc = exec_stmts(estate, stmt->body);
2339 /* Handle the return code */
2340 if (rc == PLPGSQL_RC_RETURN)
2341 break; /* break out of the loop */
2342 else if (rc == PLPGSQL_RC_EXIT)
2344 if (estate->exitlabel == NULL)
2345 /* unlabelled exit, finish the current loop */
2347 else if (stmt->label != NULL &&
2348 strcmp(stmt->label, estate->exitlabel) == 0)
2350 /* labelled exit, matches the current stmt's label */
2351 estate->exitlabel = NULL;
2356 * otherwise, this is a labelled exit that does not match the
2357 * current statement's label, if any: return RC_EXIT so that the
2358 * EXIT continues to propagate up the stack.
2362 else if (rc == PLPGSQL_RC_CONTINUE)
2364 if (estate->exitlabel == NULL)
2365 /* unlabelled continue, so re-run the current loop */
2367 else if (stmt->label != NULL &&
2368 strcmp(stmt->label, estate->exitlabel) == 0)
2370 /* label matches named continue, so re-run loop */
2371 estate->exitlabel = NULL;
2377 * otherwise, this is a named continue that does not match the
2378 * current statement's label, if any: return RC_CONTINUE so
2379 * that the CONTINUE will propagate up the stack.
2386 /* Release temporary memory, including the array value */
2387 array_free_iterator(array_iterator);
2391 * Set the FOUND variable to indicate the result of executing the loop
2392 * (namely, whether we looped one or more times). This must be set here so
2393 * that it does not interfere with the value of the FOUND variable inside
2394 * the loop processing itself.
2396 exec_set_found(estate, found);
2403 * exec_stmt_exit Implements EXIT and CONTINUE
2405 * This begins the process of exiting / restarting a loop.
2409 exec_stmt_exit(PLpgSQL_execstate *estate, PLpgSQL_stmt_exit *stmt)
2412 * If the exit / continue has a condition, evaluate it
2414 if (stmt->cond != NULL)
2419 value = exec_eval_boolean(estate, stmt->cond, &isnull);
2420 exec_eval_cleanup(estate);
2421 if (isnull || value == false)
2422 return PLPGSQL_RC_OK;
2425 estate->exitlabel = stmt->label;
2427 return PLPGSQL_RC_EXIT;
2429 return PLPGSQL_RC_CONTINUE;
2434 * exec_stmt_return Evaluate an expression and start
2435 * returning from the function.
2439 exec_stmt_return(PLpgSQL_execstate *estate, PLpgSQL_stmt_return *stmt)
2442 * If processing a set-returning PL/pgSQL function, the final RETURN
2443 * indicates that the function is finished producing tuples. The rest of
2444 * the work will be done at the top level.
2446 if (estate->retisset)
2447 return PLPGSQL_RC_RETURN;
2449 /* initialize for null result (possibly a tuple) */
2450 estate->retval = (Datum) 0;
2451 estate->rettupdesc = NULL;
2452 estate->retisnull = true;
2455 * This special-case path covers record/row variables in fn_retistuple
2456 * functions, as well as functions with one or more OUT parameters.
2458 if (stmt->retvarno >= 0)
2460 PLpgSQL_datum *retvar = estate->datums[stmt->retvarno];
2462 switch (retvar->dtype)
2464 case PLPGSQL_DTYPE_VAR:
2466 PLpgSQL_var *var = (PLpgSQL_var *) retvar;
2468 estate->retval = var->value;
2469 estate->retisnull = var->isnull;
2470 estate->rettype = var->datatype->typoid;
2474 case PLPGSQL_DTYPE_REC:
2476 PLpgSQL_rec *rec = (PLpgSQL_rec *) retvar;
2478 if (HeapTupleIsValid(rec->tup))
2480 estate->retval = PointerGetDatum(rec->tup);
2481 estate->rettupdesc = rec->tupdesc;
2482 estate->retisnull = false;
2487 case PLPGSQL_DTYPE_ROW:
2489 PLpgSQL_row *row = (PLpgSQL_row *) retvar;
2491 Assert(row->rowtupdesc);
2493 PointerGetDatum(make_tuple_from_row(estate, row,
2495 if (DatumGetPointer(estate->retval) == NULL) /* should not happen */
2496 elog(ERROR, "row not compatible with its own tupdesc");
2497 estate->rettupdesc = row->rowtupdesc;
2498 estate->retisnull = false;
2503 elog(ERROR, "unrecognized dtype: %d", retvar->dtype);
2506 return PLPGSQL_RC_RETURN;
2509 if (stmt->expr != NULL)
2511 estate->retval = exec_eval_expr(estate, stmt->expr,
2512 &(estate->retisnull),
2513 &(estate->rettype));
2515 if (estate->retistuple && !estate->retisnull)
2517 /* Convert composite datum to a HeapTuple and TupleDesc */
2521 /* Source must be of RECORD or composite type */
2522 if (!type_is_rowtype(estate->rettype))
2524 (errcode(ERRCODE_DATATYPE_MISMATCH),
2525 errmsg("cannot return non-composite value from function returning composite type")));
2526 tuple = get_tuple_from_datum(estate->retval);
2527 tupdesc = get_tupdesc_from_datum(estate->retval);
2528 estate->retval = PointerGetDatum(tuple);
2529 estate->rettupdesc = CreateTupleDescCopy(tupdesc);
2530 ReleaseTupleDesc(tupdesc);
2533 return PLPGSQL_RC_RETURN;
2537 * Special hack for function returning VOID: instead of NULL, return a
2538 * non-null VOID value. This is of dubious importance but is kept for
2539 * backwards compatibility.
2541 if (estate->fn_rettype == VOIDOID)
2543 estate->retval = (Datum) 0;
2544 estate->retisnull = false;
2545 estate->rettype = VOIDOID;
2548 return PLPGSQL_RC_RETURN;
2552 * exec_stmt_return_next Evaluate an expression and add it to the
2553 * list of tuples returned by the current
2558 exec_stmt_return_next(PLpgSQL_execstate *estate,
2559 PLpgSQL_stmt_return_next *stmt)
2563 HeapTuple tuple = NULL;
2564 bool free_tuple = false;
2566 if (!estate->retisset)
2568 (errcode(ERRCODE_SYNTAX_ERROR),
2569 errmsg("cannot use RETURN NEXT in a non-SETOF function")));
2571 if (estate->tuple_store == NULL)
2572 exec_init_tuple_store(estate);
2574 /* rettupdesc will be filled by exec_init_tuple_store */
2575 tupdesc = estate->rettupdesc;
2576 natts = tupdesc->natts;
2579 * This special-case path covers record/row variables in fn_retistuple
2580 * functions, as well as functions with one or more OUT parameters.
2582 if (stmt->retvarno >= 0)
2584 PLpgSQL_datum *retvar = estate->datums[stmt->retvarno];
2586 switch (retvar->dtype)
2588 case PLPGSQL_DTYPE_VAR:
2590 PLpgSQL_var *var = (PLpgSQL_var *) retvar;
2591 Datum retval = var->value;
2592 bool isNull = var->isnull;
2596 (errcode(ERRCODE_DATATYPE_MISMATCH),
2597 errmsg("wrong result type supplied in RETURN NEXT")));
2599 /* coerce type if needed */
2600 retval = exec_simple_cast_value(estate,
2602 var->datatype->typoid,
2603 tupdesc->attrs[0]->atttypid,
2604 tupdesc->attrs[0]->atttypmod,
2607 tuplestore_putvalues(estate->tuple_store, tupdesc,
2612 case PLPGSQL_DTYPE_REC:
2614 PLpgSQL_rec *rec = (PLpgSQL_rec *) retvar;
2615 TupleConversionMap *tupmap;
2617 if (!HeapTupleIsValid(rec->tup))
2619 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2620 errmsg("record \"%s\" is not assigned yet",
2622 errdetail("The tuple structure of a not-yet-assigned"
2623 " record is indeterminate.")));
2624 tupmap = convert_tuples_by_position(rec->tupdesc,
2626 gettext_noop("wrong record type supplied in RETURN NEXT"));
2628 /* it might need conversion */
2631 tuple = do_convert_tuple(tuple, tupmap);
2632 free_conversion_map(tupmap);
2638 case PLPGSQL_DTYPE_ROW:
2640 PLpgSQL_row *row = (PLpgSQL_row *) retvar;
2642 tuple = make_tuple_from_row(estate, row, tupdesc);
2645 (errcode(ERRCODE_DATATYPE_MISMATCH),
2646 errmsg("wrong record type supplied in RETURN NEXT")));
2652 elog(ERROR, "unrecognized dtype: %d", retvar->dtype);
2656 else if (stmt->expr)
2662 retval = exec_eval_expr(estate,
2667 if (estate->retistuple)
2669 /* Expression should be of RECORD or composite type */
2672 TupleDesc retvaldesc;
2673 TupleConversionMap *tupmap;
2675 if (!type_is_rowtype(rettype))
2677 (errcode(ERRCODE_DATATYPE_MISMATCH),
2678 errmsg("cannot return non-composite value from function returning composite type")));
2680 tuple = get_tuple_from_datum(retval);
2681 free_tuple = true; /* tuple is always freshly palloc'd */
2683 /* it might need conversion */
2684 retvaldesc = get_tupdesc_from_datum(retval);
2685 tupmap = convert_tuples_by_position(retvaldesc, tupdesc,
2686 gettext_noop("returned record type does not match expected record type"));
2691 newtuple = do_convert_tuple(tuple, tupmap);
2692 free_conversion_map(tupmap);
2693 heap_freetuple(tuple);
2696 ReleaseTupleDesc(retvaldesc);
2697 /* tuple will be stored into tuplestore below */
2701 /* Composite NULL --- store a row of nulls */
2705 nulldatums = (Datum *) palloc0(natts * sizeof(Datum));
2706 nullflags = (bool *) palloc(natts * sizeof(bool));
2707 memset(nullflags, true, natts * sizeof(bool));
2708 tuplestore_putvalues(estate->tuple_store, tupdesc,
2709 nulldatums, nullflags);
2716 /* Simple scalar result */
2719 (errcode(ERRCODE_DATATYPE_MISMATCH),
2720 errmsg("wrong result type supplied in RETURN NEXT")));
2722 /* coerce type if needed */
2723 retval = exec_simple_cast_value(estate,
2726 tupdesc->attrs[0]->atttypid,
2727 tupdesc->attrs[0]->atttypmod,
2730 tuplestore_putvalues(estate->tuple_store, tupdesc,
2737 (errcode(ERRCODE_SYNTAX_ERROR),
2738 errmsg("RETURN NEXT must have a parameter")));
2741 if (HeapTupleIsValid(tuple))
2743 tuplestore_puttuple(estate->tuple_store, tuple);
2746 heap_freetuple(tuple);
2749 exec_eval_cleanup(estate);
2751 return PLPGSQL_RC_OK;
2755 * exec_stmt_return_query Evaluate a query and add it to the
2756 * list of tuples returned by the current
2761 exec_stmt_return_query(PLpgSQL_execstate *estate,
2762 PLpgSQL_stmt_return_query *stmt)
2765 uint32 processed = 0;
2766 TupleConversionMap *tupmap;
2768 if (!estate->retisset)
2770 (errcode(ERRCODE_SYNTAX_ERROR),
2771 errmsg("cannot use RETURN QUERY in a non-SETOF function")));
2773 if (estate->tuple_store == NULL)
2774 exec_init_tuple_store(estate);
2776 if (stmt->query != NULL)
2779 exec_run_select(estate, stmt->query, 0, &portal);
2783 /* RETURN QUERY EXECUTE */
2784 Assert(stmt->dynquery != NULL);
2785 portal = exec_dynquery_with_params(estate, stmt->dynquery,
2786 stmt->params, NULL, 0);
2789 tupmap = convert_tuples_by_position(portal->tupDesc,
2791 gettext_noop("structure of query does not match function result type"));
2797 SPI_cursor_fetch(portal, true, 50);
2798 if (SPI_processed == 0)
2801 for (i = 0; i < SPI_processed; i++)
2803 HeapTuple tuple = SPI_tuptable->vals[i];
2806 tuple = do_convert_tuple(tuple, tupmap);
2807 tuplestore_puttuple(estate->tuple_store, tuple);
2809 heap_freetuple(tuple);
2813 SPI_freetuptable(SPI_tuptable);
2817 free_conversion_map(tupmap);
2819 SPI_freetuptable(SPI_tuptable);
2820 SPI_cursor_close(portal);
2822 estate->eval_processed = processed;
2823 exec_set_found(estate, processed != 0);
2825 return PLPGSQL_RC_OK;
2829 exec_init_tuple_store(PLpgSQL_execstate *estate)
2831 ReturnSetInfo *rsi = estate->rsi;
2832 MemoryContext oldcxt;
2833 ResourceOwner oldowner;
2836 * Check caller can handle a set result in the way we want
2838 if (!rsi || !IsA(rsi, ReturnSetInfo) ||
2839 (rsi->allowedModes & SFRM_Materialize) == 0 ||
2840 rsi->expectedDesc == NULL)
2842 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2843 errmsg("set-valued function called in context that cannot accept a set")));
2846 * Switch to the right memory context and resource owner for storing the
2847 * tuplestore for return set. If we're within a subtransaction opened for
2848 * an exception-block, for example, we must still create the tuplestore in
2849 * the resource owner that was active when this function was entered, and
2850 * not in the subtransaction resource owner.
2852 oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
2853 oldowner = CurrentResourceOwner;
2854 CurrentResourceOwner = estate->tuple_store_owner;
2856 estate->tuple_store =
2857 tuplestore_begin_heap(rsi->allowedModes & SFRM_Materialize_Random,
2860 CurrentResourceOwner = oldowner;
2861 MemoryContextSwitchTo(oldcxt);
2863 estate->rettupdesc = rsi->expectedDesc;
2866 #define SET_RAISE_OPTION_TEXT(opt, name) \
2870 (errcode(ERRCODE_SYNTAX_ERROR), \
2871 errmsg("RAISE option already specified: %s", \
2873 opt = pstrdup(extval); \
2877 * exec_stmt_raise Build a message and throw it with elog()
2881 exec_stmt_raise(PLpgSQL_execstate *estate, PLpgSQL_stmt_raise *stmt)
2884 char *condname = NULL;
2885 char *err_message = NULL;
2886 char *err_detail = NULL;
2887 char *err_hint = NULL;
2888 char *err_column = NULL;
2889 char *err_constraint = NULL;
2890 char *err_datatype = NULL;
2891 char *err_table = NULL;
2892 char *err_schema = NULL;
2895 /* RAISE with no parameters: re-throw current exception */
2896 if (stmt->condname == NULL && stmt->message == NULL &&
2897 stmt->options == NIL)
2899 if (estate->cur_error != NULL)
2900 ReThrowError(estate->cur_error);
2901 /* oops, we're not inside a handler */
2903 (errcode(ERRCODE_STACKED_DIAGNOSTICS_ACCESSED_WITHOUT_ACTIVE_HANDLER),
2904 errmsg("RAISE without parameters cannot be used outside an exception handler")));
2909 err_code = plpgsql_recognize_err_condition(stmt->condname, true);
2910 condname = pstrdup(stmt->condname);
2916 ListCell *current_param;
2919 initStringInfo(&ds);
2920 current_param = list_head(stmt->params);
2922 for (cp = stmt->message; *cp; cp++)
2925 * Occurrences of a single % are replaced by the next parameter's
2926 * external representation. Double %'s are converted to one %.
2937 appendStringInfoChar(&ds, '%');
2942 /* should have been checked at compile time */
2943 if (current_param == NULL)
2944 elog(ERROR, "unexpected RAISE parameter list length");
2946 paramvalue = exec_eval_expr(estate,
2947 (PLpgSQL_expr *) lfirst(current_param),
2954 extval = convert_value_to_string(estate,
2957 appendStringInfoString(&ds, extval);
2958 current_param = lnext(current_param);
2959 exec_eval_cleanup(estate);
2962 appendStringInfoChar(&ds, cp[0]);
2965 /* should have been checked at compile time */
2966 if (current_param != NULL)
2967 elog(ERROR, "unexpected RAISE parameter list length");
2969 err_message = ds.data;
2970 /* No pfree(ds.data), the pfree(err_message) does it */
2973 foreach(lc, stmt->options)
2975 PLpgSQL_raise_option *opt = (PLpgSQL_raise_option *) lfirst(lc);
2981 optionvalue = exec_eval_expr(estate, opt->expr,
2986 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2987 errmsg("RAISE statement option cannot be null")));
2989 extval = convert_value_to_string(estate, optionvalue, optiontypeid);
2991 switch (opt->opt_type)
2993 case PLPGSQL_RAISEOPTION_ERRCODE:
2996 (errcode(ERRCODE_SYNTAX_ERROR),
2997 errmsg("RAISE option already specified: %s",
2999 err_code = plpgsql_recognize_err_condition(extval, true);
3000 condname = pstrdup(extval);
3002 case PLPGSQL_RAISEOPTION_MESSAGE:
3003 SET_RAISE_OPTION_TEXT(err_message, "MESSAGE");
3005 case PLPGSQL_RAISEOPTION_DETAIL:
3006 SET_RAISE_OPTION_TEXT(err_detail, "DETAIL");
3008 case PLPGSQL_RAISEOPTION_HINT:
3009 SET_RAISE_OPTION_TEXT(err_hint, "HINT");
3011 case PLPGSQL_RAISEOPTION_COLUMN:
3012 SET_RAISE_OPTION_TEXT(err_column, "COLUMN");
3014 case PLPGSQL_RAISEOPTION_CONSTRAINT:
3015 SET_RAISE_OPTION_TEXT(err_constraint, "CONSTRAINT");
3017 case PLPGSQL_RAISEOPTION_DATATYPE:
3018 SET_RAISE_OPTION_TEXT(err_datatype, "DATATYPE");
3020 case PLPGSQL_RAISEOPTION_TABLE:
3021 SET_RAISE_OPTION_TEXT(err_table, "TABLE");
3023 case PLPGSQL_RAISEOPTION_SCHEMA:
3024 SET_RAISE_OPTION_TEXT(err_schema, "SCHEMA");
3027 elog(ERROR, "unrecognized raise option: %d", opt->opt_type);
3030 exec_eval_cleanup(estate);
3033 /* Default code if nothing specified */
3034 if (err_code == 0 && stmt->elog_level >= ERROR)
3035 err_code = ERRCODE_RAISE_EXCEPTION;
3037 /* Default error message if nothing specified */
3038 if (err_message == NULL)
3042 err_message = condname;
3046 err_message = pstrdup(unpack_sql_state(err_code));
3050 * Throw the error (may or may not come back)
3052 estate->err_text = raise_skip_msg; /* suppress traceback of raise */
3054 ereport(stmt->elog_level,
3055 (err_code ? errcode(err_code) : 0,
3056 errmsg_internal("%s", err_message),
3057 (err_detail != NULL) ? errdetail_internal("%s", err_detail) : 0,
3058 (err_hint != NULL) ? errhint("%s", err_hint) : 0,
3059 (err_column != NULL) ?
3060 err_generic_string(PG_DIAG_COLUMN_NAME, err_column) : 0,
3061 (err_constraint != NULL) ?
3062 err_generic_string(PG_DIAG_CONSTRAINT_NAME, err_constraint) : 0,
3063 (err_datatype != NULL) ?
3064 err_generic_string(PG_DIAG_DATATYPE_NAME, err_datatype) : 0,
3065 (err_table != NULL) ?
3066 err_generic_string(PG_DIAG_TABLE_NAME, err_table) : 0,
3067 (err_schema != NULL) ?
3068 err_generic_string(PG_DIAG_SCHEMA_NAME, err_schema) : 0));
3070 estate->err_text = NULL; /* un-suppress... */
3072 if (condname != NULL)
3074 if (err_message != NULL)
3076 if (err_detail != NULL)
3078 if (err_hint != NULL)
3080 if (err_column != NULL)
3082 if (err_constraint != NULL)
3083 pfree(err_constraint);
3084 if (err_datatype != NULL)
3085 pfree(err_datatype);
3086 if (err_table != NULL)
3088 if (err_schema != NULL)
3091 return PLPGSQL_RC_OK;
3096 * Initialize a mostly empty execution state
3100 plpgsql_estate_setup(PLpgSQL_execstate *estate,
3101 PLpgSQL_function *func,
3103 EState *simple_eval_estate)
3105 /* this link will be restored at exit from plpgsql_call_handler */
3106 func->cur_estate = estate;
3108 estate->func = func;
3110 estate->retval = (Datum) 0;
3111 estate->retisnull = true;
3112 estate->rettype = InvalidOid;
3114 estate->fn_rettype = func->fn_rettype;
3115 estate->retistuple = func->fn_retistuple;
3116 estate->retisset = func->fn_retset;
3118 estate->readonly_func = func->fn_readonly;
3120 estate->rettupdesc = NULL;
3121 estate->exitlabel = NULL;
3122 estate->cur_error = NULL;
3124 estate->tuple_store = NULL;
3127 estate->tuple_store_cxt = rsi->econtext->ecxt_per_query_memory;
3128 estate->tuple_store_owner = CurrentResourceOwner;
3132 estate->tuple_store_cxt = NULL;
3133 estate->tuple_store_owner = NULL;
3137 estate->found_varno = func->found_varno;
3138 estate->ndatums = func->ndatums;
3139 estate->datums = palloc(sizeof(PLpgSQL_datum *) * estate->ndatums);
3140 /* caller is expected to fill the datums array */
3142 /* set up for use of appropriate simple-expression EState */
3143 if (simple_eval_estate)
3144 estate->simple_eval_estate = simple_eval_estate;
3146 estate->simple_eval_estate = shared_simple_eval_estate;
3148 estate->eval_tuptable = NULL;
3149 estate->eval_processed = 0;
3150 estate->eval_lastoid = InvalidOid;
3151 estate->eval_econtext = NULL;
3152 estate->cur_expr = NULL;
3154 estate->err_stmt = NULL;
3155 estate->err_text = NULL;
3157 estate->plugin_info = NULL;
3160 * Create an EState and ExprContext for evaluation of simple expressions.
3162 plpgsql_create_econtext(estate);
3165 * Let the plugin see this function before we initialize any local
3166 * PL/pgSQL variables - note that we also give the plugin a few function
3167 * pointers so it can call back into PL/pgSQL for doing things like
3168 * variable assignments and stack traces
3172 (*plugin_ptr)->error_callback = plpgsql_exec_error_callback;
3173 (*plugin_ptr)->assign_expr = exec_assign_expr;
3175 if ((*plugin_ptr)->func_setup)
3176 ((*plugin_ptr)->func_setup) (estate, func);
3181 * Release temporary memory used by expression/subselect evaluation
3183 * NB: the result of the evaluation is no longer valid after this is done,
3184 * unless it is a pass-by-value datatype.
3186 * NB: if you change this code, see also the hacks in exec_assign_value's
3187 * PLPGSQL_DTYPE_ARRAYELEM case.
3191 exec_eval_cleanup(PLpgSQL_execstate *estate)
3193 /* Clear result of a full SPI_execute */
3194 if (estate->eval_tuptable != NULL)
3195 SPI_freetuptable(estate->eval_tuptable);
3196 estate->eval_tuptable = NULL;
3198 /* Clear result of exec_eval_simple_expr (but keep the econtext) */
3199 if (estate->eval_econtext != NULL)
3200 ResetExprContext(estate->eval_econtext);
3205 * Generate a prepared plan
3209 exec_prepare_plan(PLpgSQL_execstate *estate,
3210 PLpgSQL_expr *expr, int cursorOptions)
3215 * The grammar can't conveniently set expr->func while building the parse
3216 * tree, so make sure it's set before parser hooks need it.
3218 expr->func = estate->func;
3221 * Generate and save the plan
3223 plan = SPI_prepare_params(expr->query,
3224 (ParserSetupHook) plpgsql_parser_setup,
3229 /* Some SPI errors deserve specific error messages */
3232 case SPI_ERROR_COPY:
3234 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3235 errmsg("cannot COPY to/from client in PL/pgSQL")));
3236 case SPI_ERROR_TRANSACTION:
3238 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3239 errmsg("cannot begin/end transactions in PL/pgSQL"),
3240 errhint("Use a BEGIN block with an EXCEPTION clause instead.")));
3242 elog(ERROR, "SPI_prepare_params failed for \"%s\": %s",
3243 expr->query, SPI_result_code_string(SPI_result));
3249 /* Check to see if it's a simple expression */
3250 exec_simple_check_plan(expr);
3255 * exec_stmt_execsql Execute an SQL statement (possibly with INTO).
3259 exec_stmt_execsql(PLpgSQL_execstate *estate,
3260 PLpgSQL_stmt_execsql *stmt)
3262 ParamListInfo paramLI;
3265 PLpgSQL_expr *expr = stmt->sqlstmt;
3268 * On the first call for this statement generate the plan, and detect
3269 * whether the statement is INSERT/UPDATE/DELETE
3271 if (expr->plan == NULL)
3275 exec_prepare_plan(estate, expr, 0);
3276 stmt->mod_stmt = false;
3277 foreach(l, SPI_plan_get_plan_sources(expr->plan))
3279 CachedPlanSource *plansource = (CachedPlanSource *) lfirst(l);
3282 foreach(l2, plansource->query_list)
3284 Query *q = (Query *) lfirst(l2);
3286 Assert(IsA(q, Query));
3289 if (q->commandType == CMD_INSERT ||
3290 q->commandType == CMD_UPDATE ||
3291 q->commandType == CMD_DELETE)
3292 stmt->mod_stmt = true;
3299 * Set up ParamListInfo (hook function and possibly data values)
3301 paramLI = setup_param_list(estate, expr);
3304 * If we have INTO, then we only need one row back ... but if we have INTO
3305 * STRICT, ask for two rows, so that we can verify the statement returns
3306 * only one. INSERT/UPDATE/DELETE are always treated strictly. Without
3307 * INTO, just run the statement to completion (tcount = 0).
3309 * We could just ask for two rows always when using INTO, but there are
3310 * some cases where demanding the extra row costs significant time, eg by
3311 * forcing completion of a sequential scan. So don't do it unless we need
3312 * to enforce strictness.
3316 if (stmt->strict || stmt->mod_stmt)
3327 rc = SPI_execute_plan_with_paramlist(expr->plan, paramLI,
3328 estate->readonly_func, tcount);
3331 * Check for error, and set FOUND if appropriate (for historical reasons
3332 * we set FOUND only for certain query types). Also Assert that we
3333 * identified the statement type the same as SPI did.
3338 Assert(!stmt->mod_stmt);
3339 exec_set_found(estate, (SPI_processed != 0));
3345 case SPI_OK_INSERT_RETURNING:
3346 case SPI_OK_UPDATE_RETURNING:
3347 case SPI_OK_DELETE_RETURNING:
3348 Assert(stmt->mod_stmt);
3349 exec_set_found(estate, (SPI_processed != 0));
3352 case SPI_OK_SELINTO:
3353 case SPI_OK_UTILITY:
3354 Assert(!stmt->mod_stmt);
3357 case SPI_OK_REWRITTEN:
3358 Assert(!stmt->mod_stmt);
3361 * The command was rewritten into another kind of command. It's
3362 * not clear what FOUND would mean in that case (and SPI doesn't
3363 * return the row count either), so just set it to false.
3365 exec_set_found(estate, false);
3368 /* Some SPI errors deserve specific error messages */
3369 case SPI_ERROR_COPY:
3371 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3372 errmsg("cannot COPY to/from client in PL/pgSQL")));
3373 case SPI_ERROR_TRANSACTION:
3375 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3376 errmsg("cannot begin/end transactions in PL/pgSQL"),
3377 errhint("Use a BEGIN block with an EXCEPTION clause instead.")));
3380 elog(ERROR, "SPI_execute_plan_with_paramlist failed executing query \"%s\": %s",
3381 expr->query, SPI_result_code_string(rc));
3384 /* All variants should save result info for GET DIAGNOSTICS */
3385 estate->eval_processed = SPI_processed;
3386 estate->eval_lastoid = SPI_lastoid;
3388 /* Process INTO if present */
3391 SPITupleTable *tuptab = SPI_tuptable;
3392 uint32 n = SPI_processed;
3393 PLpgSQL_rec *rec = NULL;
3394 PLpgSQL_row *row = NULL;
3396 /* If the statement did not return a tuple table, complain */
3399 (errcode(ERRCODE_SYNTAX_ERROR),
3400 errmsg("INTO used with a command that cannot return data")));
3402 /* Determine if we assign to a record or a row */
3403 if (stmt->rec != NULL)
3404 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->dno]);
3405 else if (stmt->row != NULL)
3406 row = (PLpgSQL_row *) (estate->datums[stmt->row->dno]);
3408 elog(ERROR, "unsupported target");
3411 * If SELECT ... INTO specified STRICT, and the query didn't find
3412 * exactly one row, throw an error. If STRICT was not specified, then
3413 * allow the query to find any number of rows.
3421 if (estate->func->print_strict_params)
3422 errdetail = format_expr_params(estate, expr);
3427 (errcode(ERRCODE_NO_DATA_FOUND),
3428 errmsg("query returned no rows"),
3429 errdetail ? errdetail_internal("parameters: %s", errdetail) : 0));
3431 /* set the target to NULL(s) */
3432 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
3436 if (n > 1 && (stmt->strict || stmt->mod_stmt))
3440 if (estate->func->print_strict_params)
3441 errdetail = format_expr_params(estate, expr);
3446 (errcode(ERRCODE_TOO_MANY_ROWS),
3447 errmsg("query returned more than one row"),
3448 errdetail ? errdetail_internal("parameters: %s", errdetail) : 0));
3450 /* Put the first result row into the target */
3451 exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
3455 exec_eval_cleanup(estate);
3456 SPI_freetuptable(SPI_tuptable);
3460 /* If the statement returned a tuple table, complain */
3461 if (SPI_tuptable != NULL)
3463 (errcode(ERRCODE_SYNTAX_ERROR),
3464 errmsg("query has no destination for result data"),
3465 (rc == SPI_OK_SELECT) ? errhint("If you want to discard the results of a SELECT, use PERFORM instead.") : 0));
3471 return PLPGSQL_RC_OK;
3476 * exec_stmt_dynexecute Execute a dynamic SQL query
3477 * (possibly with INTO).
3481 exec_stmt_dynexecute(PLpgSQL_execstate *estate,
3482 PLpgSQL_stmt_dynexecute *stmt)
3485 bool isnull = false;
3489 PreparedParamsData *ppd = NULL;
3492 * First we evaluate the string expression after the EXECUTE keyword. Its
3493 * result is the querystring we have to execute.
3495 query = exec_eval_expr(estate, stmt->query, &isnull, &restype);
3498 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3499 errmsg("query string argument of EXECUTE is null")));
3501 /* Get the C-String representation */
3502 querystr = convert_value_to_string(estate, query, restype);
3504 /* copy it out of the temporary context before we clean up */
3505 querystr = pstrdup(querystr);
3507 exec_eval_cleanup(estate);
3510 * Execute the query without preparing a saved plan.
3514 ppd = exec_eval_using_params(estate, stmt->params);
3515 exec_res = SPI_execute_with_args(querystr,
3516 ppd->nargs, ppd->types,
3517 ppd->values, ppd->nulls,
3518 estate->readonly_func, 0);
3521 exec_res = SPI_execute(querystr, estate->readonly_func, 0);
3529 case SPI_OK_INSERT_RETURNING:
3530 case SPI_OK_UPDATE_RETURNING:
3531 case SPI_OK_DELETE_RETURNING:
3532 case SPI_OK_UTILITY:
3533 case SPI_OK_REWRITTEN:
3539 * Also allow a zero return, which implies the querystring
3540 * contained no commands.
3544 case SPI_OK_SELINTO:
3547 * We want to disallow SELECT INTO for now, because its behavior
3548 * is not consistent with SELECT INTO in a normal plpgsql context.
3549 * (We need to reimplement EXECUTE to parse the string as a
3550 * plpgsql command, not just feed it to SPI_execute.) This is not
3551 * a functional limitation because CREATE TABLE AS is allowed.
3554 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3555 errmsg("EXECUTE of SELECT ... INTO is not implemented"),
3556 errhint("You might want to use EXECUTE ... INTO or EXECUTE CREATE TABLE ... AS instead.")));
3559 /* Some SPI errors deserve specific error messages */
3560 case SPI_ERROR_COPY:
3562 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3563 errmsg("cannot COPY to/from client in PL/pgSQL")));
3564 case SPI_ERROR_TRANSACTION:
3566 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3567 errmsg("cannot begin/end transactions in PL/pgSQL"),
3568 errhint("Use a BEGIN block with an EXCEPTION clause instead.")));
3571 elog(ERROR, "SPI_execute failed executing query \"%s\": %s",
3572 querystr, SPI_result_code_string(exec_res));
3576 /* Save result info for GET DIAGNOSTICS */
3577 estate->eval_processed = SPI_processed;
3578 estate->eval_lastoid = SPI_lastoid;
3580 /* Process INTO if present */
3583 SPITupleTable *tuptab = SPI_tuptable;
3584 uint32 n = SPI_processed;
3585 PLpgSQL_rec *rec = NULL;
3586 PLpgSQL_row *row = NULL;
3588 /* If the statement did not return a tuple table, complain */
3591 (errcode(ERRCODE_SYNTAX_ERROR),
3592 errmsg("INTO used with a command that cannot return data")));
3594 /* Determine if we assign to a record or a row */
3595 if (stmt->rec != NULL)
3596 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->dno]);
3597 else if (stmt->row != NULL)
3598 row = (PLpgSQL_row *) (estate->datums[stmt->row->dno]);
3600 elog(ERROR, "unsupported target");
3603 * If SELECT ... INTO specified STRICT, and the query didn't find
3604 * exactly one row, throw an error. If STRICT was not specified, then
3605 * allow the query to find any number of rows.
3613 if (estate->func->print_strict_params)
3614 errdetail = format_preparedparamsdata(estate, ppd);
3619 (errcode(ERRCODE_NO_DATA_FOUND),
3620 errmsg("query returned no rows"),
3621 errdetail ? errdetail_internal("parameters: %s", errdetail) : 0));
3623 /* set the target to NULL(s) */
3624 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
3628 if (n > 1 && stmt->strict)
3632 if (estate->func->print_strict_params)
3633 errdetail = format_preparedparamsdata(estate, ppd);
3638 (errcode(ERRCODE_TOO_MANY_ROWS),
3639 errmsg("query returned more than one row"),
3640 errdetail ? errdetail_internal("parameters: %s", errdetail) : 0));
3643 /* Put the first result row into the target */
3644 exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
3646 /* clean up after exec_move_row() */
3647 exec_eval_cleanup(estate);
3652 * It might be a good idea to raise an error if the query returned
3653 * tuples that are being ignored, but historically we have not done
3659 free_params_data(ppd);
3661 /* Release any result from SPI_execute, as well as the querystring */
3662 SPI_freetuptable(SPI_tuptable);
3665 return PLPGSQL_RC_OK;
3670 * exec_stmt_dynfors Execute a dynamic query, assign each
3671 * tuple to a record or row and
3672 * execute a group of statements
3677 exec_stmt_dynfors(PLpgSQL_execstate *estate, PLpgSQL_stmt_dynfors *stmt)
3682 portal = exec_dynquery_with_params(estate, stmt->query, stmt->params,
3688 rc = exec_for_query(estate, (PLpgSQL_stmt_forq *) stmt, portal, true);
3691 * Close the implicit cursor
3693 SPI_cursor_close(portal);
3700 * exec_stmt_open Execute an OPEN cursor statement
3704 exec_stmt_open(PLpgSQL_execstate *estate, PLpgSQL_stmt_open *stmt)
3706 PLpgSQL_var *curvar;
3707 char *curname = NULL;
3708 PLpgSQL_expr *query;
3710 ParamListInfo paramLI;
3713 * Get the cursor variable and if it has an assigned name, check
3714 * that it's not in use currently.
3717 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
3718 if (!curvar->isnull)
3720 curname = TextDatumGetCString(curvar->value);
3721 if (SPI_cursor_find(curname) != NULL)
3723 (errcode(ERRCODE_DUPLICATE_CURSOR),
3724 errmsg("cursor \"%s\" already in use", curname)));
3728 * Process the OPEN according to it's type.
3731 if (stmt->query != NULL)
3734 * This is an OPEN refcursor FOR SELECT ...
3736 * We just make sure the query is planned. The real work is
3740 query = stmt->query;
3741 if (query->plan == NULL)
3742 exec_prepare_plan(estate, query, stmt->cursor_options);
3744 else if (stmt->dynquery != NULL)
3747 * This is an OPEN refcursor FOR EXECUTE ...
3750 portal = exec_dynquery_with_params(estate,
3754 stmt->cursor_options);
3757 * If cursor variable was NULL, store the generated portal name in it
3759 if (curname == NULL)
3760 assign_text_var(curvar, portal->name);
3762 return PLPGSQL_RC_OK;
3767 * This is an OPEN cursor
3769 * Note: parser should already have checked that statement supplies
3770 * args iff cursor needs them, but we check again to be safe.
3773 if (stmt->argquery != NULL)
3776 * OPEN CURSOR with args. We fake a SELECT ... INTO ...
3777 * statement to evaluate the args and put 'em into the
3781 PLpgSQL_stmt_execsql set_args;
3783 if (curvar->cursor_explicit_argrow < 0)
3785 (errcode(ERRCODE_SYNTAX_ERROR),
3786 errmsg("arguments given for cursor without arguments")));
3788 memset(&set_args, 0, sizeof(set_args));
3789 set_args.cmd_type = PLPGSQL_STMT_EXECSQL;
3790 set_args.lineno = stmt->lineno;
3791 set_args.sqlstmt = stmt->argquery;
3792 set_args.into = true;
3793 /* XXX historically this has not been STRICT */
3794 set_args.row = (PLpgSQL_row *)
3795 (estate->datums[curvar->cursor_explicit_argrow]);
3797 if (exec_stmt_execsql(estate, &set_args) != PLPGSQL_RC_OK)
3798 elog(ERROR, "open cursor failed during argument processing");
3802 if (curvar->cursor_explicit_argrow >= 0)
3804 (errcode(ERRCODE_SYNTAX_ERROR),
3805 errmsg("arguments required for cursor")));
3808 query = curvar->cursor_explicit_expr;
3809 if (query->plan == NULL)
3810 exec_prepare_plan(estate, query, curvar->cursor_options);
3814 * Set up ParamListInfo (hook function and possibly data values)
3816 paramLI = setup_param_list(estate, query);
3821 portal = SPI_cursor_open_with_paramlist(curname, query->plan,
3823 estate->readonly_func);
3825 elog(ERROR, "could not open cursor: %s",
3826 SPI_result_code_string(SPI_result));
3829 * If cursor variable was NULL, store the generated portal name in it
3831 if (curname == NULL)
3832 assign_text_var(curvar, portal->name);
3839 return PLPGSQL_RC_OK;
3844 * exec_stmt_fetch Fetch from a cursor into a target, or just
3845 * move the current position of the cursor
3849 exec_stmt_fetch(PLpgSQL_execstate *estate, PLpgSQL_stmt_fetch *stmt)
3851 PLpgSQL_var *curvar = NULL;
3852 PLpgSQL_rec *rec = NULL;
3853 PLpgSQL_row *row = NULL;
3854 long how_many = stmt->how_many;
3855 SPITupleTable *tuptab;
3861 * Get the portal of the cursor by name
3864 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
3867 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3868 errmsg("cursor variable \"%s\" is null", curvar->refname)));
3869 curname = TextDatumGetCString(curvar->value);
3871 portal = SPI_cursor_find(curname);
3874 (errcode(ERRCODE_UNDEFINED_CURSOR),
3875 errmsg("cursor \"%s\" does not exist", curname)));
3878 /* Calculate position for FETCH_RELATIVE or FETCH_ABSOLUTE */
3883 /* XXX should be doing this in LONG not INT width */
3884 how_many = exec_eval_integer(estate, stmt->expr, &isnull);
3888 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3889 errmsg("relative or absolute cursor position is null")));
3891 exec_eval_cleanup(estate);
3897 * Determine if we fetch into a record or a row
3900 if (stmt->rec != NULL)
3901 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->dno]);
3902 else if (stmt->row != NULL)
3903 row = (PLpgSQL_row *) (estate->datums[stmt->row->dno]);
3905 elog(ERROR, "unsupported target");
3908 * Fetch 1 tuple from the cursor
3911 SPI_scroll_cursor_fetch(portal, stmt->direction, how_many);
3912 tuptab = SPI_tuptable;
3916 * Set the target appropriately.
3920 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
3922 exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
3924 exec_eval_cleanup(estate);
3925 SPI_freetuptable(tuptab);
3929 /* Move the cursor */
3930 SPI_scroll_cursor_move(portal, stmt->direction, how_many);
3934 /* Set the ROW_COUNT and the global FOUND variable appropriately. */
3935 estate->eval_processed = n;
3936 exec_set_found(estate, n != 0);
3938 return PLPGSQL_RC_OK;
3942 * exec_stmt_close Close a cursor
3946 exec_stmt_close(PLpgSQL_execstate *estate, PLpgSQL_stmt_close *stmt)
3948 PLpgSQL_var *curvar = NULL;
3953 * Get the portal of the cursor by name
3956 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
3959 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3960 errmsg("cursor variable \"%s\" is null", curvar->refname)));
3961 curname = TextDatumGetCString(curvar->value);
3963 portal = SPI_cursor_find(curname);
3966 (errcode(ERRCODE_UNDEFINED_CURSOR),
3967 errmsg("cursor \"%s\" does not exist", curname)));
3974 SPI_cursor_close(portal);
3976 return PLPGSQL_RC_OK;
3981 * exec_assign_expr Put an expression's result into a variable.
3985 exec_assign_expr(PLpgSQL_execstate *estate, PLpgSQL_datum *target,
3990 bool isnull = false;
3992 value = exec_eval_expr(estate, expr, &isnull, &valtype);
3993 exec_assign_value(estate, target, value, valtype, &isnull);
3994 exec_eval_cleanup(estate);
3999 * exec_assign_c_string Put a C string into a text variable.
4001 * We take a NULL pointer as signifying empty string, not SQL null.
4005 exec_assign_c_string(PLpgSQL_execstate *estate, PLpgSQL_datum *target,
4009 bool isnull = false;
4012 value = cstring_to_text(str);
4014 value = cstring_to_text("");
4015 exec_assign_value(estate, target, PointerGetDatum(value),
4022 * exec_assign_value Put a value into a target field
4024 * Note: in some code paths, this will leak memory in the eval_econtext;
4025 * we assume that will be cleaned up later by exec_eval_cleanup. We cannot
4026 * call exec_eval_cleanup here for fear of destroying the input Datum value.
4030 exec_assign_value(PLpgSQL_execstate *estate,
4031 PLpgSQL_datum *target,
4032 Datum value, Oid valtype, bool *isNull)
4034 switch (target->dtype)
4036 case PLPGSQL_DTYPE_VAR:
4039 * Target is a variable
4041 PLpgSQL_var *var = (PLpgSQL_var *) target;
4044 newvalue = exec_cast_value(estate,
4047 var->datatype->typoid,
4048 &(var->datatype->typinput),
4049 var->datatype->typioparam,
4050 var->datatype->atttypmod,
4053 if (*isNull && var->notnull)
4055 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
4056 errmsg("null value cannot be assigned to variable \"%s\" declared NOT NULL",
4060 * If type is by-reference, copy the new value (which is
4061 * probably in the eval_econtext) into the procedure's memory
4064 if (!var->datatype->typbyval && !*isNull)
4065 newvalue = datumCopy(newvalue,
4067 var->datatype->typlen);
4070 * Now free the old value. (We can't do this any earlier
4071 * because of the possibility that we are assigning the var's
4072 * old value to it, eg "foo := foo". We could optimize out
4073 * the assignment altogether in such cases, but it's too
4074 * infrequent to be worth testing for.)
4078 var->value = newvalue;
4079 var->isnull = *isNull;
4080 if (!var->datatype->typbyval && !*isNull)
4081 var->freeval = true;
4085 case PLPGSQL_DTYPE_ROW:
4088 * Target is a row variable
4090 PLpgSQL_row *row = (PLpgSQL_row *) target;
4094 /* If source is null, just assign nulls to the row */
4095 exec_move_row(estate, NULL, row, NULL, NULL);
4099 /* Source must be of RECORD or composite type */
4100 if (!type_is_rowtype(valtype))
4102 (errcode(ERRCODE_DATATYPE_MISMATCH),
4103 errmsg("cannot assign non-composite value to a row variable")));
4104 exec_move_row_from_datum(estate, NULL, row, value);
4109 case PLPGSQL_DTYPE_REC:
4112 * Target is a record variable
4114 PLpgSQL_rec *rec = (PLpgSQL_rec *) target;
4118 /* If source is null, just assign nulls to the record */
4119 exec_move_row(estate, rec, NULL, NULL, NULL);
4123 /* Source must be of RECORD or composite type */
4124 if (!type_is_rowtype(valtype))
4126 (errcode(ERRCODE_DATATYPE_MISMATCH),
4127 errmsg("cannot assign non-composite value to a record variable")));
4128 exec_move_row_from_datum(estate, rec, NULL, value);
4133 case PLPGSQL_DTYPE_RECFIELD:
4136 * Target is a field of a record
4138 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) target;
4150 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
4153 * Check that there is already a tuple in the record. We need
4154 * that because records don't have any predefined field
4157 if (!HeapTupleIsValid(rec->tup))
4159 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4160 errmsg("record \"%s\" is not assigned yet",
4162 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
4165 * Get the number of the records field to change and the
4166 * number of attributes in the tuple. Note: disallow system
4167 * column names because the code below won't cope.
4169 fno = SPI_fnumber(rec->tupdesc, recfield->fieldname);
4172 (errcode(ERRCODE_UNDEFINED_COLUMN),
4173 errmsg("record \"%s\" has no field \"%s\"",
4174 rec->refname, recfield->fieldname)));
4176 natts = rec->tupdesc->natts;
4179 * Set up values/control arrays for heap_modify_tuple. For all
4180 * the attributes except the one we want to replace, use the
4181 * value that's in the old tuple.
4183 values = palloc(sizeof(Datum) * natts);
4184 nulls = palloc(sizeof(bool) * natts);
4185 replaces = palloc(sizeof(bool) * natts);
4187 memset(replaces, false, sizeof(bool) * natts);
4188 replaces[fno] = true;
4191 * Now insert the new value, being careful to cast it to the
4194 atttype = SPI_gettypeid(rec->tupdesc, fno + 1);
4195 atttypmod = rec->tupdesc->attrs[fno]->atttypmod;
4196 attisnull = *isNull;
4197 values[fno] = exec_simple_cast_value(estate,
4203 nulls[fno] = attisnull;
4206 * Now call heap_modify_tuple() to create a new tuple that
4207 * replaces the old one in the record.
4209 newtup = heap_modify_tuple(rec->tup, rec->tupdesc,
4210 values, nulls, replaces);
4213 heap_freetuple(rec->tup);
4216 rec->freetup = true;
4225 case PLPGSQL_DTYPE_ARRAYELEM:
4228 * Target is an element of an array
4230 PLpgSQL_arrayelem *arrayelem;
4233 PLpgSQL_expr *subscripts[MAXDIM];
4234 int subscriptvals[MAXDIM];
4235 Datum oldarraydatum,
4237 bool oldarrayisnull;
4240 ArrayType *oldarrayval;
4241 ArrayType *newarrayval;
4242 SPITupleTable *save_eval_tuptable;
4243 MemoryContext oldcontext;
4246 * We need to do subscript evaluation, which might require
4247 * evaluating general expressions; and the caller might have
4248 * done that too in order to prepare the input Datum. We have
4249 * to save and restore the caller's SPI_execute result, if
4252 save_eval_tuptable = estate->eval_tuptable;
4253 estate->eval_tuptable = NULL;
4256 * To handle constructs like x[1][2] := something, we have to
4257 * be prepared to deal with a chain of arrayelem datums. Chase
4258 * back to find the base array datum, and save the subscript
4259 * expressions as we go. (We are scanning right to left here,
4260 * but want to evaluate the subscripts left-to-right to
4261 * minimize surprises.) Note that arrayelem is left pointing
4262 * to the leftmost arrayelem datum, where we will cache the
4263 * array element type data.
4268 arrayelem = (PLpgSQL_arrayelem *) target;
4269 if (nsubscripts >= MAXDIM)
4271 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
4272 errmsg("number of array dimensions (%d) exceeds the maximum allowed (%d)",
4273 nsubscripts + 1, MAXDIM)));
4274 subscripts[nsubscripts++] = arrayelem->subscript;
4275 target = estate->datums[arrayelem->arrayparentno];
4276 } while (target->dtype == PLPGSQL_DTYPE_ARRAYELEM);
4278 /* Fetch current value of array datum */
4279 exec_eval_datum(estate, target,
4280 &parenttypoid, &parenttypmod,
4281 &oldarraydatum, &oldarrayisnull);
4283 /* Update cached type data if necessary */
4284 if (arrayelem->parenttypoid != parenttypoid ||
4285 arrayelem->parenttypmod != parenttypmod)
4288 int32 arraytypmod = parenttypmod;
4295 /* If target is domain over array, reduce to base type */
4296 arraytypoid = getBaseTypeAndTypmod(parenttypoid,
4299 /* ... and identify the element type */
4300 elemtypoid = get_element_type(arraytypoid);
4301 if (!OidIsValid(elemtypoid))
4303 (errcode(ERRCODE_DATATYPE_MISMATCH),
4304 errmsg("subscripted object is not an array")));
4306 /* Collect needed data about the types */
4307 arraytyplen = get_typlen(arraytypoid);
4309 get_typlenbyvalalign(elemtypoid,
4314 /* Now safe to update the cached data */
4315 arrayelem->parenttypoid = parenttypoid;
4316 arrayelem->parenttypmod = parenttypmod;
4317 arrayelem->arraytypoid = arraytypoid;
4318 arrayelem->arraytypmod = arraytypmod;
4319 arrayelem->arraytyplen = arraytyplen;
4320 arrayelem->elemtypoid = elemtypoid;
4321 arrayelem->elemtyplen = elemtyplen;
4322 arrayelem->elemtypbyval = elemtypbyval;
4323 arrayelem->elemtypalign = elemtypalign;
4327 * Evaluate the subscripts, switch into left-to-right order.
4328 * Like ExecEvalArrayRef(), complain if any subscript is null.
4330 for (i = 0; i < nsubscripts; i++)
4335 exec_eval_integer(estate,
4336 subscripts[nsubscripts - 1 - i],
4340 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
4341 errmsg("array subscript in assignment must not be null")));
4344 * Clean up in case the subscript expression wasn't
4345 * simple. We can't do exec_eval_cleanup, but we can do
4346 * this much (which is safe because the integer subscript
4347 * value is surely pass-by-value), and we must do it in
4348 * case the next subscript expression isn't simple either.
4350 if (estate->eval_tuptable != NULL)
4351 SPI_freetuptable(estate->eval_tuptable);
4352 estate->eval_tuptable = NULL;
4355 /* Now we can restore caller's SPI_execute result if any. */
4356 Assert(estate->eval_tuptable == NULL);
4357 estate->eval_tuptable = save_eval_tuptable;
4359 /* Coerce source value to match array element type. */
4360 coerced_value = exec_simple_cast_value(estate,
4363 arrayelem->elemtypoid,
4364 arrayelem->arraytypmod,
4368 * If the original array is null, cons up an empty array so
4369 * that the assignment can proceed; we'll end with a
4370 * one-element array containing just the assigned-to
4371 * subscript. This only works for varlena arrays, though; for
4372 * fixed-length array types we skip the assignment. We can't
4373 * support assignment of a null entry into a fixed-length
4374 * array, either, so that's a no-op too. This is all ugly but
4375 * corresponds to the current behavior of ExecEvalArrayRef().
4377 if (arrayelem->arraytyplen > 0 && /* fixed-length array? */
4378 (oldarrayisnull || *isNull))
4381 /* oldarrayval and newarrayval should be short-lived */
4382 oldcontext = MemoryContextSwitchTo(estate->eval_econtext->ecxt_per_tuple_memory);
4385 oldarrayval = construct_empty_array(arrayelem->elemtypoid);
4387 oldarrayval = (ArrayType *) DatumGetPointer(oldarraydatum);
4390 * Build the modified array value.
4392 newarrayval = array_set(oldarrayval,
4397 arrayelem->arraytyplen,
4398 arrayelem->elemtyplen,
4399 arrayelem->elemtypbyval,
4400 arrayelem->elemtypalign);
4402 MemoryContextSwitchTo(oldcontext);
4405 * Assign the new array to the base variable. It's never NULL
4406 * at this point. Note that if the target is a domain,
4407 * coercing the base array type back up to the domain will
4408 * happen within exec_assign_value.
4411 exec_assign_value(estate, target,
4412 PointerGetDatum(newarrayval),
4413 arrayelem->arraytypoid, isNull);
4418 elog(ERROR, "unrecognized dtype: %d", target->dtype);
4423 * exec_eval_datum Get current value of a PLpgSQL_datum
4425 * The type oid, typmod, value in Datum format, and null flag are returned.
4427 * At present this doesn't handle PLpgSQL_expr or PLpgSQL_arrayelem datums.
4429 * NOTE: caller must not modify the returned value, since it points right
4430 * at the stored value in the case of pass-by-reference datatypes. In some
4431 * cases we have to palloc a return value, and in such cases we put it into
4432 * the estate's short-term memory context.
4435 exec_eval_datum(PLpgSQL_execstate *estate,
4436 PLpgSQL_datum *datum,
4442 MemoryContext oldcontext;
4444 switch (datum->dtype)
4446 case PLPGSQL_DTYPE_VAR:
4448 PLpgSQL_var *var = (PLpgSQL_var *) datum;
4450 *typeid = var->datatype->typoid;
4451 *typetypmod = var->datatype->atttypmod;
4452 *value = var->value;
4453 *isnull = var->isnull;
4457 case PLPGSQL_DTYPE_ROW:
4459 PLpgSQL_row *row = (PLpgSQL_row *) datum;
4462 if (!row->rowtupdesc) /* should not happen */
4463 elog(ERROR, "row variable has no tupdesc");
4464 /* Make sure we have a valid type/typmod setting */
4465 BlessTupleDesc(row->rowtupdesc);
4466 oldcontext = MemoryContextSwitchTo(estate->eval_econtext->ecxt_per_tuple_memory);
4467 tup = make_tuple_from_row(estate, row, row->rowtupdesc);
4468 if (tup == NULL) /* should not happen */
4469 elog(ERROR, "row not compatible with its own tupdesc");
4470 *typeid = row->rowtupdesc->tdtypeid;
4471 *typetypmod = row->rowtupdesc->tdtypmod;
4472 *value = HeapTupleGetDatum(tup);
4474 MemoryContextSwitchTo(oldcontext);
4478 case PLPGSQL_DTYPE_REC:
4480 PLpgSQL_rec *rec = (PLpgSQL_rec *) datum;
4482 if (!HeapTupleIsValid(rec->tup))
4484 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4485 errmsg("record \"%s\" is not assigned yet",
4487 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
4488 Assert(rec->tupdesc != NULL);
4489 /* Make sure we have a valid type/typmod setting */
4490 BlessTupleDesc(rec->tupdesc);
4492 oldcontext = MemoryContextSwitchTo(estate->eval_econtext->ecxt_per_tuple_memory);
4493 *typeid = rec->tupdesc->tdtypeid;
4494 *typetypmod = rec->tupdesc->tdtypmod;
4495 *value = heap_copy_tuple_as_datum(rec->tup, rec->tupdesc);
4497 MemoryContextSwitchTo(oldcontext);
4501 case PLPGSQL_DTYPE_RECFIELD:
4503 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) datum;
4507 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
4508 if (!HeapTupleIsValid(rec->tup))
4510 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4511 errmsg("record \"%s\" is not assigned yet",
4513 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
4514 fno = SPI_fnumber(rec->tupdesc, recfield->fieldname);
4515 if (fno == SPI_ERROR_NOATTRIBUTE)
4517 (errcode(ERRCODE_UNDEFINED_COLUMN),
4518 errmsg("record \"%s\" has no field \"%s\"",
4519 rec->refname, recfield->fieldname)));
4520 *typeid = SPI_gettypeid(rec->tupdesc, fno);
4522 *typetypmod = rec->tupdesc->attrs[fno - 1]->atttypmod;
4525 *value = SPI_getbinval(rec->tup, rec->tupdesc, fno, isnull);
4530 elog(ERROR, "unrecognized dtype: %d", datum->dtype);
4535 * exec_get_datum_type Get datatype of a PLpgSQL_datum
4537 * This is the same logic as in exec_eval_datum, except that it can handle
4538 * some cases where exec_eval_datum has to fail; specifically, we may have
4539 * a tupdesc but no row value for a record variable. (This currently can
4540 * happen only for a trigger's NEW/OLD records.)
4543 exec_get_datum_type(PLpgSQL_execstate *estate,
4544 PLpgSQL_datum *datum)
4548 switch (datum->dtype)
4550 case PLPGSQL_DTYPE_VAR:
4552 PLpgSQL_var *var = (PLpgSQL_var *) datum;
4554 typeid = var->datatype->typoid;
4558 case PLPGSQL_DTYPE_ROW:
4560 PLpgSQL_row *row = (PLpgSQL_row *) datum;
4562 if (!row->rowtupdesc) /* should not happen */
4563 elog(ERROR, "row variable has no tupdesc");
4564 /* Make sure we have a valid type/typmod setting */
4565 BlessTupleDesc(row->rowtupdesc);
4566 typeid = row->rowtupdesc->tdtypeid;
4570 case PLPGSQL_DTYPE_REC:
4572 PLpgSQL_rec *rec = (PLpgSQL_rec *) datum;
4574 if (rec->tupdesc == NULL)
4576 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4577 errmsg("record \"%s\" is not assigned yet",
4579 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
4580 /* Make sure we have a valid type/typmod setting */
4581 BlessTupleDesc(rec->tupdesc);
4582 typeid = rec->tupdesc->tdtypeid;
4586 case PLPGSQL_DTYPE_RECFIELD:
4588 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) datum;
4592 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
4593 if (rec->tupdesc == NULL)
4595 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4596 errmsg("record \"%s\" is not assigned yet",
4598 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
4599 fno = SPI_fnumber(rec->tupdesc, recfield->fieldname);
4600 if (fno == SPI_ERROR_NOATTRIBUTE)
4602 (errcode(ERRCODE_UNDEFINED_COLUMN),
4603 errmsg("record \"%s\" has no field \"%s\"",
4604 rec->refname, recfield->fieldname)));
4605 typeid = SPI_gettypeid(rec->tupdesc, fno);
4610 elog(ERROR, "unrecognized dtype: %d", datum->dtype);
4611 typeid = InvalidOid; /* keep compiler quiet */
4619 * exec_get_datum_type_info Get datatype etc of a PLpgSQL_datum
4621 * An extended version of exec_get_datum_type, which also retrieves the
4622 * typmod and collation of the datum.
4625 exec_get_datum_type_info(PLpgSQL_execstate *estate,
4626 PLpgSQL_datum *datum,
4627 Oid *typeid, int32 *typmod, Oid *collation)
4629 switch (datum->dtype)
4631 case PLPGSQL_DTYPE_VAR:
4633 PLpgSQL_var *var = (PLpgSQL_var *) datum;
4635 *typeid = var->datatype->typoid;
4636 *typmod = var->datatype->atttypmod;
4637 *collation = var->datatype->collation;
4641 case PLPGSQL_DTYPE_ROW:
4643 PLpgSQL_row *row = (PLpgSQL_row *) datum;
4645 if (!row->rowtupdesc) /* should not happen */
4646 elog(ERROR, "row variable has no tupdesc");
4647 /* Make sure we have a valid type/typmod setting */
4648 BlessTupleDesc(row->rowtupdesc);
4649 *typeid = row->rowtupdesc->tdtypeid;
4650 /* do NOT return the mutable typmod of a RECORD variable */
4652 /* composite types are never collatable */
4653 *collation = InvalidOid;
4657 case PLPGSQL_DTYPE_REC:
4659 PLpgSQL_rec *rec = (PLpgSQL_rec *) datum;
4661 if (rec->tupdesc == NULL)
4663 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4664 errmsg("record \"%s\" is not assigned yet",
4666 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
4667 /* Make sure we have a valid type/typmod setting */
4668 BlessTupleDesc(rec->tupdesc);
4669 *typeid = rec->tupdesc->tdtypeid;
4670 /* do NOT return the mutable typmod of a RECORD variable */
4672 /* composite types are never collatable */
4673 *collation = InvalidOid;
4677 case PLPGSQL_DTYPE_RECFIELD:
4679 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) datum;
4683 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
4684 if (rec->tupdesc == NULL)
4686 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4687 errmsg("record \"%s\" is not assigned yet",
4689 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
4690 fno = SPI_fnumber(rec->tupdesc, recfield->fieldname);
4691 if (fno == SPI_ERROR_NOATTRIBUTE)
4693 (errcode(ERRCODE_UNDEFINED_COLUMN),
4694 errmsg("record \"%s\" has no field \"%s\"",
4695 rec->refname, recfield->fieldname)));
4696 *typeid = SPI_gettypeid(rec->tupdesc, fno);
4698 *typmod = rec->tupdesc->attrs[fno - 1]->atttypmod;
4702 *collation = rec->tupdesc->attrs[fno - 1]->attcollation;
4703 else /* no system column types have collation */
4704 *collation = InvalidOid;
4709 elog(ERROR, "unrecognized dtype: %d", datum->dtype);
4710 *typeid = InvalidOid; /* keep compiler quiet */
4712 *collation = InvalidOid;
4718 * exec_eval_integer Evaluate an expression, coerce result to int4
4720 * Note we do not do exec_eval_cleanup here; the caller must do it at
4721 * some later point. (We do this because the caller may be holding the
4722 * results of other, pass-by-reference, expression evaluations, such as
4723 * an array value to be subscripted. Also see notes in exec_eval_simple_expr
4724 * about allocation of the parameter array.)
4728 exec_eval_integer(PLpgSQL_execstate *estate,
4735 exprdatum = exec_eval_expr(estate, expr, isNull, &exprtypeid);
4736 exprdatum = exec_simple_cast_value(estate, exprdatum, exprtypeid,
4739 return DatumGetInt32(exprdatum);
4743 * exec_eval_boolean Evaluate an expression, coerce result to bool
4745 * Note we do not do exec_eval_cleanup here; the caller must do it at
4750 exec_eval_boolean(PLpgSQL_execstate *estate,
4757 exprdatum = exec_eval_expr(estate, expr, isNull, &exprtypeid);
4758 exprdatum = exec_simple_cast_value(estate, exprdatum, exprtypeid,
4761 return DatumGetBool(exprdatum);
4765 * exec_eval_expr Evaluate an expression and return
4768 * NOTE: caller must do exec_eval_cleanup when done with the Datum.
4772 exec_eval_expr(PLpgSQL_execstate *estate,
4781 * If first time through, create a plan for this expression.
4783 if (expr->plan == NULL)
4784 exec_prepare_plan(estate, expr, 0);
4787 * If this is a simple expression, bypass SPI and use the executor
4790 if (exec_eval_simple_expr(estate, expr, &result, isNull, rettype))
4794 * Else do it the hard way via exec_run_select
4796 rc = exec_run_select(estate, expr, 2, NULL);
4797 if (rc != SPI_OK_SELECT)
4799 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
4800 errmsg("query \"%s\" did not return data", expr->query)));
4803 * Check that the expression returns exactly one column...
4805 if (estate->eval_tuptable->tupdesc->natts != 1)
4807 (errcode(ERRCODE_SYNTAX_ERROR),
4808 errmsg_plural("query \"%s\" returned %d column",
4809 "query \"%s\" returned %d columns",
4810 estate->eval_tuptable->tupdesc->natts,
4812 estate->eval_tuptable->tupdesc->natts)));
4815 * ... and get the column's datatype.
4817 *rettype = SPI_gettypeid(estate->eval_tuptable->tupdesc, 1);
4820 * If there are no rows selected, the result is a NULL of that type.
4822 if (estate->eval_processed == 0)
4829 * Check that the expression returned no more than one row.
4831 if (estate->eval_processed != 1)
4833 (errcode(ERRCODE_CARDINALITY_VIOLATION),
4834 errmsg("query \"%s\" returned more than one row",
4838 * Return the single result Datum.
4840 return SPI_getbinval(estate->eval_tuptable->vals[0],
4841 estate->eval_tuptable->tupdesc, 1, isNull);
4846 * exec_run_select Execute a select query
4850 exec_run_select(PLpgSQL_execstate *estate,
4851 PLpgSQL_expr *expr, long maxtuples, Portal *portalP)
4853 ParamListInfo paramLI;
4857 * On the first call for this expression generate the plan
4859 if (expr->plan == NULL)
4860 exec_prepare_plan(estate, expr, 0);
4863 * Set up ParamListInfo (hook function and possibly data values)
4865 paramLI = setup_param_list(estate, expr);
4868 * If a portal was requested, put the query into the portal
4870 if (portalP != NULL)
4872 *portalP = SPI_cursor_open_with_paramlist(NULL, expr->plan,
4874 estate->readonly_func);
4875 if (*portalP == NULL)
4876 elog(ERROR, "could not open implicit cursor for query \"%s\": %s",
4877 expr->query, SPI_result_code_string(SPI_result));
4880 return SPI_OK_CURSOR;
4886 rc = SPI_execute_plan_with_paramlist(expr->plan, paramLI,
4887 estate->readonly_func, maxtuples);
4888 if (rc != SPI_OK_SELECT)
4890 (errcode(ERRCODE_SYNTAX_ERROR),
4891 errmsg("query \"%s\" is not a SELECT", expr->query)));
4893 /* Save query results for eventual cleanup */
4894 Assert(estate->eval_tuptable == NULL);
4895 estate->eval_tuptable = SPI_tuptable;
4896 estate->eval_processed = SPI_processed;
4897 estate->eval_lastoid = SPI_lastoid;
4907 * exec_for_query --- execute body of FOR loop for each row from a portal
4909 * Used by exec_stmt_fors, exec_stmt_forc and exec_stmt_dynfors
4912 exec_for_query(PLpgSQL_execstate *estate, PLpgSQL_stmt_forq *stmt,
4913 Portal portal, bool prefetch_ok)
4915 PLpgSQL_rec *rec = NULL;
4916 PLpgSQL_row *row = NULL;
4917 SPITupleTable *tuptab;
4919 int rc = PLPGSQL_RC_OK;
4923 * Determine if we assign to a record or a row
4925 if (stmt->rec != NULL)
4926 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->dno]);
4927 else if (stmt->row != NULL)
4928 row = (PLpgSQL_row *) (estate->datums[stmt->row->dno]);
4930 elog(ERROR, "unsupported target");
4933 * Make sure the portal doesn't get closed by the user statements we
4939 * Fetch the initial tuple(s). If prefetching is allowed then we grab a
4940 * few more rows to avoid multiple trips through executor startup
4943 SPI_cursor_fetch(portal, true, prefetch_ok ? 10 : 1);
4944 tuptab = SPI_tuptable;
4948 * If the query didn't return any rows, set the target to NULL and fall
4949 * through with found = false.
4953 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
4954 exec_eval_cleanup(estate);
4957 found = true; /* processed at least one tuple */
4966 for (i = 0; i < n; i++)
4969 * Assign the tuple to the target
4971 exec_move_row(estate, rec, row, tuptab->vals[i], tuptab->tupdesc);
4972 exec_eval_cleanup(estate);
4975 * Execute the statements
4977 rc = exec_stmts(estate, stmt->body);
4979 if (rc != PLPGSQL_RC_OK)
4981 if (rc == PLPGSQL_RC_EXIT)
4983 if (estate->exitlabel == NULL)
4985 /* unlabelled exit, so exit the current loop */
4988 else if (stmt->label != NULL &&
4989 strcmp(stmt->label, estate->exitlabel) == 0)
4991 /* label matches this loop, so exit loop */
4992 estate->exitlabel = NULL;
4997 * otherwise, we processed a labelled exit that does not
4998 * match the current statement's label, if any; return
4999 * RC_EXIT so that the EXIT continues to recurse upward.
5002 else if (rc == PLPGSQL_RC_CONTINUE)
5004 if (estate->exitlabel == NULL)
5006 /* unlabelled continue, so re-run the current loop */
5010 else if (stmt->label != NULL &&
5011 strcmp(stmt->label, estate->exitlabel) == 0)
5013 /* label matches this loop, so re-run loop */
5014 estate->exitlabel = NULL;
5020 * otherwise, we process a labelled continue that does not
5021 * match the current statement's label, if any; return
5022 * RC_CONTINUE so that the CONTINUE will propagate up the
5028 * We're aborting the loop. Need a goto to get out of two
5035 SPI_freetuptable(tuptab);
5038 * Fetch more tuples. If prefetching is allowed, grab 50 at a time.
5040 SPI_cursor_fetch(portal, true, prefetch_ok ? 50 : 1);
5041 tuptab = SPI_tuptable;
5048 * Release last group of tuples (if any)
5050 SPI_freetuptable(tuptab);
5052 UnpinPortal(portal);
5055 * Set the FOUND variable to indicate the result of executing the loop
5056 * (namely, whether we looped one or more times). This must be set last so
5057 * that it does not interfere with the value of the FOUND variable inside
5058 * the loop processing itself.
5060 exec_set_found(estate, found);
5067 * exec_eval_simple_expr - Evaluate a simple expression returning
5068 * a Datum by directly calling ExecEvalExpr().
5070 * If successful, store results into *result, *isNull, *rettype and return
5071 * TRUE. If the expression cannot be handled by simple evaluation,
5074 * Because we only store one execution tree for a simple expression, we
5075 * can't handle recursion cases. So, if we see the tree is already busy
5076 * with an evaluation in the current xact, we just return FALSE and let the
5077 * caller run the expression the hard way. (Other alternatives such as
5078 * creating a new tree for a recursive call either introduce memory leaks,
5079 * or add enough bookkeeping to be doubtful wins anyway.) Another case that
5080 * is covered by the expr_simple_in_use test is where a previous execution
5081 * of the tree was aborted by an error: the tree may contain bogus state
5082 * so we dare not re-use it.
5084 * It is possible though unlikely for a simple expression to become non-simple
5085 * (consider for example redefining a trivial view). We must handle that for
5086 * correctness; fortunately it's normally inexpensive to call
5087 * SPI_plan_get_cached_plan for a simple expression. We do not consider the
5088 * other direction (non-simple expression becoming simple) because we'll still
5089 * give correct results if that happens, and it's unlikely to be worth the
5092 * Note: if pass-by-reference, the result is in the eval_econtext's
5093 * temporary memory context. It will be freed when exec_eval_cleanup
5098 exec_eval_simple_expr(PLpgSQL_execstate *estate,
5104 ExprContext *econtext = estate->eval_econtext;
5105 LocalTransactionId curlxid = MyProc->lxid;
5107 ParamListInfo paramLI;
5108 PLpgSQL_expr *save_cur_expr;
5109 MemoryContext oldcontext;
5112 * Forget it if expression wasn't simple before.
5114 if (expr->expr_simple_expr == NULL)
5118 * If expression is in use in current xact, don't touch it.
5120 if (expr->expr_simple_in_use && expr->expr_simple_lxid == curlxid)
5124 * Revalidate cached plan, so that we will notice if it became stale. (We
5125 * need to hold a refcount while using the plan, anyway.)
5127 cplan = SPI_plan_get_cached_plan(expr->plan);
5130 * We can't get a failure here, because the number of CachedPlanSources in
5131 * the SPI plan can't change from what exec_simple_check_plan saw; it's a
5132 * property of the raw parsetree generated from the query text.
5134 Assert(cplan != NULL);
5136 if (cplan->generation != expr->expr_simple_generation)
5138 /* It got replanned ... is it still simple? */
5139 exec_simple_recheck_plan(expr, cplan);
5140 if (expr->expr_simple_expr == NULL)
5142 /* Ooops, release refcount and fail */
5143 ReleaseCachedPlan(cplan, true);
5149 * Pass back previously-determined result type.
5151 *rettype = expr->expr_simple_type;
5154 * Prepare the expression for execution, if it's not been done already in
5155 * the current transaction. (This will be forced to happen if we called
5156 * exec_simple_recheck_plan above.)
5158 if (expr->expr_simple_lxid != curlxid)
5160 oldcontext = MemoryContextSwitchTo(estate->simple_eval_estate->es_query_cxt);
5161 expr->expr_simple_state = ExecInitExpr(expr->expr_simple_expr, NULL);
5162 expr->expr_simple_in_use = false;
5163 expr->expr_simple_lxid = curlxid;
5164 MemoryContextSwitchTo(oldcontext);
5168 * We have to do some of the things SPI_execute_plan would do, in
5169 * particular advance the snapshot if we are in a non-read-only function.
5170 * Without this, stable functions within the expression would fail to see
5171 * updates made so far by our own function.
5175 oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
5176 if (!estate->readonly_func)
5178 CommandCounterIncrement();
5179 PushActiveSnapshot(GetTransactionSnapshot());
5183 * Create the param list in econtext's temporary memory context. We won't
5184 * need to free it explicitly, since it will go away at the next reset of
5187 * Just for paranoia's sake, save and restore the prior value of
5188 * estate->cur_expr, which setup_param_list() sets.
5190 save_cur_expr = estate->cur_expr;
5192 paramLI = setup_param_list(estate, expr);
5193 econtext->ecxt_param_list_info = paramLI;
5196 * Mark expression as busy for the duration of the ExecEvalExpr call.
5198 expr->expr_simple_in_use = true;
5201 * Finally we can call the executor to evaluate the expression
5203 *result = ExecEvalExpr(expr->expr_simple_state,
5208 /* Assorted cleanup */
5209 expr->expr_simple_in_use = false;
5211 estate->cur_expr = save_cur_expr;
5213 if (!estate->readonly_func)
5214 PopActiveSnapshot();
5216 MemoryContextSwitchTo(oldcontext);
5221 * Now we can release our refcount on the cached plan.
5223 ReleaseCachedPlan(cplan, true);
5233 * Create a ParamListInfo to pass to SPI
5235 * We fill in the values for any expression parameters that are plain
5236 * PLpgSQL_var datums; these are cheap and safe to evaluate, and by setting
5237 * them with PARAM_FLAG_CONST flags, we allow the planner to use those values
5238 * in custom plans. However, parameters that are not plain PLpgSQL_vars
5239 * should not be evaluated here, because they could throw errors (for example
5240 * "no such record field") and we do not want that to happen in a part of
5241 * the expression that might never be evaluated at runtime. To handle those
5242 * parameters, we set up a paramFetch hook for the executor to call when it
5243 * wants a not-presupplied value.
5245 * The result is a locally palloc'd array that should be pfree'd after use;
5246 * but note it can be NULL.
5248 static ParamListInfo
5249 setup_param_list(PLpgSQL_execstate *estate, PLpgSQL_expr *expr)
5251 ParamListInfo paramLI;
5254 * We must have created the SPIPlan already (hence, query text has been
5255 * parsed/analyzed at least once); else we cannot rely on expr->paramnos.
5257 Assert(expr->plan != NULL);
5260 * Could we re-use these arrays instead of palloc'ing a new one each time?
5261 * However, we'd have to re-fill the array each time anyway, since new
5262 * values might have been assigned to the variables.
5264 if (!bms_is_empty(expr->paramnos))
5269 paramLI = (ParamListInfo)
5270 palloc0(offsetof(ParamListInfoData, params) +
5271 estate->ndatums * sizeof(ParamExternData));
5272 paramLI->paramFetch = plpgsql_param_fetch;
5273 paramLI->paramFetchArg = (void *) estate;
5274 paramLI->parserSetup = (ParserSetupHook) plpgsql_parser_setup;
5275 paramLI->parserSetupArg = (void *) expr;
5276 paramLI->numParams = estate->ndatums;
5278 /* Instantiate values for "safe" parameters of the expression */
5279 tmpset = bms_copy(expr->paramnos);
5280 while ((dno = bms_first_member(tmpset)) >= 0)
5282 PLpgSQL_datum *datum = estate->datums[dno];
5284 if (datum->dtype == PLPGSQL_DTYPE_VAR)
5286 PLpgSQL_var *var = (PLpgSQL_var *) datum;
5287 ParamExternData *prm = ¶mLI->params[dno];
5289 prm->value = var->value;
5290 prm->isnull = var->isnull;
5291 prm->pflags = PARAM_FLAG_CONST;
5292 prm->ptype = var->datatype->typoid;
5298 * Set up link to active expr where the hook functions can find it.
5299 * Callers must save and restore cur_expr if there is any chance that
5300 * they are interrupting an active use of parameters.
5302 estate->cur_expr = expr;
5305 * Also make sure this is set before parser hooks need it. There is
5306 * no need to save and restore, since the value is always correct once
5307 * set. (Should be set already, but let's be sure.)
5309 expr->func = estate->func;
5314 * Expression requires no parameters. Be sure we represent this case
5315 * as a NULL ParamListInfo, so that plancache.c knows there is no
5316 * point in a custom plan.
5324 * plpgsql_param_fetch paramFetch callback for dynamic parameter fetch
5327 plpgsql_param_fetch(ParamListInfo params, int paramid)
5330 PLpgSQL_execstate *estate;
5332 PLpgSQL_datum *datum;
5333 ParamExternData *prm;
5336 /* paramid's are 1-based, but dnos are 0-based */
5338 Assert(dno >= 0 && dno < params->numParams);
5340 /* fetch back the hook data */
5341 estate = (PLpgSQL_execstate *) params->paramFetchArg;
5342 expr = estate->cur_expr;
5343 Assert(params->numParams == estate->ndatums);
5346 * Do nothing if asked for a value that's not supposed to be used by this
5347 * SQL expression. This avoids unwanted evaluations when functions such
5348 * as copyParamList try to materialize all the values.
5350 if (!bms_is_member(dno, expr->paramnos))
5353 /* OK, evaluate the value and store into the appropriate paramlist slot */
5354 datum = estate->datums[dno];
5355 prm = ¶ms->params[dno];
5356 exec_eval_datum(estate, datum,
5357 &prm->ptype, &prmtypmod,
5358 &prm->value, &prm->isnull);
5363 * exec_move_row Move one tuple's values into a record or row
5365 * Since this uses exec_assign_value, caller should eventually call
5366 * exec_eval_cleanup to prevent long-term memory leaks.
5370 exec_move_row(PLpgSQL_execstate *estate,
5373 HeapTuple tup, TupleDesc tupdesc)
5376 * Record is simple - just copy the tuple and its descriptor into the
5382 * Copy input first, just in case it is pointing at variable's value
5384 if (HeapTupleIsValid(tup))
5385 tup = heap_copytuple(tup);
5388 /* If we have a tupdesc but no data, form an all-nulls tuple */
5391 nulls = (bool *) palloc(tupdesc->natts * sizeof(bool));
5392 memset(nulls, true, tupdesc->natts * sizeof(bool));
5394 tup = heap_form_tuple(tupdesc, NULL, nulls);
5400 tupdesc = CreateTupleDescCopy(tupdesc);
5402 /* Free the old value ... */
5405 heap_freetuple(rec->tup);
5406 rec->freetup = false;
5408 if (rec->freetupdesc)
5410 FreeTupleDesc(rec->tupdesc);
5411 rec->freetupdesc = false;
5414 /* ... and install the new */
5415 if (HeapTupleIsValid(tup))
5418 rec->freetup = true;
5425 rec->tupdesc = tupdesc;
5426 rec->freetupdesc = true;
5429 rec->tupdesc = NULL;
5435 * Row is a bit more complicated in that we assign the individual
5436 * attributes of the tuple to the variables the row points to.
5438 * NOTE: this code used to demand row->nfields ==
5439 * HeapTupleHeaderGetNatts(tup->t_data), but that's wrong. The tuple
5440 * might have more fields than we expected if it's from an
5441 * inheritance-child table of the current table, or it might have fewer if
5442 * the table has had columns added by ALTER TABLE. Ignore extra columns
5443 * and assume NULL for missing columns, the same as heap_getattr would do.
5444 * We also have to skip over dropped columns in either the source or
5447 * If we have no tuple data at all, we'll assign NULL to all columns of
5452 int td_natts = tupdesc ? tupdesc->natts : 0;
5457 if (HeapTupleIsValid(tup))
5458 t_natts = HeapTupleHeaderGetNatts(tup->t_data);
5463 for (fnum = 0; fnum < row->nfields; fnum++)
5470 if (row->varnos[fnum] < 0)
5471 continue; /* skip dropped column in row struct */
5473 var = (PLpgSQL_var *) (estate->datums[row->varnos[fnum]]);
5475 while (anum < td_natts && tupdesc->attrs[anum]->attisdropped)
5476 anum++; /* skip dropped column in tuple */
5478 if (anum < td_natts)
5481 value = SPI_getbinval(tup, tupdesc, anum + 1, &isnull);
5487 valtype = SPI_gettypeid(tupdesc, anum + 1);
5496 * InvalidOid is OK because exec_assign_value doesn't care
5497 * about the type of a source NULL
5499 valtype = InvalidOid;
5502 exec_assign_value(estate, (PLpgSQL_datum *) var,
5503 value, valtype, &isnull);
5509 elog(ERROR, "unsupported target");
5513 * make_tuple_from_row Make a tuple from the values of a row object
5515 * A NULL return indicates rowtype mismatch; caller must raise suitable error
5519 make_tuple_from_row(PLpgSQL_execstate *estate,
5523 int natts = tupdesc->natts;
5529 if (natts != row->nfields)
5532 dvalues = (Datum *) palloc0(natts * sizeof(Datum));
5533 nulls = (bool *) palloc(natts * sizeof(bool));
5535 for (i = 0; i < natts; i++)
5540 if (tupdesc->attrs[i]->attisdropped)
5542 nulls[i] = true; /* leave the column as null */
5545 if (row->varnos[i] < 0) /* should not happen */
5546 elog(ERROR, "dropped rowtype entry for non-dropped column");
5548 exec_eval_datum(estate, estate->datums[row->varnos[i]],
5549 &fieldtypeid, &fieldtypmod,
5550 &dvalues[i], &nulls[i]);
5551 if (fieldtypeid != tupdesc->attrs[i]->atttypid)
5553 /* XXX should we insist on typmod match, too? */
5556 tuple = heap_form_tuple(tupdesc, dvalues, nulls);
5565 * get_tuple_from_datum extract a tuple from a composite Datum
5567 * Returns a freshly palloc'd HeapTuple.
5569 * Note: it's caller's responsibility to be sure value is of composite type.
5573 get_tuple_from_datum(Datum value)
5575 HeapTupleHeader td = DatumGetHeapTupleHeader(value);
5576 HeapTupleData tmptup;
5578 /* Build a temporary HeapTuple control structure */
5579 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
5580 ItemPointerSetInvalid(&(tmptup.t_self));
5581 tmptup.t_tableOid = InvalidOid;
5584 /* Build a copy and return it */
5585 return heap_copytuple(&tmptup);
5589 * get_tupdesc_from_datum get a tuple descriptor for a composite Datum
5591 * Returns a pointer to the TupleDesc of the tuple's rowtype.
5592 * Caller is responsible for calling ReleaseTupleDesc when done with it.
5594 * Note: it's caller's responsibility to be sure value is of composite type.
5598 get_tupdesc_from_datum(Datum value)
5600 HeapTupleHeader td = DatumGetHeapTupleHeader(value);
5604 /* Extract rowtype info and find a tupdesc */
5605 tupType = HeapTupleHeaderGetTypeId(td);
5606 tupTypmod = HeapTupleHeaderGetTypMod(td);
5607 return lookup_rowtype_tupdesc(tupType, tupTypmod);
5611 * exec_move_row_from_datum Move a composite Datum into a record or row
5613 * This is equivalent to get_tuple_from_datum() followed by exec_move_row(),
5614 * but we avoid constructing an intermediate physical copy of the tuple.
5618 exec_move_row_from_datum(PLpgSQL_execstate *estate,
5623 HeapTupleHeader td = DatumGetHeapTupleHeader(value);
5627 HeapTupleData tmptup;
5629 /* Extract rowtype info and find a tupdesc */
5630 tupType = HeapTupleHeaderGetTypeId(td);
5631 tupTypmod = HeapTupleHeaderGetTypMod(td);
5632 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
5634 /* Build a temporary HeapTuple control structure */
5635 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
5636 ItemPointerSetInvalid(&(tmptup.t_self));
5637 tmptup.t_tableOid = InvalidOid;
5641 exec_move_row(estate, rec, row, &tmptup, tupdesc);
5643 /* Release tupdesc usage count */
5644 ReleaseTupleDesc(tupdesc);
5648 * convert_value_to_string Convert a non-null Datum to C string
5650 * Note: the result is in the estate's eval_econtext, and will be cleared
5651 * by the next exec_eval_cleanup() call. The invoked output function might
5652 * leave additional cruft there as well, so just pfree'ing the result string
5653 * would not be enough to avoid memory leaks if we did not do it like this.
5654 * In most usages the Datum being passed in is also in that context (if
5655 * pass-by-reference) and so an exec_eval_cleanup() call is needed anyway.
5657 * Note: not caching the conversion function lookup is bad for performance.
5661 convert_value_to_string(PLpgSQL_execstate *estate, Datum value, Oid valtype)
5664 MemoryContext oldcontext;
5668 oldcontext = MemoryContextSwitchTo(estate->eval_econtext->ecxt_per_tuple_memory);
5669 getTypeOutputInfo(valtype, &typoutput, &typIsVarlena);
5670 result = OidOutputFunctionCall(typoutput, value);
5671 MemoryContextSwitchTo(oldcontext);
5677 * exec_cast_value Cast a value if required
5679 * Note: the estate's eval_econtext is used for temporary storage, and may
5680 * also contain the result Datum if we have to do a conversion to a pass-
5681 * by-reference data type. Be sure to do an exec_eval_cleanup() call when
5682 * done with the result.
5686 exec_cast_value(PLpgSQL_execstate *estate,
5687 Datum value, Oid valtype,
5695 * If the type of the given value isn't what's requested, convert it.
5697 if (valtype != reqtype || reqtypmod != -1)
5699 MemoryContext oldcontext;
5701 oldcontext = MemoryContextSwitchTo(estate->eval_econtext->ecxt_per_tuple_memory);
5706 extval = convert_value_to_string(estate, value, valtype);
5707 value = InputFunctionCall(reqinput, extval,
5708 reqtypioparam, reqtypmod);
5712 value = InputFunctionCall(reqinput, NULL,
5713 reqtypioparam, reqtypmod);
5715 MemoryContextSwitchTo(oldcontext);
5722 * exec_simple_cast_value Cast a value if required
5724 * As above, but need not supply details about target type. Note that this
5725 * is slower than exec_cast_value with cached type info, and so should be
5726 * avoided in heavily used code paths.
5730 exec_simple_cast_value(PLpgSQL_execstate *estate,
5731 Datum value, Oid valtype,
5732 Oid reqtype, int32 reqtypmod,
5735 if (valtype != reqtype || reqtypmod != -1)
5739 FmgrInfo finfo_input;
5741 getTypeInputInfo(reqtype, &typinput, &typioparam);
5743 fmgr_info(typinput, &finfo_input);
5745 value = exec_cast_value(estate,
5760 * exec_simple_check_node - Recursively check if an expression
5761 * is made only of simple things we can
5762 * hand out directly to ExecEvalExpr()
5763 * instead of calling SPI.
5767 exec_simple_check_node(Node *node)
5772 switch (nodeTag(node))
5782 ArrayRef *expr = (ArrayRef *) node;
5784 if (!exec_simple_check_node((Node *) expr->refupperindexpr))
5786 if (!exec_simple_check_node((Node *) expr->reflowerindexpr))
5788 if (!exec_simple_check_node((Node *) expr->refexpr))
5790 if (!exec_simple_check_node((Node *) expr->refassgnexpr))
5798 FuncExpr *expr = (FuncExpr *) node;
5800 if (expr->funcretset)
5802 if (!exec_simple_check_node((Node *) expr->args))
5810 OpExpr *expr = (OpExpr *) node;
5814 if (!exec_simple_check_node((Node *) expr->args))
5820 case T_DistinctExpr:
5822 DistinctExpr *expr = (DistinctExpr *) node;
5826 if (!exec_simple_check_node((Node *) expr->args))
5834 NullIfExpr *expr = (NullIfExpr *) node;
5838 if (!exec_simple_check_node((Node *) expr->args))
5844 case T_ScalarArrayOpExpr:
5846 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
5848 if (!exec_simple_check_node((Node *) expr->args))
5856 BoolExpr *expr = (BoolExpr *) node;
5858 if (!exec_simple_check_node((Node *) expr->args))
5865 return exec_simple_check_node((Node *) ((FieldSelect *) node)->arg);
5869 FieldStore *expr = (FieldStore *) node;
5871 if (!exec_simple_check_node((Node *) expr->arg))
5873 if (!exec_simple_check_node((Node *) expr->newvals))
5880 return exec_simple_check_node((Node *) ((RelabelType *) node)->arg);
5883 return exec_simple_check_node((Node *) ((CoerceViaIO *) node)->arg);
5885 case T_ArrayCoerceExpr:
5886 return exec_simple_check_node((Node *) ((ArrayCoerceExpr *) node)->arg);
5888 case T_ConvertRowtypeExpr:
5889 return exec_simple_check_node((Node *) ((ConvertRowtypeExpr *) node)->arg);
5893 CaseExpr *expr = (CaseExpr *) node;
5895 if (!exec_simple_check_node((Node *) expr->arg))
5897 if (!exec_simple_check_node((Node *) expr->args))
5899 if (!exec_simple_check_node((Node *) expr->defresult))
5907 CaseWhen *when = (CaseWhen *) node;
5909 if (!exec_simple_check_node((Node *) when->expr))
5911 if (!exec_simple_check_node((Node *) when->result))
5917 case T_CaseTestExpr:
5922 ArrayExpr *expr = (ArrayExpr *) node;
5924 if (!exec_simple_check_node((Node *) expr->elements))
5932 RowExpr *expr = (RowExpr *) node;
5934 if (!exec_simple_check_node((Node *) expr->args))
5940 case T_RowCompareExpr:
5942 RowCompareExpr *expr = (RowCompareExpr *) node;
5944 if (!exec_simple_check_node((Node *) expr->largs))
5946 if (!exec_simple_check_node((Node *) expr->rargs))
5952 case T_CoalesceExpr:
5954 CoalesceExpr *expr = (CoalesceExpr *) node;
5956 if (!exec_simple_check_node((Node *) expr->args))
5964 MinMaxExpr *expr = (MinMaxExpr *) node;
5966 if (!exec_simple_check_node((Node *) expr->args))
5974 XmlExpr *expr = (XmlExpr *) node;
5976 if (!exec_simple_check_node((Node *) expr->named_args))
5978 if (!exec_simple_check_node((Node *) expr->args))
5985 return exec_simple_check_node((Node *) ((NullTest *) node)->arg);
5988 return exec_simple_check_node((Node *) ((BooleanTest *) node)->arg);
5990 case T_CoerceToDomain:
5991 return exec_simple_check_node((Node *) ((CoerceToDomain *) node)->arg);
5993 case T_CoerceToDomainValue:
5998 List *expr = (List *) node;
6003 if (!exec_simple_check_node(lfirst(l)))
6017 * exec_simple_check_plan - Check if a plan is simple enough to
6018 * be evaluated by ExecEvalExpr() instead
6023 exec_simple_check_plan(PLpgSQL_expr *expr)
6026 CachedPlanSource *plansource;
6031 * Initialize to "not simple", and remember the plan generation number we
6032 * last checked. (If we don't get as far as obtaining a plan to check, we
6033 * just leave expr_simple_generation set to 0.)
6035 expr->expr_simple_expr = NULL;
6036 expr->expr_simple_generation = 0;
6039 * We can only test queries that resulted in exactly one CachedPlanSource
6041 plansources = SPI_plan_get_plan_sources(expr->plan);
6042 if (list_length(plansources) != 1)
6044 plansource = (CachedPlanSource *) linitial(plansources);
6047 * Do some checking on the analyzed-and-rewritten form of the query. These
6048 * checks are basically redundant with the tests in
6049 * exec_simple_recheck_plan, but the point is to avoid building a plan if
6050 * possible. Since this function is only called immediately after
6051 * creating the CachedPlanSource, we need not worry about the query being
6056 * 1. There must be one single querytree.
6058 if (list_length(plansource->query_list) != 1)
6060 query = (Query *) linitial(plansource->query_list);
6063 * 2. It must be a plain SELECT query without any input tables
6065 if (!IsA(query, Query))
6067 if (query->commandType != CMD_SELECT)
6069 if (query->rtable != NIL)
6073 * 3. Can't have any subplans, aggregates, qual clauses either
6075 if (query->hasAggs ||
6076 query->hasWindowFuncs ||
6077 query->hasSubLinks ||
6078 query->hasForUpdate ||
6080 query->jointree->quals ||
6081 query->groupClause ||
6082 query->havingQual ||
6083 query->windowClause ||
6084 query->distinctClause ||
6085 query->sortClause ||
6086 query->limitOffset ||
6087 query->limitCount ||
6088 query->setOperations)
6092 * 4. The query must have a single attribute as result
6094 if (list_length(query->targetList) != 1)
6098 * OK, it seems worth constructing a plan for more careful checking.
6101 /* Get the generic plan for the query */
6102 cplan = SPI_plan_get_cached_plan(expr->plan);
6104 /* Can't fail, because we checked for a single CachedPlanSource above */
6105 Assert(cplan != NULL);
6107 /* Share the remaining work with recheck code path */
6108 exec_simple_recheck_plan(expr, cplan);
6110 /* Release our plan refcount */
6111 ReleaseCachedPlan(cplan, true);
6115 * exec_simple_recheck_plan --- check for simple plan once we have CachedPlan
6118 exec_simple_recheck_plan(PLpgSQL_expr *expr, CachedPlan *cplan)
6125 * Initialize to "not simple", and remember the plan generation number we
6128 expr->expr_simple_expr = NULL;
6129 expr->expr_simple_generation = cplan->generation;
6132 * 1. There must be one single plantree
6134 if (list_length(cplan->stmt_list) != 1)
6136 stmt = (PlannedStmt *) linitial(cplan->stmt_list);
6139 * 2. It must be a RESULT plan --> no scan's required
6141 if (!IsA(stmt, PlannedStmt))
6143 if (stmt->commandType != CMD_SELECT)
6145 plan = stmt->planTree;
6146 if (!IsA(plan, Result))
6150 * 3. Can't have any subplan or qual clause, either
6152 if (plan->lefttree != NULL ||
6153 plan->righttree != NULL ||
6154 plan->initPlan != NULL ||
6155 plan->qual != NULL ||
6156 ((Result *) plan)->resconstantqual != NULL)
6160 * 4. The plan must have a single attribute as result
6162 if (list_length(plan->targetlist) != 1)
6165 tle = (TargetEntry *) linitial(plan->targetlist);
6168 * 5. Check that all the nodes in the expression are non-scary.
6170 if (!exec_simple_check_node((Node *) tle->expr))
6174 * Yes - this is a simple expression. Mark it as such, and initialize
6175 * state to "not valid in current transaction".
6177 expr->expr_simple_expr = tle->expr;
6178 expr->expr_simple_state = NULL;
6179 expr->expr_simple_in_use = false;
6180 expr->expr_simple_lxid = InvalidLocalTransactionId;
6181 /* Also stash away the expression result type */
6182 expr->expr_simple_type = exprType((Node *) tle->expr);
6186 * exec_set_found Set the global found variable to true/false
6190 exec_set_found(PLpgSQL_execstate *estate, bool state)
6194 var = (PLpgSQL_var *) (estate->datums[estate->found_varno]);
6195 var->value = BoolGetDatum(state);
6196 var->isnull = false;
6200 * plpgsql_create_econtext --- create an eval_econtext for the current function
6202 * We may need to create a new shared_simple_eval_estate too, if there's not
6203 * one already for the current transaction. The EState will be cleaned up at
6207 plpgsql_create_econtext(PLpgSQL_execstate *estate)
6209 SimpleEcontextStackEntry *entry;
6212 * Create an EState for evaluation of simple expressions, if there's not
6213 * one already in the current transaction. The EState is made a child of
6214 * TopTransactionContext so it will have the right lifespan.
6216 * Note that this path is never taken when executing a DO block; the
6217 * required EState was already made by plpgsql_inline_handler.
6219 if (estate->simple_eval_estate == NULL)
6221 MemoryContext oldcontext;
6223 Assert(shared_simple_eval_estate == NULL);
6224 oldcontext = MemoryContextSwitchTo(TopTransactionContext);
6225 shared_simple_eval_estate = CreateExecutorState();
6226 estate->simple_eval_estate = shared_simple_eval_estate;
6227 MemoryContextSwitchTo(oldcontext);
6231 * Create a child econtext for the current function.
6233 estate->eval_econtext = CreateExprContext(estate->simple_eval_estate);
6236 * Make a stack entry so we can clean up the econtext at subxact end.
6237 * Stack entries are kept in TopTransactionContext for simplicity.
6239 entry = (SimpleEcontextStackEntry *)
6240 MemoryContextAlloc(TopTransactionContext,
6241 sizeof(SimpleEcontextStackEntry));
6243 entry->stack_econtext = estate->eval_econtext;
6244 entry->xact_subxid = GetCurrentSubTransactionId();
6246 entry->next = simple_econtext_stack;
6247 simple_econtext_stack = entry;
6251 * plpgsql_destroy_econtext --- destroy function's econtext
6253 * We check that it matches the top stack entry, and destroy the stack
6254 * entry along with the context.
6257 plpgsql_destroy_econtext(PLpgSQL_execstate *estate)
6259 SimpleEcontextStackEntry *next;
6261 Assert(simple_econtext_stack != NULL);
6262 Assert(simple_econtext_stack->stack_econtext == estate->eval_econtext);
6264 next = simple_econtext_stack->next;
6265 pfree(simple_econtext_stack);
6266 simple_econtext_stack = next;
6268 FreeExprContext(estate->eval_econtext, true);
6269 estate->eval_econtext = NULL;
6273 * plpgsql_xact_cb --- post-transaction-commit-or-abort cleanup
6275 * If a simple-expression EState was created in the current transaction,
6276 * it has to be cleaned up.
6279 plpgsql_xact_cb(XactEvent event, void *arg)
6282 * If we are doing a clean transaction shutdown, free the EState (so that
6283 * any remaining resources will be released correctly). In an abort, we
6284 * expect the regular abort recovery procedures to release everything of
6287 if (event == XACT_EVENT_COMMIT || event == XACT_EVENT_PREPARE)
6289 /* Shouldn't be any econtext stack entries left at commit */
6290 Assert(simple_econtext_stack == NULL);
6292 if (shared_simple_eval_estate)
6293 FreeExecutorState(shared_simple_eval_estate);
6294 shared_simple_eval_estate = NULL;
6296 else if (event == XACT_EVENT_ABORT)
6298 simple_econtext_stack = NULL;
6299 shared_simple_eval_estate = NULL;
6304 * plpgsql_subxact_cb --- post-subtransaction-commit-or-abort cleanup
6306 * Make sure any simple-expression econtexts created in the current
6307 * subtransaction get cleaned up. We have to do this explicitly because
6308 * no other code knows which econtexts belong to which level of subxact.
6311 plpgsql_subxact_cb(SubXactEvent event, SubTransactionId mySubid,
6312 SubTransactionId parentSubid, void *arg)
6314 if (event == SUBXACT_EVENT_COMMIT_SUB || event == SUBXACT_EVENT_ABORT_SUB)
6316 while (simple_econtext_stack != NULL &&
6317 simple_econtext_stack->xact_subxid == mySubid)
6319 SimpleEcontextStackEntry *next;
6321 FreeExprContext(simple_econtext_stack->stack_econtext,
6322 (event == SUBXACT_EVENT_COMMIT_SUB));
6323 next = simple_econtext_stack->next;
6324 pfree(simple_econtext_stack);
6325 simple_econtext_stack = next;
6331 * free_var --- pfree any pass-by-reference value of the variable.
6333 * This should always be followed by some assignment to var->value,
6334 * as it leaves a dangling pointer.
6337 free_var(PLpgSQL_var *var)
6341 pfree(DatumGetPointer(var->value));
6342 var->freeval = false;
6347 * free old value of a text variable and assign new value from C string
6350 assign_text_var(PLpgSQL_var *var, const char *str)
6353 var->value = CStringGetTextDatum(str);
6354 var->isnull = false;
6355 var->freeval = true;
6359 * exec_eval_using_params --- evaluate params of USING clause
6361 static PreparedParamsData *
6362 exec_eval_using_params(PLpgSQL_execstate *estate, List *params)
6364 PreparedParamsData *ppd;
6369 ppd = (PreparedParamsData *) palloc(sizeof(PreparedParamsData));
6370 nargs = list_length(params);
6373 ppd->types = (Oid *) palloc(nargs * sizeof(Oid));
6374 ppd->values = (Datum *) palloc(nargs * sizeof(Datum));
6375 ppd->nulls = (char *) palloc(nargs * sizeof(char));
6376 ppd->freevals = (bool *) palloc(nargs * sizeof(bool));
6381 PLpgSQL_expr *param = (PLpgSQL_expr *) lfirst(lc);
6384 ppd->values[i] = exec_eval_expr(estate, param,
6387 ppd->nulls[i] = isnull ? 'n' : ' ';
6388 ppd->freevals[i] = false;
6390 if (ppd->types[i] == UNKNOWNOID)
6393 * Treat 'unknown' parameters as text, since that's what most
6394 * people would expect. SPI_execute_with_args can coerce unknown
6395 * constants in a more intelligent way, but not unknown Params.
6396 * This code also takes care of copying into the right context.
6397 * Note we assume 'unknown' has the representation of C-string.
6399 ppd->types[i] = TEXTOID;
6402 ppd->values[i] = CStringGetTextDatum(DatumGetCString(ppd->values[i]));
6403 ppd->freevals[i] = true;
6406 /* pass-by-ref non null values must be copied into plpgsql context */
6412 get_typlenbyval(ppd->types[i], &typLen, &typByVal);
6415 ppd->values[i] = datumCopy(ppd->values[i], typByVal, typLen);
6416 ppd->freevals[i] = true;
6420 exec_eval_cleanup(estate);
6429 * free_params_data --- pfree all pass-by-reference values used in USING clause
6432 free_params_data(PreparedParamsData *ppd)
6436 for (i = 0; i < ppd->nargs; i++)
6438 if (ppd->freevals[i])
6439 pfree(DatumGetPointer(ppd->values[i]));
6445 pfree(ppd->freevals);
6451 * Open portal for dynamic query
6454 exec_dynquery_with_params(PLpgSQL_execstate *estate,
6455 PLpgSQL_expr *dynquery,
6457 const char *portalname,
6467 * Evaluate the string expression after the EXECUTE keyword. Its result is
6468 * the querystring we have to execute.
6470 query = exec_eval_expr(estate, dynquery, &isnull, &restype);
6473 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
6474 errmsg("query string argument of EXECUTE is null")));
6476 /* Get the C-String representation */
6477 querystr = convert_value_to_string(estate, query, restype);
6479 /* copy it out of the temporary context before we clean up */
6480 querystr = pstrdup(querystr);
6482 exec_eval_cleanup(estate);
6485 * Open an implicit cursor for the query. We use
6486 * SPI_cursor_open_with_args even when there are no params, because this
6487 * avoids making and freeing one copy of the plan.
6491 PreparedParamsData *ppd;
6493 ppd = exec_eval_using_params(estate, params);
6494 portal = SPI_cursor_open_with_args(portalname,
6496 ppd->nargs, ppd->types,
6497 ppd->values, ppd->nulls,
6498 estate->readonly_func,
6500 free_params_data(ppd);
6504 portal = SPI_cursor_open_with_args(portalname,
6508 estate->readonly_func,
6513 elog(ERROR, "could not open implicit cursor for query \"%s\": %s",
6514 querystr, SPI_result_code_string(SPI_result));
6521 * Return a formatted string with information about an expression's parameters,
6522 * or NULL if the expression does not take any parameters.
6525 format_expr_params(PLpgSQL_execstate *estate,
6526 const PLpgSQL_expr *expr)
6530 StringInfoData paramstr;
6533 if (!expr->paramnos)
6536 initStringInfo(¶mstr);
6537 tmpset = bms_copy(expr->paramnos);
6539 while ((dno = bms_first_member(tmpset)) >= 0)
6545 PLpgSQL_var *curvar;
6547 curvar = (PLpgSQL_var *) estate->datums[dno];
6549 exec_eval_datum(estate, (PLpgSQL_datum *) curvar, ¶mtypeid,
6550 ¶mtypmod, ¶mdatum, ¶misnull);
6552 appendStringInfo(¶mstr, "%s%s = ",
6553 paramno > 0 ? ", " : "",
6557 appendStringInfoString(¶mstr, "NULL");
6560 char *value = convert_value_to_string(estate, paramdatum, paramtypeid);
6563 appendStringInfoCharMacro(¶mstr, '\'');
6564 for (p = value; *p; p++)
6566 if (*p == '\'') /* double single quotes */
6567 appendStringInfoCharMacro(¶mstr, *p);
6568 appendStringInfoCharMacro(¶mstr, *p);
6570 appendStringInfoCharMacro(¶mstr, '\'');
6577 return paramstr.data;
6581 * Return a formatted string with information about PreparedParamsData, or NULL
6582 * if there are no parameters.
6585 format_preparedparamsdata(PLpgSQL_execstate *estate,
6586 const PreparedParamsData *ppd)
6589 StringInfoData paramstr;
6594 initStringInfo(¶mstr);
6595 for (paramno = 0; paramno < ppd->nargs; paramno++)
6597 appendStringInfo(¶mstr, "%s$%d = ",
6598 paramno > 0 ? ", " : "",
6601 if (ppd->nulls[paramno] == 'n')
6602 appendStringInfoString(¶mstr, "NULL");
6605 char *value = convert_value_to_string(estate, ppd->values[paramno], ppd->types[paramno]);
6608 appendStringInfoCharMacro(¶mstr, '\'');
6609 for (p = value; *p; p++)
6611 if (*p == '\'') /* double single quotes */
6612 appendStringInfoCharMacro(¶mstr, *p);
6613 appendStringInfoCharMacro(¶mstr, *p);
6615 appendStringInfoCharMacro(¶mstr, '\'');
6619 return paramstr.data;