1 /*-------------------------------------------------------------------------
3 * pl_exec.c - Executor for the PL/pgSQL
6 * Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $PostgreSQL: pgsql/src/pl/plpgsql/src/pl_exec.c,v 1.213 2008/05/12 20:02:02 alvherre Exp $
13 *-------------------------------------------------------------------------
21 #include "access/transam.h"
22 #include "catalog/pg_proc.h"
23 #include "catalog/pg_type.h"
24 #include "executor/spi_priv.h"
26 #include "optimizer/clauses.h"
27 #include "parser/parse_expr.h"
28 #include "parser/scansup.h"
29 #include "tcop/tcopprot.h"
30 #include "utils/array.h"
31 #include "utils/builtins.h"
32 #include "utils/lsyscache.h"
33 #include "utils/memutils.h"
34 #include "utils/snapmgr.h"
35 #include "utils/typcache.h"
38 static const char *const raise_skip_msg = "RAISE";
42 int nargs; /* number of arguments */
43 Oid *types; /* types of arguments */
44 Datum *values; /* evaluated argument values */
45 char *nulls; /* null markers (' '/'n' style) */
46 bool *freevals; /* which arguments are pfree-able */
50 * All plpgsql function executions within a single transaction share the same
51 * executor EState for evaluating "simple" expressions. Each function call
52 * creates its own "eval_econtext" ExprContext within this estate for
53 * per-evaluation workspace. eval_econtext is freed at normal function exit,
54 * and the EState is freed at transaction end (in case of error, we assume
55 * that the abort mechanisms clean it all up). In order to be sure
56 * ExprContext callbacks are handled properly, each subtransaction has to have
57 * its own such EState; hence we need a stack. We use a simple counter to
58 * distinguish different instantiations of the EState, so that we can tell
59 * whether we have a current copy of a prepared expression.
61 * This arrangement is a bit tedious to maintain, but it's worth the trouble
62 * so that we don't have to re-prepare simple expressions on each trip through
63 * a function. (We assume the case to optimize is many repetitions of a
64 * function within a transaction.)
66 typedef struct SimpleEstateStackEntry
68 EState *xact_eval_estate; /* EState for current xact level */
69 long int xact_estate_simple_id; /* ID for xact_eval_estate */
70 SubTransactionId xact_subxid; /* ID for current subxact */
71 struct SimpleEstateStackEntry *next; /* next stack entry up */
72 } SimpleEstateStackEntry;
74 static SimpleEstateStackEntry *simple_estate_stack = NULL;
75 static long int simple_estate_id_counter = 0;
77 /************************************************************
78 * Local function forward declarations
79 ************************************************************/
80 static void plpgsql_exec_error_callback(void *arg);
81 static PLpgSQL_datum *copy_plpgsql_datum(PLpgSQL_datum *datum);
83 static int exec_stmt_block(PLpgSQL_execstate *estate,
84 PLpgSQL_stmt_block *block);
85 static int exec_stmts(PLpgSQL_execstate *estate,
87 static int exec_stmt(PLpgSQL_execstate *estate,
89 static int exec_stmt_assign(PLpgSQL_execstate *estate,
90 PLpgSQL_stmt_assign *stmt);
91 static int exec_stmt_perform(PLpgSQL_execstate *estate,
92 PLpgSQL_stmt_perform *stmt);
93 static int exec_stmt_getdiag(PLpgSQL_execstate *estate,
94 PLpgSQL_stmt_getdiag *stmt);
95 static int exec_stmt_if(PLpgSQL_execstate *estate,
96 PLpgSQL_stmt_if *stmt);
97 static int exec_stmt_loop(PLpgSQL_execstate *estate,
98 PLpgSQL_stmt_loop *stmt);
99 static int exec_stmt_while(PLpgSQL_execstate *estate,
100 PLpgSQL_stmt_while *stmt);
101 static int exec_stmt_fori(PLpgSQL_execstate *estate,
102 PLpgSQL_stmt_fori *stmt);
103 static int exec_stmt_fors(PLpgSQL_execstate *estate,
104 PLpgSQL_stmt_fors *stmt);
105 static int exec_stmt_forc(PLpgSQL_execstate *estate,
106 PLpgSQL_stmt_forc *stmt);
107 static int exec_stmt_open(PLpgSQL_execstate *estate,
108 PLpgSQL_stmt_open *stmt);
109 static int exec_stmt_fetch(PLpgSQL_execstate *estate,
110 PLpgSQL_stmt_fetch *stmt);
111 static int exec_stmt_close(PLpgSQL_execstate *estate,
112 PLpgSQL_stmt_close *stmt);
113 static int exec_stmt_exit(PLpgSQL_execstate *estate,
114 PLpgSQL_stmt_exit *stmt);
115 static int exec_stmt_return(PLpgSQL_execstate *estate,
116 PLpgSQL_stmt_return *stmt);
117 static int exec_stmt_return_next(PLpgSQL_execstate *estate,
118 PLpgSQL_stmt_return_next *stmt);
119 static int exec_stmt_return_query(PLpgSQL_execstate *estate,
120 PLpgSQL_stmt_return_query *stmt);
121 static int exec_stmt_raise(PLpgSQL_execstate *estate,
122 PLpgSQL_stmt_raise *stmt);
123 static int exec_stmt_execsql(PLpgSQL_execstate *estate,
124 PLpgSQL_stmt_execsql *stmt);
125 static int exec_stmt_dynexecute(PLpgSQL_execstate *estate,
126 PLpgSQL_stmt_dynexecute *stmt);
127 static int exec_stmt_dynfors(PLpgSQL_execstate *estate,
128 PLpgSQL_stmt_dynfors *stmt);
130 static void plpgsql_estate_setup(PLpgSQL_execstate *estate,
131 PLpgSQL_function *func,
133 static void exec_eval_cleanup(PLpgSQL_execstate *estate);
135 static void exec_prepare_plan(PLpgSQL_execstate *estate,
136 PLpgSQL_expr *expr, int cursorOptions);
137 static bool exec_simple_check_node(Node *node);
138 static void exec_simple_check_plan(PLpgSQL_expr *expr);
139 static bool exec_eval_simple_expr(PLpgSQL_execstate *estate,
145 static void exec_assign_expr(PLpgSQL_execstate *estate,
146 PLpgSQL_datum *target,
148 static void exec_assign_value(PLpgSQL_execstate *estate,
149 PLpgSQL_datum *target,
150 Datum value, Oid valtype, bool *isNull);
151 static void exec_eval_datum(PLpgSQL_execstate *estate,
152 PLpgSQL_datum *datum,
157 static int exec_eval_integer(PLpgSQL_execstate *estate,
160 static bool exec_eval_boolean(PLpgSQL_execstate *estate,
163 static Datum exec_eval_expr(PLpgSQL_execstate *estate,
167 static int exec_run_select(PLpgSQL_execstate *estate,
168 PLpgSQL_expr *expr, long maxtuples, Portal *portalP);
169 static int exec_for_query(PLpgSQL_execstate *estate, PLpgSQL_stmt_forq *stmt,
170 Portal portal, bool prefetch_ok);
171 static void eval_expr_params(PLpgSQL_execstate *estate,
172 PLpgSQL_expr *expr, Datum **p_values, char **p_nulls);
173 static void exec_move_row(PLpgSQL_execstate *estate,
176 HeapTuple tup, TupleDesc tupdesc);
177 static HeapTuple make_tuple_from_row(PLpgSQL_execstate *estate,
180 static char *convert_value_to_string(Datum value, Oid valtype);
181 static Datum exec_cast_value(Datum value, Oid valtype,
187 static Datum exec_simple_cast_value(Datum value, Oid valtype,
188 Oid reqtype, int32 reqtypmod,
190 static void exec_init_tuple_store(PLpgSQL_execstate *estate);
191 static bool compatible_tupdesc(TupleDesc td1, TupleDesc td2);
192 static void exec_set_found(PLpgSQL_execstate *estate, bool state);
193 static void plpgsql_create_econtext(PLpgSQL_execstate *estate);
194 static void free_var(PLpgSQL_var *var);
195 static void assign_text_var(PLpgSQL_var *var, const char *str);
196 static PreparedParamsData *exec_eval_using_params(PLpgSQL_execstate *estate,
198 static void free_params_data(PreparedParamsData *ppd);
199 static Portal exec_dynquery_with_params(PLpgSQL_execstate *estate,
200 PLpgSQL_expr *query, List *params);
204 * plpgsql_exec_function Called by the call handler for
205 * function execution.
209 plpgsql_exec_function(PLpgSQL_function *func, FunctionCallInfo fcinfo)
211 PLpgSQL_execstate estate;
212 ErrorContextCallback plerrcontext;
217 * Setup the execution state
219 plpgsql_estate_setup(&estate, func, (ReturnSetInfo *) fcinfo->resultinfo);
222 * Setup error traceback support for ereport()
224 plerrcontext.callback = plpgsql_exec_error_callback;
225 plerrcontext.arg = &estate;
226 plerrcontext.previous = error_context_stack;
227 error_context_stack = &plerrcontext;
230 * Make local execution copies of all the datums
232 estate.err_text = gettext_noop("during initialization of execution state");
233 for (i = 0; i < estate.ndatums; i++)
234 estate.datums[i] = copy_plpgsql_datum(func->datums[i]);
237 * Store the actual call argument values into the appropriate variables
239 estate.err_text = gettext_noop("while storing call arguments into local variables");
240 for (i = 0; i < func->fn_nargs; i++)
242 int n = func->fn_argvarnos[i];
244 switch (estate.datums[n]->dtype)
246 case PLPGSQL_DTYPE_VAR:
248 PLpgSQL_var *var = (PLpgSQL_var *) estate.datums[n];
250 var->value = fcinfo->arg[i];
251 var->isnull = fcinfo->argnull[i];
252 var->freeval = false;
256 case PLPGSQL_DTYPE_ROW:
258 PLpgSQL_row *row = (PLpgSQL_row *) estate.datums[n];
260 if (!fcinfo->argnull[i])
266 HeapTupleData tmptup;
268 td = DatumGetHeapTupleHeader(fcinfo->arg[i]);
269 /* Extract rowtype info and find a tupdesc */
270 tupType = HeapTupleHeaderGetTypeId(td);
271 tupTypmod = HeapTupleHeaderGetTypMod(td);
272 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
273 /* Build a temporary HeapTuple control structure */
274 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
275 ItemPointerSetInvalid(&(tmptup.t_self));
276 tmptup.t_tableOid = InvalidOid;
278 exec_move_row(&estate, NULL, row, &tmptup, tupdesc);
279 ReleaseTupleDesc(tupdesc);
283 /* If arg is null, treat it as an empty row */
284 exec_move_row(&estate, NULL, row, NULL, NULL);
290 elog(ERROR, "unrecognized dtype: %d", func->datums[i]->dtype);
294 estate.err_text = gettext_noop("during function entry");
297 * Set the magic variable FOUND to false
299 exec_set_found(&estate, false);
302 * Let the instrumentation plugin peek at this function
304 if (*plugin_ptr && (*plugin_ptr)->func_beg)
305 ((*plugin_ptr)->func_beg) (&estate, func);
308 * Now call the toplevel block of statements
310 estate.err_text = NULL;
311 estate.err_stmt = (PLpgSQL_stmt *) (func->action);
312 rc = exec_stmt_block(&estate, func->action);
313 if (rc != PLPGSQL_RC_RETURN)
315 estate.err_stmt = NULL;
316 estate.err_text = NULL;
319 * Provide a more helpful message if a CONTINUE has been used outside
322 if (rc == PLPGSQL_RC_CONTINUE)
324 (errcode(ERRCODE_SYNTAX_ERROR),
325 errmsg("CONTINUE cannot be used outside a loop")));
328 (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
329 errmsg("control reached end of function without RETURN")));
333 * We got a return value - process it
335 estate.err_stmt = NULL;
336 estate.err_text = gettext_noop("while casting return value to function's return type");
338 fcinfo->isnull = estate.retisnull;
342 ReturnSetInfo *rsi = estate.rsi;
344 /* Check caller can handle a set result */
345 if (!rsi || !IsA(rsi, ReturnSetInfo) ||
346 (rsi->allowedModes & SFRM_Materialize) == 0)
348 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
349 errmsg("set-valued function called in context that cannot accept a set")));
350 rsi->returnMode = SFRM_Materialize;
352 /* If we produced any tuples, send back the result */
353 if (estate.tuple_store)
355 rsi->setResult = estate.tuple_store;
356 if (estate.rettupdesc)
358 MemoryContext oldcxt;
360 oldcxt = MemoryContextSwitchTo(estate.tuple_store_cxt);
361 rsi->setDesc = CreateTupleDescCopy(estate.rettupdesc);
362 MemoryContextSwitchTo(oldcxt);
365 estate.retval = (Datum) 0;
366 fcinfo->isnull = true;
368 else if (!estate.retisnull)
370 if (estate.retistuple)
373 * We have to check that the returned tuple actually matches the
374 * expected result type. XXX would be better to cache the tupdesc
375 * instead of repeating get_call_result_type()
379 switch (get_call_result_type(fcinfo, NULL, &tupdesc))
381 case TYPEFUNC_COMPOSITE:
382 /* got the expected result rowtype, now check it */
383 if (estate.rettupdesc == NULL ||
384 !compatible_tupdesc(estate.rettupdesc, tupdesc))
386 (errcode(ERRCODE_DATATYPE_MISMATCH),
387 errmsg("returned record type does not match expected record type")));
389 case TYPEFUNC_RECORD:
392 * Failed to determine actual type of RECORD. We could
393 * raise an error here, but what this means in practice is
394 * that the caller is expecting any old generic rowtype,
395 * so we don't really need to be restrictive. Pass back
396 * the generated result type, instead.
398 tupdesc = estate.rettupdesc;
399 if (tupdesc == NULL) /* shouldn't happen */
400 elog(ERROR, "return type must be a row type");
403 /* shouldn't get here if retistuple is true ... */
404 elog(ERROR, "return type must be a row type");
409 * Copy tuple to upper executor memory, as a tuple Datum. Make
410 * sure it is labeled with the caller-supplied tuple type.
413 PointerGetDatum(SPI_returntuple((HeapTuple)DatumGetPointer(estate.retval),
418 /* Cast value to proper type */
419 estate.retval = exec_cast_value(estate.retval, estate.rettype,
421 &(func->fn_retinput),
422 func->fn_rettypioparam,
427 * If the function's return type isn't by value, copy the value
428 * into upper executor memory context.
430 if (!fcinfo->isnull && !func->fn_retbyval)
435 len = datumGetSize(estate.retval, false, func->fn_rettyplen);
436 tmp = SPI_palloc(len);
437 memcpy(tmp, DatumGetPointer(estate.retval), len);
438 estate.retval = PointerGetDatum(tmp);
443 estate.err_text = gettext_noop("during function exit");
446 * Let the instrumentation plugin peek at this function
448 if (*plugin_ptr && (*plugin_ptr)->func_end)
449 ((*plugin_ptr)->func_end) (&estate, func);
451 /* Clean up any leftover temporary memory */
452 FreeExprContext(estate.eval_econtext);
453 estate.eval_econtext = NULL;
454 exec_eval_cleanup(&estate);
457 * Pop the error context stack
459 error_context_stack = plerrcontext.previous;
462 * Return the function's result
464 return estate.retval;
469 * plpgsql_exec_trigger Called by the call handler for
474 plpgsql_exec_trigger(PLpgSQL_function *func,
475 TriggerData *trigdata)
477 PLpgSQL_execstate estate;
478 ErrorContextCallback plerrcontext;
482 PLpgSQL_rec *rec_new,
487 * Setup the execution state
489 plpgsql_estate_setup(&estate, func, NULL);
492 * Setup error traceback support for ereport()
494 plerrcontext.callback = plpgsql_exec_error_callback;
495 plerrcontext.arg = &estate;
496 plerrcontext.previous = error_context_stack;
497 error_context_stack = &plerrcontext;
500 * Make local execution copies of all the datums
502 estate.err_text = gettext_noop("during initialization of execution state");
503 for (i = 0; i < estate.ndatums; i++)
504 estate.datums[i] = copy_plpgsql_datum(func->datums[i]);
507 * Put the OLD and NEW tuples into record variables
509 rec_new = (PLpgSQL_rec *) (estate.datums[func->new_varno]);
510 rec_new->freetup = false;
511 rec_new->freetupdesc = false;
512 rec_old = (PLpgSQL_rec *) (estate.datums[func->old_varno]);
513 rec_old->freetup = false;
514 rec_old->freetupdesc = false;
516 if (TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
519 * Per-statement triggers don't use OLD/NEW variables
522 rec_new->tupdesc = NULL;
524 rec_old->tupdesc = NULL;
526 else if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
528 rec_new->tup = trigdata->tg_trigtuple;
529 rec_new->tupdesc = trigdata->tg_relation->rd_att;
531 rec_old->tupdesc = NULL;
533 else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
535 rec_new->tup = trigdata->tg_newtuple;
536 rec_new->tupdesc = trigdata->tg_relation->rd_att;
537 rec_old->tup = trigdata->tg_trigtuple;
538 rec_old->tupdesc = trigdata->tg_relation->rd_att;
540 else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
543 rec_new->tupdesc = NULL;
544 rec_old->tup = trigdata->tg_trigtuple;
545 rec_old->tupdesc = trigdata->tg_relation->rd_att;
548 elog(ERROR, "unrecognized trigger action: not INSERT, DELETE, or UPDATE");
551 * Assign the special tg_ variables
554 var = (PLpgSQL_var *) (estate.datums[func->tg_op_varno]);
555 if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
556 var->value = CStringGetTextDatum("INSERT");
557 else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
558 var->value = CStringGetTextDatum("UPDATE");
559 else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
560 var->value = CStringGetTextDatum("DELETE");
561 else if (TRIGGER_FIRED_BY_TRUNCATE(trigdata->tg_event))
562 var->value = CStringGetTextDatum("TRUNCATE");
564 elog(ERROR, "unrecognized trigger action: not INSERT, DELETE, UPDATE, or TRUNCATE");
568 var = (PLpgSQL_var *) (estate.datums[func->tg_name_varno]);
569 var->value = DirectFunctionCall1(namein,
570 CStringGetDatum(trigdata->tg_trigger->tgname));
574 var = (PLpgSQL_var *) (estate.datums[func->tg_when_varno]);
575 if (TRIGGER_FIRED_BEFORE(trigdata->tg_event))
576 var->value = CStringGetTextDatum("BEFORE");
577 else if (TRIGGER_FIRED_AFTER(trigdata->tg_event))
578 var->value = CStringGetTextDatum("AFTER");
580 elog(ERROR, "unrecognized trigger execution time: not BEFORE or AFTER");
584 var = (PLpgSQL_var *) (estate.datums[func->tg_level_varno]);
585 if (TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
586 var->value = CStringGetTextDatum("ROW");
587 else if (TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
588 var->value = CStringGetTextDatum("STATEMENT");
590 elog(ERROR, "unrecognized trigger event type: not ROW or STATEMENT");
594 var = (PLpgSQL_var *) (estate.datums[func->tg_relid_varno]);
595 var->value = ObjectIdGetDatum(trigdata->tg_relation->rd_id);
597 var->freeval = false;
599 var = (PLpgSQL_var *) (estate.datums[func->tg_relname_varno]);
600 var->value = DirectFunctionCall1(namein,
601 CStringGetDatum(RelationGetRelationName(trigdata->tg_relation)));
605 var = (PLpgSQL_var *) (estate.datums[func->tg_table_name_varno]);
606 var->value = DirectFunctionCall1(namein,
607 CStringGetDatum(RelationGetRelationName(trigdata->tg_relation)));
611 var = (PLpgSQL_var *) (estate.datums[func->tg_table_schema_varno]);
612 var->value = DirectFunctionCall1(namein,
615 RelationGetNamespace(
616 trigdata->tg_relation))));
620 var = (PLpgSQL_var *) (estate.datums[func->tg_nargs_varno]);
621 var->value = Int16GetDatum(trigdata->tg_trigger->tgnargs);
623 var->freeval = false;
626 * Store the trigger argument values into the special execution state
629 estate.err_text = gettext_noop("while storing call arguments into local variables");
630 estate.trig_nargs = trigdata->tg_trigger->tgnargs;
631 if (estate.trig_nargs == 0)
632 estate.trig_argv = NULL;
635 estate.trig_argv = palloc(sizeof(Datum) * estate.trig_nargs);
636 for (i = 0; i < trigdata->tg_trigger->tgnargs; i++)
637 estate.trig_argv[i] = CStringGetTextDatum(trigdata->tg_trigger->tgargs[i]);
640 estate.err_text = gettext_noop("during function entry");
643 * Set the magic variable FOUND to false
645 exec_set_found(&estate, false);
648 * Let the instrumentation plugin peek at this function
650 if (*plugin_ptr && (*plugin_ptr)->func_beg)
651 ((*plugin_ptr)->func_beg) (&estate, func);
654 * Now call the toplevel block of statements
656 estate.err_text = NULL;
657 estate.err_stmt = (PLpgSQL_stmt *) (func->action);
658 rc = exec_stmt_block(&estate, func->action);
659 if (rc != PLPGSQL_RC_RETURN)
661 estate.err_stmt = NULL;
662 estate.err_text = NULL;
665 * Provide a more helpful message if a CONTINUE has been used outside
668 if (rc == PLPGSQL_RC_CONTINUE)
670 (errcode(ERRCODE_SYNTAX_ERROR),
671 errmsg("CONTINUE cannot be used outside a loop")));
674 (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
675 errmsg("control reached end of trigger procedure without RETURN")));
678 estate.err_stmt = NULL;
679 estate.err_text = gettext_noop("during function exit");
683 (errcode(ERRCODE_DATATYPE_MISMATCH),
684 errmsg("trigger procedure cannot return a set")));
687 * Check that the returned tuple structure has the same attributes, the
688 * relation that fired the trigger has. A per-statement trigger always
689 * needs to return NULL, so we ignore any return value the function itself
690 * produces (XXX: is this a good idea?)
692 * XXX This way it is possible, that the trigger returns a tuple where
693 * attributes don't have the correct atttypmod's length. It's up to the
694 * trigger's programmer to ensure that this doesn't happen. Jan
696 if (estate.retisnull || TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
700 if (!compatible_tupdesc(estate.rettupdesc,
701 trigdata->tg_relation->rd_att))
703 (errcode(ERRCODE_DATATYPE_MISMATCH),
704 errmsg("returned tuple structure does not match table of trigger event")));
705 /* Copy tuple to upper executor memory */
706 rettup = SPI_copytuple((HeapTuple) DatumGetPointer(estate.retval));
710 * Let the instrumentation plugin peek at this function
712 if (*plugin_ptr && (*plugin_ptr)->func_end)
713 ((*plugin_ptr)->func_end) (&estate, func);
715 /* Clean up any leftover temporary memory */
716 FreeExprContext(estate.eval_econtext);
717 estate.eval_econtext = NULL;
718 exec_eval_cleanup(&estate);
721 * Pop the error context stack
723 error_context_stack = plerrcontext.previous;
726 * Return the trigger's result
733 * error context callback to let us supply a call-stack traceback
736 plpgsql_exec_error_callback(void *arg)
738 PLpgSQL_execstate *estate = (PLpgSQL_execstate *) arg;
740 /* safety check, shouldn't happen */
741 if (estate->err_func == NULL)
744 /* if we are doing RAISE, don't report its location */
745 if (estate->err_text == raise_skip_msg)
748 if (estate->err_text != NULL)
751 * We don't expend the cycles to run gettext() on err_text unless we
752 * actually need it. Therefore, places that set up err_text should
753 * use gettext_noop() to ensure the strings get recorded in the
754 * message dictionary.
756 * If both err_text and err_stmt are set, use the err_text as
757 * description, but report the err_stmt's line number. When err_stmt
758 * is not set, we're in function entry/exit, or some such place not
759 * attached to a specific line number.
761 if (estate->err_stmt != NULL)
764 * translator: last %s is a phrase such as "during statement block
765 * local variable initialization"
767 errcontext("PL/pgSQL function \"%s\" line %d %s",
768 estate->err_func->fn_name,
769 estate->err_stmt->lineno,
770 gettext(estate->err_text));
775 * translator: last %s is a phrase such as "while storing call
776 * arguments into local variables"
778 errcontext("PL/pgSQL function \"%s\" %s",
779 estate->err_func->fn_name,
780 gettext(estate->err_text));
783 else if (estate->err_stmt != NULL)
785 /* translator: last %s is a plpgsql statement type name */
786 errcontext("PL/pgSQL function \"%s\" line %d at %s",
787 estate->err_func->fn_name,
788 estate->err_stmt->lineno,
789 plpgsql_stmt_typename(estate->err_stmt));
792 errcontext("PL/pgSQL function \"%s\"",
793 estate->err_func->fn_name);
798 * Support function for initializing local execution variables
801 static PLpgSQL_datum *
802 copy_plpgsql_datum(PLpgSQL_datum *datum)
804 PLpgSQL_datum *result;
806 switch (datum->dtype)
808 case PLPGSQL_DTYPE_VAR:
810 PLpgSQL_var *new = palloc(sizeof(PLpgSQL_var));
812 memcpy(new, datum, sizeof(PLpgSQL_var));
813 /* Ensure the value is null (possibly not needed?) */
816 new->freeval = false;
818 result = (PLpgSQL_datum *) new;
822 case PLPGSQL_DTYPE_REC:
824 PLpgSQL_rec *new = palloc(sizeof(PLpgSQL_rec));
826 memcpy(new, datum, sizeof(PLpgSQL_rec));
827 /* Ensure the value is null (possibly not needed?) */
830 new->freetup = false;
831 new->freetupdesc = false;
833 result = (PLpgSQL_datum *) new;
837 case PLPGSQL_DTYPE_ROW:
838 case PLPGSQL_DTYPE_RECFIELD:
839 case PLPGSQL_DTYPE_ARRAYELEM:
840 case PLPGSQL_DTYPE_TRIGARG:
843 * These datum records are read-only at runtime, so no need to
850 elog(ERROR, "unrecognized dtype: %d", datum->dtype);
851 result = NULL; /* keep compiler quiet */
860 exception_matches_conditions(ErrorData *edata, PLpgSQL_condition *cond)
862 for (; cond != NULL; cond = cond->next)
864 int sqlerrstate = cond->sqlerrstate;
867 * OTHERS matches everything *except* query-canceled; if you're
868 * foolish enough, you can match that explicitly.
870 if (sqlerrstate == 0)
872 if (edata->sqlerrcode != ERRCODE_QUERY_CANCELED)
876 else if (edata->sqlerrcode == sqlerrstate)
878 /* Category match? */
879 else if (ERRCODE_IS_CATEGORY(sqlerrstate) &&
880 ERRCODE_TO_CATEGORY(edata->sqlerrcode) == sqlerrstate)
888 * exec_stmt_block Execute a block of statements
892 exec_stmt_block(PLpgSQL_execstate *estate, PLpgSQL_stmt_block *block)
894 volatile int rc = -1;
899 * First initialize all variables declared in this block
901 estate->err_text = gettext_noop("during statement block local variable initialization");
903 for (i = 0; i < block->n_initvars; i++)
905 n = block->initvarnos[i];
907 switch (estate->datums[n]->dtype)
909 case PLPGSQL_DTYPE_VAR:
911 PLpgSQL_var *var = (PLpgSQL_var *) (estate->datums[n]);
913 /* free any old value, in case re-entering block */
916 /* Initially it contains a NULL */
917 var->value = (Datum) 0;
920 if (var->default_val == NULL)
923 * If needed, give the datatype a chance to reject
924 * NULLs, by assigning a NULL to the variable. We
925 * claim the value is of type UNKNOWN, not the var's
926 * datatype, else coercion will be skipped. (Do this
927 * before the notnull check to be consistent with
928 * exec_assign_value.)
930 if (!var->datatype->typinput.fn_strict)
932 bool valIsNull = true;
934 exec_assign_value(estate,
935 (PLpgSQL_datum *) var,
942 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
943 errmsg("variable \"%s\" declared NOT NULL cannot default to NULL",
948 exec_assign_expr(estate, (PLpgSQL_datum *) var,
954 case PLPGSQL_DTYPE_REC:
956 PLpgSQL_rec *rec = (PLpgSQL_rec *) (estate->datums[n]);
960 heap_freetuple(rec->tup);
961 FreeTupleDesc(rec->tupdesc);
962 rec->freetup = false;
970 case PLPGSQL_DTYPE_RECFIELD:
971 case PLPGSQL_DTYPE_ARRAYELEM:
975 elog(ERROR, "unrecognized dtype: %d",
976 estate->datums[n]->dtype);
980 if (block->exceptions)
983 * Execute the statements in the block's body inside a sub-transaction
985 MemoryContext oldcontext = CurrentMemoryContext;
986 ResourceOwner oldowner = CurrentResourceOwner;
987 ExprContext *old_eval_econtext = estate->eval_econtext;
988 EState *old_eval_estate = estate->eval_estate;
989 long int old_eval_estate_simple_id = estate->eval_estate_simple_id;
991 estate->err_text = gettext_noop("during statement block entry");
993 BeginInternalSubTransaction(NULL);
994 /* Want to run statements inside function's memory context */
995 MemoryContextSwitchTo(oldcontext);
1000 * We need to run the block's statements with a new eval_econtext
1001 * that belongs to the current subtransaction; if we try to use
1002 * the outer econtext then ExprContext shutdown callbacks will be
1003 * called at the wrong times.
1005 plpgsql_create_econtext(estate);
1007 estate->err_text = NULL;
1009 /* Run the block's statements */
1010 rc = exec_stmts(estate, block->body);
1012 estate->err_text = gettext_noop("during statement block exit");
1015 * If the block ended with RETURN, we may need to copy the return
1016 * value out of the subtransaction eval_context. This is
1017 * currently only needed for scalar result types --- rowtype
1018 * values will always exist in the function's own memory context.
1020 if (rc == PLPGSQL_RC_RETURN &&
1021 !estate->retisset &&
1022 !estate->retisnull &&
1023 estate->rettupdesc == NULL)
1028 get_typlenbyval(estate->rettype, &resTypLen, &resTypByVal);
1029 estate->retval = datumCopy(estate->retval,
1030 resTypByVal, resTypLen);
1033 /* Commit the inner transaction, return to outer xact context */
1034 ReleaseCurrentSubTransaction();
1035 MemoryContextSwitchTo(oldcontext);
1036 CurrentResourceOwner = oldowner;
1038 /* Revert to outer eval_econtext */
1039 estate->eval_econtext = old_eval_econtext;
1040 estate->eval_estate = old_eval_estate;
1041 estate->eval_estate_simple_id = old_eval_estate_simple_id;
1044 * AtEOSubXact_SPI() should not have popped any SPI context, but
1045 * just in case it did, make sure we remain connected.
1047 SPI_restore_connection();
1054 estate->err_text = gettext_noop("during exception cleanup");
1056 /* Save error info */
1057 MemoryContextSwitchTo(oldcontext);
1058 edata = CopyErrorData();
1061 /* Abort the inner transaction */
1062 RollbackAndReleaseCurrentSubTransaction();
1063 MemoryContextSwitchTo(oldcontext);
1064 CurrentResourceOwner = oldowner;
1066 /* Revert to outer eval_econtext */
1067 estate->eval_econtext = old_eval_econtext;
1068 estate->eval_estate = old_eval_estate;
1069 estate->eval_estate_simple_id = old_eval_estate_simple_id;
1072 * If AtEOSubXact_SPI() popped any SPI context of the subxact, it
1073 * will have left us in a disconnected state. We need this hack
1074 * to return to connected state.
1076 SPI_restore_connection();
1078 /* Look for a matching exception handler */
1079 foreach(e, block->exceptions->exc_list)
1081 PLpgSQL_exception *exception = (PLpgSQL_exception *) lfirst(e);
1083 if (exception_matches_conditions(edata, exception->conditions))
1086 * Initialize the magic SQLSTATE and SQLERRM variables for
1087 * the exception block. We needn't do this until we have
1088 * found a matching exception.
1090 PLpgSQL_var *state_var;
1091 PLpgSQL_var *errm_var;
1093 state_var = (PLpgSQL_var *)
1094 estate->datums[block->exceptions->sqlstate_varno];
1095 errm_var = (PLpgSQL_var *)
1096 estate->datums[block->exceptions->sqlerrm_varno];
1098 assign_text_var(state_var,
1099 unpack_sql_state(edata->sqlerrcode));
1100 assign_text_var(errm_var, edata->message);
1102 estate->err_text = NULL;
1104 rc = exec_stmts(estate, exception->action);
1106 free_var(state_var);
1107 state_var->value = (Datum) 0;
1108 state_var->isnull = true;
1110 errm_var->value = (Datum) 0;
1111 errm_var->isnull = true;
1116 /* If no match found, re-throw the error */
1118 ReThrowError(edata);
1120 FreeErrorData(edata);
1127 * Just execute the statements in the block's body
1129 estate->err_text = NULL;
1131 rc = exec_stmts(estate, block->body);
1134 estate->err_text = NULL;
1137 * Handle the return code.
1142 case PLPGSQL_RC_CONTINUE:
1143 case PLPGSQL_RC_RETURN:
1146 case PLPGSQL_RC_EXIT:
1147 if (estate->exitlabel == NULL)
1148 return PLPGSQL_RC_OK;
1149 if (block->label == NULL)
1150 return PLPGSQL_RC_EXIT;
1151 if (strcmp(block->label, estate->exitlabel))
1152 return PLPGSQL_RC_EXIT;
1153 estate->exitlabel = NULL;
1154 return PLPGSQL_RC_OK;
1157 elog(ERROR, "unrecognized rc: %d", rc);
1160 return PLPGSQL_RC_OK;
1165 * exec_stmts Iterate over a list of statements
1166 * as long as their return code is OK
1170 exec_stmts(PLpgSQL_execstate *estate, List *stmts)
1177 * Ensure we do a CHECK_FOR_INTERRUPTS() even though there is no
1178 * statement. This prevents hangup in a tight loop if, for instance,
1179 * there is a LOOP construct with an empty body.
1181 CHECK_FOR_INTERRUPTS();
1182 return PLPGSQL_RC_OK;
1187 PLpgSQL_stmt *stmt = (PLpgSQL_stmt *) lfirst(s);
1188 int rc = exec_stmt(estate, stmt);
1190 if (rc != PLPGSQL_RC_OK)
1194 return PLPGSQL_RC_OK;
1199 * exec_stmt Distribute one statement to the statements
1200 * type specific execution function.
1204 exec_stmt(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
1206 PLpgSQL_stmt *save_estmt;
1209 save_estmt = estate->err_stmt;
1210 estate->err_stmt = stmt;
1212 /* Let the plugin know that we are about to execute this statement */
1213 if (*plugin_ptr && (*plugin_ptr)->stmt_beg)
1214 ((*plugin_ptr)->stmt_beg) (estate, stmt);
1216 CHECK_FOR_INTERRUPTS();
1218 switch (stmt->cmd_type)
1220 case PLPGSQL_STMT_BLOCK:
1221 rc = exec_stmt_block(estate, (PLpgSQL_stmt_block *) stmt);
1224 case PLPGSQL_STMT_ASSIGN:
1225 rc = exec_stmt_assign(estate, (PLpgSQL_stmt_assign *) stmt);
1228 case PLPGSQL_STMT_PERFORM:
1229 rc = exec_stmt_perform(estate, (PLpgSQL_stmt_perform *) stmt);
1232 case PLPGSQL_STMT_GETDIAG:
1233 rc = exec_stmt_getdiag(estate, (PLpgSQL_stmt_getdiag *) stmt);
1236 case PLPGSQL_STMT_IF:
1237 rc = exec_stmt_if(estate, (PLpgSQL_stmt_if *) stmt);
1240 case PLPGSQL_STMT_LOOP:
1241 rc = exec_stmt_loop(estate, (PLpgSQL_stmt_loop *) stmt);
1244 case PLPGSQL_STMT_WHILE:
1245 rc = exec_stmt_while(estate, (PLpgSQL_stmt_while *) stmt);
1248 case PLPGSQL_STMT_FORI:
1249 rc = exec_stmt_fori(estate, (PLpgSQL_stmt_fori *) stmt);
1252 case PLPGSQL_STMT_FORS:
1253 rc = exec_stmt_fors(estate, (PLpgSQL_stmt_fors *) stmt);
1256 case PLPGSQL_STMT_FORC:
1257 rc = exec_stmt_forc(estate, (PLpgSQL_stmt_forc *) stmt);
1260 case PLPGSQL_STMT_EXIT:
1261 rc = exec_stmt_exit(estate, (PLpgSQL_stmt_exit *) stmt);
1264 case PLPGSQL_STMT_RETURN:
1265 rc = exec_stmt_return(estate, (PLpgSQL_stmt_return *) stmt);
1268 case PLPGSQL_STMT_RETURN_NEXT:
1269 rc = exec_stmt_return_next(estate, (PLpgSQL_stmt_return_next *) stmt);
1272 case PLPGSQL_STMT_RETURN_QUERY:
1273 rc = exec_stmt_return_query(estate, (PLpgSQL_stmt_return_query *) stmt);
1276 case PLPGSQL_STMT_RAISE:
1277 rc = exec_stmt_raise(estate, (PLpgSQL_stmt_raise *) stmt);
1280 case PLPGSQL_STMT_EXECSQL:
1281 rc = exec_stmt_execsql(estate, (PLpgSQL_stmt_execsql *) stmt);
1284 case PLPGSQL_STMT_DYNEXECUTE:
1285 rc = exec_stmt_dynexecute(estate, (PLpgSQL_stmt_dynexecute *) stmt);
1288 case PLPGSQL_STMT_DYNFORS:
1289 rc = exec_stmt_dynfors(estate, (PLpgSQL_stmt_dynfors *) stmt);
1292 case PLPGSQL_STMT_OPEN:
1293 rc = exec_stmt_open(estate, (PLpgSQL_stmt_open *) stmt);
1296 case PLPGSQL_STMT_FETCH:
1297 rc = exec_stmt_fetch(estate, (PLpgSQL_stmt_fetch *) stmt);
1300 case PLPGSQL_STMT_CLOSE:
1301 rc = exec_stmt_close(estate, (PLpgSQL_stmt_close *) stmt);
1305 estate->err_stmt = save_estmt;
1306 elog(ERROR, "unrecognized cmdtype: %d", stmt->cmd_type);
1309 /* Let the plugin know that we have finished executing this statement */
1310 if (*plugin_ptr && (*plugin_ptr)->stmt_end)
1311 ((*plugin_ptr)->stmt_end) (estate, stmt);
1313 estate->err_stmt = save_estmt;
1320 * exec_stmt_assign Evaluate an expression and
1321 * put the result into a variable.
1325 exec_stmt_assign(PLpgSQL_execstate *estate, PLpgSQL_stmt_assign *stmt)
1327 Assert(stmt->varno >= 0);
1329 exec_assign_expr(estate, estate->datums[stmt->varno], stmt->expr);
1331 return PLPGSQL_RC_OK;
1335 * exec_stmt_perform Evaluate query and discard result (but set
1336 * FOUND depending on whether at least one row
1341 exec_stmt_perform(PLpgSQL_execstate *estate, PLpgSQL_stmt_perform *stmt)
1343 PLpgSQL_expr *expr = stmt->expr;
1345 (void) exec_run_select(estate, expr, 0, NULL);
1346 exec_set_found(estate, (estate->eval_processed != 0));
1347 exec_eval_cleanup(estate);
1349 return PLPGSQL_RC_OK;
1353 * exec_stmt_getdiag Put internal PG information into
1354 * specified variables.
1358 exec_stmt_getdiag(PLpgSQL_execstate *estate, PLpgSQL_stmt_getdiag *stmt)
1362 foreach(lc, stmt->diag_items)
1364 PLpgSQL_diag_item *diag_item = (PLpgSQL_diag_item *) lfirst(lc);
1366 bool isnull = false;
1368 if (diag_item->target <= 0)
1371 var = estate->datums[diag_item->target];
1376 switch (diag_item->kind)
1378 case PLPGSQL_GETDIAG_ROW_COUNT:
1380 exec_assign_value(estate, var,
1381 UInt32GetDatum(estate->eval_processed),
1385 case PLPGSQL_GETDIAG_RESULT_OID:
1387 exec_assign_value(estate, var,
1388 ObjectIdGetDatum(estate->eval_lastoid),
1393 elog(ERROR, "unrecognized attribute request: %d",
1398 return PLPGSQL_RC_OK;
1402 * exec_stmt_if Evaluate a bool expression and
1403 * execute the true or false body
1408 exec_stmt_if(PLpgSQL_execstate *estate, PLpgSQL_stmt_if *stmt)
1413 value = exec_eval_boolean(estate, stmt->cond, &isnull);
1414 exec_eval_cleanup(estate);
1416 if (!isnull && value)
1418 if (stmt->true_body != NIL)
1419 return exec_stmts(estate, stmt->true_body);
1423 if (stmt->false_body != NIL)
1424 return exec_stmts(estate, stmt->false_body);
1427 return PLPGSQL_RC_OK;
1432 * exec_stmt_loop Loop over statements until
1437 exec_stmt_loop(PLpgSQL_execstate *estate, PLpgSQL_stmt_loop *stmt)
1441 int rc = exec_stmts(estate, stmt->body);
1448 case PLPGSQL_RC_EXIT:
1449 if (estate->exitlabel == NULL)
1450 return PLPGSQL_RC_OK;
1451 if (stmt->label == NULL)
1452 return PLPGSQL_RC_EXIT;
1453 if (strcmp(stmt->label, estate->exitlabel) != 0)
1454 return PLPGSQL_RC_EXIT;
1455 estate->exitlabel = NULL;
1456 return PLPGSQL_RC_OK;
1458 case PLPGSQL_RC_CONTINUE:
1459 if (estate->exitlabel == NULL)
1460 /* anonymous continue, so re-run the loop */
1462 else if (stmt->label != NULL &&
1463 strcmp(stmt->label, estate->exitlabel) == 0)
1464 /* label matches named continue, so re-run loop */
1465 estate->exitlabel = NULL;
1467 /* label doesn't match named continue, so propagate upward */
1468 return PLPGSQL_RC_CONTINUE;
1471 case PLPGSQL_RC_RETURN:
1472 return PLPGSQL_RC_RETURN;
1475 elog(ERROR, "unrecognized rc: %d", rc);
1479 return PLPGSQL_RC_OK;
1484 * exec_stmt_while Loop over statements as long
1485 * as an expression evaluates to
1486 * true or an exit occurs.
1490 exec_stmt_while(PLpgSQL_execstate *estate, PLpgSQL_stmt_while *stmt)
1498 value = exec_eval_boolean(estate, stmt->cond, &isnull);
1499 exec_eval_cleanup(estate);
1501 if (isnull || !value)
1504 rc = exec_stmts(estate, stmt->body);
1511 case PLPGSQL_RC_EXIT:
1512 if (estate->exitlabel == NULL)
1513 return PLPGSQL_RC_OK;
1514 if (stmt->label == NULL)
1515 return PLPGSQL_RC_EXIT;
1516 if (strcmp(stmt->label, estate->exitlabel))
1517 return PLPGSQL_RC_EXIT;
1518 estate->exitlabel = NULL;
1519 return PLPGSQL_RC_OK;
1521 case PLPGSQL_RC_CONTINUE:
1522 if (estate->exitlabel == NULL)
1523 /* anonymous continue, so re-run loop */
1525 else if (stmt->label != NULL &&
1526 strcmp(stmt->label, estate->exitlabel) == 0)
1527 /* label matches named continue, so re-run loop */
1528 estate->exitlabel = NULL;
1530 /* label doesn't match named continue, propagate upward */
1531 return PLPGSQL_RC_CONTINUE;
1534 case PLPGSQL_RC_RETURN:
1535 return PLPGSQL_RC_RETURN;
1538 elog(ERROR, "unrecognized rc: %d", rc);
1542 return PLPGSQL_RC_OK;
1547 * exec_stmt_fori Iterate an integer variable
1548 * from a lower to an upper value
1549 * incrementing or decrementing by the BY value
1553 exec_stmt_fori(PLpgSQL_execstate *estate, PLpgSQL_stmt_fori *stmt)
1563 int rc = PLPGSQL_RC_OK;
1565 var = (PLpgSQL_var *) (estate->datums[stmt->var->varno]);
1568 * Get the value of the lower bound
1570 value = exec_eval_expr(estate, stmt->lower, &isnull, &valtype);
1571 value = exec_cast_value(value, valtype, var->datatype->typoid,
1572 &(var->datatype->typinput),
1573 var->datatype->typioparam,
1574 var->datatype->atttypmod, isnull);
1577 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1578 errmsg("lower bound of FOR loop cannot be NULL")));
1579 loop_value = DatumGetInt32(value);
1580 exec_eval_cleanup(estate);
1583 * Get the value of the upper bound
1585 value = exec_eval_expr(estate, stmt->upper, &isnull, &valtype);
1586 value = exec_cast_value(value, valtype, var->datatype->typoid,
1587 &(var->datatype->typinput),
1588 var->datatype->typioparam,
1589 var->datatype->atttypmod, isnull);
1592 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1593 errmsg("upper bound of FOR loop cannot be NULL")));
1594 end_value = DatumGetInt32(value);
1595 exec_eval_cleanup(estate);
1598 * Get the step value
1602 value = exec_eval_expr(estate, stmt->step, &isnull, &valtype);
1603 value = exec_cast_value(value, valtype, var->datatype->typoid,
1604 &(var->datatype->typinput),
1605 var->datatype->typioparam,
1606 var->datatype->atttypmod, isnull);
1609 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1610 errmsg("BY value of FOR loop cannot be NULL")));
1611 step_value = DatumGetInt32(value);
1612 exec_eval_cleanup(estate);
1613 if (step_value <= 0)
1615 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1616 errmsg("BY value of FOR loop must be greater than zero")));
1627 * Check against upper bound
1631 if (loop_value < end_value)
1636 if (loop_value > end_value)
1640 found = true; /* looped at least once */
1643 * Assign current value to loop var
1645 var->value = Int32GetDatum(loop_value);
1646 var->isnull = false;
1649 * Execute the statements
1651 rc = exec_stmts(estate, stmt->body);
1653 if (rc == PLPGSQL_RC_RETURN)
1654 break; /* return from function */
1655 else if (rc == PLPGSQL_RC_EXIT)
1657 if (estate->exitlabel == NULL)
1658 /* unlabelled exit, finish the current loop */
1660 else if (stmt->label != NULL &&
1661 strcmp(stmt->label, estate->exitlabel) == 0)
1663 /* labelled exit, matches the current stmt's label */
1664 estate->exitlabel = NULL;
1669 * otherwise, this is a labelled exit that does not match the
1670 * current statement's label, if any: return RC_EXIT so that the
1671 * EXIT continues to propagate up the stack.
1675 else if (rc == PLPGSQL_RC_CONTINUE)
1677 if (estate->exitlabel == NULL)
1678 /* unlabelled continue, so re-run the current loop */
1680 else if (stmt->label != NULL &&
1681 strcmp(stmt->label, estate->exitlabel) == 0)
1683 /* label matches named continue, so re-run loop */
1684 estate->exitlabel = NULL;
1690 * otherwise, this is a named continue that does not match the
1691 * current statement's label, if any: return RC_CONTINUE so
1692 * that the CONTINUE will propagate up the stack.
1699 * Increase/decrease loop value, unless it would overflow, in which
1700 * case exit the loop.
1704 if ((int32) (loop_value - step_value) > loop_value)
1706 loop_value -= step_value;
1710 if ((int32) (loop_value + step_value) < loop_value)
1712 loop_value += step_value;
1717 * Set the FOUND variable to indicate the result of executing the loop
1718 * (namely, whether we looped one or more times). This must be set here so
1719 * that it does not interfere with the value of the FOUND variable inside
1720 * the loop processing itself.
1722 exec_set_found(estate, found);
1729 * exec_stmt_fors Execute a query, assign each
1730 * tuple to a record or row and
1731 * execute a group of statements
1736 exec_stmt_fors(PLpgSQL_execstate *estate, PLpgSQL_stmt_fors *stmt)
1742 * Open the implicit cursor for the statement using exec_run_select
1744 exec_run_select(estate, stmt->query, 0, &portal);
1749 rc = exec_for_query(estate, (PLpgSQL_stmt_forq *) stmt, portal, true);
1752 * Close the implicit cursor
1754 SPI_cursor_close(portal);
1761 * exec_stmt_forc Execute a loop for each row from a cursor.
1765 exec_stmt_forc(PLpgSQL_execstate *estate, PLpgSQL_stmt_forc *stmt)
1767 PLpgSQL_var *curvar;
1768 char *curname = NULL;
1769 PLpgSQL_expr *query;
1776 * Get the cursor variable and if it has an assigned name, check
1777 * that it's not in use currently.
1780 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
1781 if (!curvar->isnull)
1783 curname = TextDatumGetCString(curvar->value);
1784 if (SPI_cursor_find(curname) != NULL)
1786 (errcode(ERRCODE_DUPLICATE_CURSOR),
1787 errmsg("cursor \"%s\" already in use", curname)));
1791 * Open the cursor just like an OPEN command
1793 * Note: parser should already have checked that statement supplies
1794 * args iff cursor needs them, but we check again to be safe.
1797 if (stmt->argquery != NULL)
1800 * OPEN CURSOR with args. We fake a SELECT ... INTO ...
1801 * statement to evaluate the args and put 'em into the
1805 PLpgSQL_stmt_execsql set_args;
1807 if (curvar->cursor_explicit_argrow < 0)
1809 (errcode(ERRCODE_SYNTAX_ERROR),
1810 errmsg("arguments given for cursor without arguments")));
1812 memset(&set_args, 0, sizeof(set_args));
1813 set_args.cmd_type = PLPGSQL_STMT_EXECSQL;
1814 set_args.lineno = stmt->lineno;
1815 set_args.sqlstmt = stmt->argquery;
1816 set_args.into = true;
1817 /* XXX historically this has not been STRICT */
1818 set_args.row = (PLpgSQL_row *)
1819 (estate->datums[curvar->cursor_explicit_argrow]);
1821 if (exec_stmt_execsql(estate, &set_args) != PLPGSQL_RC_OK)
1822 elog(ERROR, "open cursor failed during argument processing");
1826 if (curvar->cursor_explicit_argrow >= 0)
1828 (errcode(ERRCODE_SYNTAX_ERROR),
1829 errmsg("arguments required for cursor")));
1832 query = curvar->cursor_explicit_expr;
1835 if (query->plan == NULL)
1836 exec_prepare_plan(estate, query, curvar->cursor_options);
1839 * Now build up the values and nulls arguments for SPI_execute_plan()
1841 eval_expr_params(estate, query, &values, &nulls);
1846 portal = SPI_cursor_open(curname, query->plan, values, nulls,
1847 estate->readonly_func);
1849 elog(ERROR, "could not open cursor: %s",
1850 SPI_result_code_string(SPI_result));
1853 * If cursor variable was NULL, store the generated portal name in it
1855 if (curname == NULL)
1856 assign_text_var(curvar, portal->name);
1859 * Execute the loop. We can't prefetch because the cursor is accessible
1860 * to the user, for instance via UPDATE WHERE CURRENT OF within the loop.
1862 rc = exec_for_query(estate, (PLpgSQL_stmt_forq *) stmt, portal, false);
1865 * Close portal, and restore cursor variable if it was initially NULL.
1868 SPI_cursor_close(portal);
1870 if (curname == NULL)
1873 curvar->value = (Datum) 0;
1874 curvar->isnull = true;
1887 * exec_stmt_exit Implements EXIT and CONTINUE
1889 * This begins the process of exiting / restarting a loop.
1893 exec_stmt_exit(PLpgSQL_execstate *estate, PLpgSQL_stmt_exit *stmt)
1896 * If the exit / continue has a condition, evaluate it
1898 if (stmt->cond != NULL)
1903 value = exec_eval_boolean(estate, stmt->cond, &isnull);
1904 exec_eval_cleanup(estate);
1905 if (isnull || value == false)
1906 return PLPGSQL_RC_OK;
1909 estate->exitlabel = stmt->label;
1911 return PLPGSQL_RC_EXIT;
1913 return PLPGSQL_RC_CONTINUE;
1918 * exec_stmt_return Evaluate an expression and start
1919 * returning from the function.
1923 exec_stmt_return(PLpgSQL_execstate *estate, PLpgSQL_stmt_return *stmt)
1926 * If processing a set-returning PL/PgSQL function, the final RETURN
1927 * indicates that the function is finished producing tuples. The rest of
1928 * the work will be done at the top level.
1930 if (estate->retisset)
1931 return PLPGSQL_RC_RETURN;
1933 /* initialize for null result (possibly a tuple) */
1934 estate->retval = (Datum) 0;
1935 estate->rettupdesc = NULL;
1936 estate->retisnull = true;
1938 if (stmt->retvarno >= 0)
1940 PLpgSQL_datum *retvar = estate->datums[stmt->retvarno];
1942 switch (retvar->dtype)
1944 case PLPGSQL_DTYPE_VAR:
1946 PLpgSQL_var *var = (PLpgSQL_var *) retvar;
1948 estate->retval = var->value;
1949 estate->retisnull = var->isnull;
1950 estate->rettype = var->datatype->typoid;
1954 case PLPGSQL_DTYPE_REC:
1956 PLpgSQL_rec *rec = (PLpgSQL_rec *) retvar;
1958 if (HeapTupleIsValid(rec->tup))
1960 estate->retval = PointerGetDatum(rec->tup);
1961 estate->rettupdesc = rec->tupdesc;
1962 estate->retisnull = false;
1967 case PLPGSQL_DTYPE_ROW:
1969 PLpgSQL_row *row = (PLpgSQL_row *) retvar;
1971 Assert(row->rowtupdesc);
1973 PointerGetDatum(make_tuple_from_row(estate, row,
1975 if (DatumGetPointer(estate->retval) == NULL) /* should not happen */
1976 elog(ERROR, "row not compatible with its own tupdesc");
1977 estate->rettupdesc = row->rowtupdesc;
1978 estate->retisnull = false;
1983 elog(ERROR, "unrecognized dtype: %d", retvar->dtype);
1986 return PLPGSQL_RC_RETURN;
1989 if (stmt->expr != NULL)
1991 if (estate->retistuple)
1993 exec_run_select(estate, stmt->expr, 1, NULL);
1994 if (estate->eval_processed > 0)
1996 estate->retval = PointerGetDatum(estate->eval_tuptable->vals[0]);
1997 estate->rettupdesc = estate->eval_tuptable->tupdesc;
1998 estate->retisnull = false;
2003 /* Normal case for scalar results */
2004 estate->retval = exec_eval_expr(estate, stmt->expr,
2005 &(estate->retisnull),
2006 &(estate->rettype));
2009 return PLPGSQL_RC_RETURN;
2013 * Special hack for function returning VOID: instead of NULL, return a
2014 * non-null VOID value. This is of dubious importance but is kept for
2015 * backwards compatibility. Note that the only other way to get here is
2016 * to have written "RETURN NULL" in a function returning tuple.
2018 if (estate->fn_rettype == VOIDOID)
2020 estate->retval = (Datum) 0;
2021 estate->retisnull = false;
2022 estate->rettype = VOIDOID;
2025 return PLPGSQL_RC_RETURN;
2029 * exec_stmt_return_next Evaluate an expression and add it to the
2030 * list of tuples returned by the current
2035 exec_stmt_return_next(PLpgSQL_execstate *estate,
2036 PLpgSQL_stmt_return_next *stmt)
2040 MemoryContext oldcxt;
2041 HeapTuple tuple = NULL;
2042 bool free_tuple = false;
2044 if (!estate->retisset)
2046 (errcode(ERRCODE_SYNTAX_ERROR),
2047 errmsg("cannot use RETURN NEXT in a non-SETOF function")));
2049 if (estate->tuple_store == NULL)
2050 exec_init_tuple_store(estate);
2052 /* rettupdesc will be filled by exec_init_tuple_store */
2053 tupdesc = estate->rettupdesc;
2054 natts = tupdesc->natts;
2056 if (stmt->retvarno >= 0)
2058 PLpgSQL_datum *retvar = estate->datums[stmt->retvarno];
2060 switch (retvar->dtype)
2062 case PLPGSQL_DTYPE_VAR:
2064 PLpgSQL_var *var = (PLpgSQL_var *) retvar;
2065 Datum retval = var->value;
2066 bool isNull = var->isnull;
2070 (errcode(ERRCODE_DATATYPE_MISMATCH),
2071 errmsg("wrong result type supplied in RETURN NEXT")));
2073 /* coerce type if needed */
2074 retval = exec_simple_cast_value(retval,
2075 var->datatype->typoid,
2076 tupdesc->attrs[0]->atttypid,
2077 tupdesc->attrs[0]->atttypmod,
2080 oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
2081 tuplestore_putvalues(estate->tuple_store, tupdesc,
2083 MemoryContextSwitchTo(oldcxt);
2087 case PLPGSQL_DTYPE_REC:
2089 PLpgSQL_rec *rec = (PLpgSQL_rec *) retvar;
2091 if (!HeapTupleIsValid(rec->tup))
2093 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2094 errmsg("record \"%s\" is not assigned yet",
2096 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
2097 if (!compatible_tupdesc(tupdesc, rec->tupdesc))
2099 (errcode(ERRCODE_DATATYPE_MISMATCH),
2100 errmsg("wrong record type supplied in RETURN NEXT")));
2105 case PLPGSQL_DTYPE_ROW:
2107 PLpgSQL_row *row = (PLpgSQL_row *) retvar;
2109 tuple = make_tuple_from_row(estate, row, tupdesc);
2112 (errcode(ERRCODE_DATATYPE_MISMATCH),
2113 errmsg("wrong record type supplied in RETURN NEXT")));
2119 elog(ERROR, "unrecognized dtype: %d", retvar->dtype);
2123 else if (stmt->expr)
2131 (errcode(ERRCODE_DATATYPE_MISMATCH),
2132 errmsg("wrong result type supplied in RETURN NEXT")));
2134 retval = exec_eval_expr(estate,
2139 /* coerce type if needed */
2140 retval = exec_simple_cast_value(retval,
2142 tupdesc->attrs[0]->atttypid,
2143 tupdesc->attrs[0]->atttypmod,
2146 oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
2147 tuplestore_putvalues(estate->tuple_store, tupdesc,
2149 MemoryContextSwitchTo(oldcxt);
2151 exec_eval_cleanup(estate);
2156 (errcode(ERRCODE_SYNTAX_ERROR),
2157 errmsg("RETURN NEXT must have a parameter")));
2160 if (HeapTupleIsValid(tuple))
2162 oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
2163 tuplestore_puttuple(estate->tuple_store, tuple);
2164 MemoryContextSwitchTo(oldcxt);
2167 heap_freetuple(tuple);
2170 return PLPGSQL_RC_OK;
2174 * exec_stmt_return_query Evaluate a query and add it to the
2175 * list of tuples returned by the current
2180 exec_stmt_return_query(PLpgSQL_execstate *estate,
2181 PLpgSQL_stmt_return_query *stmt)
2185 if (!estate->retisset)
2187 (errcode(ERRCODE_SYNTAX_ERROR),
2188 errmsg("cannot use RETURN QUERY in a non-SETOF function")));
2190 if (estate->tuple_store == NULL)
2191 exec_init_tuple_store(estate);
2193 if (stmt->query != NULL)
2196 exec_run_select(estate, stmt->query, 0, &portal);
2200 /* RETURN QUERY EXECUTE */
2201 Assert(stmt->dynquery != NULL);
2202 portal = exec_dynquery_with_params(estate, stmt->dynquery,
2206 if (!compatible_tupdesc(estate->rettupdesc, portal->tupDesc))
2208 (errcode(ERRCODE_DATATYPE_MISMATCH),
2209 errmsg("structure of query does not match function result type")));
2213 MemoryContext old_cxt;
2216 SPI_cursor_fetch(portal, true, 50);
2217 if (SPI_processed == 0)
2220 old_cxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
2221 for (i = 0; i < SPI_processed; i++)
2223 HeapTuple tuple = SPI_tuptable->vals[i];
2225 tuplestore_puttuple(estate->tuple_store, tuple);
2227 MemoryContextSwitchTo(old_cxt);
2229 SPI_freetuptable(SPI_tuptable);
2232 SPI_freetuptable(SPI_tuptable);
2233 SPI_cursor_close(portal);
2235 return PLPGSQL_RC_OK;
2239 exec_init_tuple_store(PLpgSQL_execstate *estate)
2241 ReturnSetInfo *rsi = estate->rsi;
2242 MemoryContext oldcxt;
2245 * Check caller can handle a set result in the way we want
2247 if (!rsi || !IsA(rsi, ReturnSetInfo) ||
2248 (rsi->allowedModes & SFRM_Materialize) == 0 ||
2249 rsi->expectedDesc == NULL)
2251 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2252 errmsg("set-valued function called in context that cannot accept a set")));
2254 estate->tuple_store_cxt = rsi->econtext->ecxt_per_query_memory;
2256 oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
2257 estate->tuple_store = tuplestore_begin_heap(true, false, work_mem);
2258 MemoryContextSwitchTo(oldcxt);
2260 estate->rettupdesc = rsi->expectedDesc;
2264 * exec_stmt_raise Build a message and throw it with elog()
2268 exec_stmt_raise(PLpgSQL_execstate *estate, PLpgSQL_stmt_raise *stmt)
2272 ListCell *current_param;
2274 plpgsql_dstring_init(&ds);
2275 current_param = list_head(stmt->params);
2277 for (cp = stmt->message; *cp; cp++)
2280 * Occurrences of a single % are replaced by the next parameter's
2281 * external representation. Double %'s are converted to one %.
2292 plpgsql_dstring_append_char(&ds, cp[1]);
2297 if (current_param == NULL)
2299 (errcode(ERRCODE_SYNTAX_ERROR),
2300 errmsg("too few parameters specified for RAISE")));
2302 paramvalue = exec_eval_expr(estate,
2303 (PLpgSQL_expr *) lfirst(current_param),
2310 extval = convert_value_to_string(paramvalue, paramtypeid);
2311 plpgsql_dstring_append(&ds, extval);
2312 current_param = lnext(current_param);
2313 exec_eval_cleanup(estate);
2317 plpgsql_dstring_append_char(&ds, cp[0]);
2321 * If more parameters were specified than were required to process the
2322 * format string, throw an error
2324 if (current_param != NULL)
2326 (errcode(ERRCODE_SYNTAX_ERROR),
2327 errmsg("too many parameters specified for RAISE")));
2330 * Throw the error (may or may not come back)
2332 estate->err_text = raise_skip_msg; /* suppress traceback of raise */
2334 ereport(stmt->elog_level,
2335 ((stmt->elog_level >= ERROR) ? errcode(ERRCODE_RAISE_EXCEPTION) : 0,
2336 errmsg_internal("%s", plpgsql_dstring_get(&ds))));
2338 estate->err_text = NULL; /* un-suppress... */
2340 plpgsql_dstring_free(&ds);
2342 return PLPGSQL_RC_OK;
2347 * Initialize a mostly empty execution state
2351 plpgsql_estate_setup(PLpgSQL_execstate *estate,
2352 PLpgSQL_function *func,
2355 estate->retval = (Datum) 0;
2356 estate->retisnull = true;
2357 estate->rettype = InvalidOid;
2359 estate->fn_rettype = func->fn_rettype;
2360 estate->retistuple = func->fn_retistuple;
2361 estate->retisset = func->fn_retset;
2363 estate->readonly_func = func->fn_readonly;
2365 estate->rettupdesc = NULL;
2366 estate->exitlabel = NULL;
2368 estate->tuple_store = NULL;
2369 estate->tuple_store_cxt = NULL;
2372 estate->trig_nargs = 0;
2373 estate->trig_argv = NULL;
2375 estate->found_varno = func->found_varno;
2376 estate->ndatums = func->ndatums;
2377 estate->datums = palloc(sizeof(PLpgSQL_datum *) * estate->ndatums);
2378 /* caller is expected to fill the datums array */
2380 estate->eval_tuptable = NULL;
2381 estate->eval_processed = 0;
2382 estate->eval_lastoid = InvalidOid;
2384 estate->err_func = func;
2385 estate->err_stmt = NULL;
2386 estate->err_text = NULL;
2389 * Create an EState and ExprContext for evaluation of simple expressions.
2391 plpgsql_create_econtext(estate);
2394 * Let the plugin see this function before we initialize any local
2395 * PL/pgSQL variables - note that we also give the plugin a few function
2396 * pointers so it can call back into PL/pgSQL for doing things like
2397 * variable assignments and stack traces
2401 (*plugin_ptr)->error_callback = plpgsql_exec_error_callback;
2402 (*plugin_ptr)->assign_expr = exec_assign_expr;
2404 if ((*plugin_ptr)->func_setup)
2405 ((*plugin_ptr)->func_setup) (estate, func);
2410 * Release temporary memory used by expression/subselect evaluation
2412 * NB: the result of the evaluation is no longer valid after this is done,
2413 * unless it is a pass-by-value datatype.
2417 exec_eval_cleanup(PLpgSQL_execstate *estate)
2419 /* Clear result of a full SPI_execute */
2420 if (estate->eval_tuptable != NULL)
2421 SPI_freetuptable(estate->eval_tuptable);
2422 estate->eval_tuptable = NULL;
2424 /* Clear result of exec_eval_simple_expr (but keep the econtext) */
2425 if (estate->eval_econtext != NULL)
2426 ResetExprContext(estate->eval_econtext);
2431 * Generate a prepared plan
2435 exec_prepare_plan(PLpgSQL_execstate *estate,
2436 PLpgSQL_expr *expr, int cursorOptions)
2443 * We need a temporary argtypes array to load with data. (The finished
2444 * plan structure will contain a copy of it.)
2446 argtypes = (Oid *) palloc(expr->nparams * sizeof(Oid));
2448 for (i = 0; i < expr->nparams; i++)
2453 exec_eval_datum(estate, estate->datums[expr->params[i]],
2455 &argtypes[i], ¶mval, ¶misnull);
2459 * Generate and save the plan
2461 plan = SPI_prepare_cursor(expr->query, expr->nparams, argtypes,
2465 /* Some SPI errors deserve specific error messages */
2468 case SPI_ERROR_COPY:
2470 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2471 errmsg("cannot COPY to/from client in PL/pgSQL")));
2472 case SPI_ERROR_TRANSACTION:
2474 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2475 errmsg("cannot begin/end transactions in PL/pgSQL"),
2476 errhint("Use a BEGIN block with an EXCEPTION clause instead.")));
2478 elog(ERROR, "SPI_prepare_cursor failed for \"%s\": %s",
2479 expr->query, SPI_result_code_string(SPI_result));
2482 expr->plan = SPI_saveplan(plan);
2485 expr->plan_argtypes = plan->argtypes;
2486 exec_simple_check_plan(expr);
2493 * exec_stmt_execsql Execute an SQL statement (possibly with INTO).
2497 exec_stmt_execsql(PLpgSQL_execstate *estate,
2498 PLpgSQL_stmt_execsql *stmt)
2504 PLpgSQL_expr *expr = stmt->sqlstmt;
2507 * On the first call for this statement generate the plan, and detect
2508 * whether the statement is INSERT/UPDATE/DELETE
2510 if (expr->plan == NULL)
2514 exec_prepare_plan(estate, expr, 0);
2515 stmt->mod_stmt = false;
2516 foreach(l, expr->plan->plancache_list)
2518 CachedPlanSource *plansource = (CachedPlanSource *) lfirst(l);
2521 foreach(l2, plansource->plan->stmt_list)
2523 PlannedStmt *p = (PlannedStmt *) lfirst(l2);
2525 if (IsA(p, PlannedStmt) &&
2528 if (p->commandType == CMD_INSERT ||
2529 p->commandType == CMD_UPDATE ||
2530 p->commandType == CMD_DELETE)
2531 stmt->mod_stmt = true;
2538 * Now build up the values and nulls arguments for SPI_execute_plan()
2540 eval_expr_params(estate, expr, &values, &nulls);
2543 * If we have INTO, then we only need one row back ... but if we have INTO
2544 * STRICT, ask for two rows, so that we can verify the statement returns
2545 * only one. INSERT/UPDATE/DELETE are always treated strictly. Without
2546 * INTO, just run the statement to completion (tcount = 0).
2548 * We could just ask for two rows always when using INTO, but there are
2549 * some cases where demanding the extra row costs significant time, eg by
2550 * forcing completion of a sequential scan. So don't do it unless we need
2551 * to enforce strictness.
2555 if (stmt->strict || stmt->mod_stmt)
2566 rc = SPI_execute_plan(expr->plan, values, nulls,
2567 estate->readonly_func, tcount);
2570 * Check for error, and set FOUND if appropriate (for historical reasons
2571 * we set FOUND only for certain query types). Also Assert that we
2572 * identified the statement type the same as SPI did.
2577 Assert(!stmt->mod_stmt);
2578 exec_set_found(estate, (SPI_processed != 0));
2584 case SPI_OK_INSERT_RETURNING:
2585 case SPI_OK_UPDATE_RETURNING:
2586 case SPI_OK_DELETE_RETURNING:
2587 Assert(stmt->mod_stmt);
2588 exec_set_found(estate, (SPI_processed != 0));
2591 case SPI_OK_SELINTO:
2592 case SPI_OK_UTILITY:
2593 Assert(!stmt->mod_stmt);
2597 elog(ERROR, "SPI_execute_plan failed executing query \"%s\": %s",
2598 expr->query, SPI_result_code_string(rc));
2601 /* All variants should save result info for GET DIAGNOSTICS */
2602 estate->eval_processed = SPI_processed;
2603 estate->eval_lastoid = SPI_lastoid;
2605 /* Process INTO if present */
2608 SPITupleTable *tuptab = SPI_tuptable;
2609 uint32 n = SPI_processed;
2610 PLpgSQL_rec *rec = NULL;
2611 PLpgSQL_row *row = NULL;
2613 /* If the statement did not return a tuple table, complain */
2616 (errcode(ERRCODE_SYNTAX_ERROR),
2617 errmsg("INTO used with a command that cannot return data")));
2619 /* Determine if we assign to a record or a row */
2620 if (stmt->rec != NULL)
2621 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
2622 else if (stmt->row != NULL)
2623 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
2625 elog(ERROR, "unsupported target");
2628 * If SELECT ... INTO specified STRICT, and the query didn't find
2629 * exactly one row, throw an error. If STRICT was not specified, then
2630 * allow the query to find any number of rows.
2636 (errcode(ERRCODE_NO_DATA_FOUND),
2637 errmsg("query returned no rows")));
2638 /* set the target to NULL(s) */
2639 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
2643 if (n > 1 && (stmt->strict || stmt->mod_stmt))
2645 (errcode(ERRCODE_TOO_MANY_ROWS),
2646 errmsg("query returned more than one row")));
2647 /* Put the first result row into the target */
2648 exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
2652 SPI_freetuptable(SPI_tuptable);
2656 /* If the statement returned a tuple table, complain */
2657 if (SPI_tuptable != NULL)
2659 (errcode(ERRCODE_SYNTAX_ERROR),
2660 errmsg("query has no destination for result data"),
2661 (rc == SPI_OK_SELECT) ? errhint("If you want to discard the results of a SELECT, use PERFORM instead.") : 0));
2667 return PLPGSQL_RC_OK;
2672 * exec_stmt_dynexecute Execute a dynamic SQL query
2673 * (possibly with INTO).
2677 exec_stmt_dynexecute(PLpgSQL_execstate *estate,
2678 PLpgSQL_stmt_dynexecute *stmt)
2681 bool isnull = false;
2687 * First we evaluate the string expression after the EXECUTE keyword. Its
2688 * result is the querystring we have to execute.
2690 query = exec_eval_expr(estate, stmt->query, &isnull, &restype);
2693 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2694 errmsg("cannot EXECUTE a null querystring")));
2696 /* Get the C-String representation */
2697 querystr = convert_value_to_string(query, restype);
2699 exec_eval_cleanup(estate);
2702 * Execute the query without preparing a saved plan.
2706 PreparedParamsData *ppd;
2708 ppd = exec_eval_using_params(estate, stmt->params);
2709 exec_res = SPI_execute_with_args(querystr,
2710 ppd->nargs, ppd->types,
2711 ppd->values, ppd->nulls,
2712 estate->readonly_func, 0);
2713 free_params_data(ppd);
2716 exec_res = SPI_execute(querystr, estate->readonly_func, 0);
2724 case SPI_OK_INSERT_RETURNING:
2725 case SPI_OK_UPDATE_RETURNING:
2726 case SPI_OK_DELETE_RETURNING:
2727 case SPI_OK_UTILITY:
2733 * Also allow a zero return, which implies the querystring
2734 * contained no commands.
2738 case SPI_OK_SELINTO:
2741 * We want to disallow SELECT INTO for now, because its behavior
2742 * is not consistent with SELECT INTO in a normal plpgsql context.
2743 * (We need to reimplement EXECUTE to parse the string as a
2744 * plpgsql command, not just feed it to SPI_execute.) However,
2745 * CREATE AS should be allowed ... and since it produces the same
2746 * parsetree as SELECT INTO, there's no way to tell the difference
2747 * except to look at the source text. Wotta kluge!
2752 for (ptr = querystr; *ptr; ptr++)
2753 if (!scanner_isspace(*ptr))
2755 if (*ptr == 'S' || *ptr == 's')
2757 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2758 errmsg("EXECUTE of SELECT ... INTO is not implemented yet")));
2762 /* Some SPI errors deserve specific error messages */
2763 case SPI_ERROR_COPY:
2765 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2766 errmsg("cannot COPY to/from client in PL/pgSQL")));
2767 case SPI_ERROR_TRANSACTION:
2769 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2770 errmsg("cannot begin/end transactions in PL/pgSQL"),
2771 errhint("Use a BEGIN block with an EXCEPTION clause instead.")));
2774 elog(ERROR, "SPI_execute failed executing query \"%s\": %s",
2775 querystr, SPI_result_code_string(exec_res));
2779 /* Save result info for GET DIAGNOSTICS */
2780 estate->eval_processed = SPI_processed;
2781 estate->eval_lastoid = SPI_lastoid;
2783 /* Process INTO if present */
2786 SPITupleTable *tuptab = SPI_tuptable;
2787 uint32 n = SPI_processed;
2788 PLpgSQL_rec *rec = NULL;
2789 PLpgSQL_row *row = NULL;
2791 /* If the statement did not return a tuple table, complain */
2794 (errcode(ERRCODE_SYNTAX_ERROR),
2795 errmsg("INTO used with a command that cannot return data")));
2797 /* Determine if we assign to a record or a row */
2798 if (stmt->rec != NULL)
2799 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
2800 else if (stmt->row != NULL)
2801 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
2803 elog(ERROR, "unsupported target");
2806 * If SELECT ... INTO specified STRICT, and the query didn't find
2807 * exactly one row, throw an error. If STRICT was not specified, then
2808 * allow the query to find any number of rows.
2814 (errcode(ERRCODE_NO_DATA_FOUND),
2815 errmsg("query returned no rows")));
2816 /* set the target to NULL(s) */
2817 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
2821 if (n > 1 && stmt->strict)
2823 (errcode(ERRCODE_TOO_MANY_ROWS),
2824 errmsg("query returned more than one row")));
2825 /* Put the first result row into the target */
2826 exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
2832 * It might be a good idea to raise an error if the query returned
2833 * tuples that are being ignored, but historically we have not done
2838 /* Release any result from SPI_execute, as well as the querystring */
2839 SPI_freetuptable(SPI_tuptable);
2842 return PLPGSQL_RC_OK;
2847 * exec_stmt_dynfors Execute a dynamic query, assign each
2848 * tuple to a record or row and
2849 * execute a group of statements
2854 exec_stmt_dynfors(PLpgSQL_execstate *estate, PLpgSQL_stmt_dynfors *stmt)
2859 portal = exec_dynquery_with_params(estate, stmt->query, stmt->params);
2864 rc = exec_for_query(estate, (PLpgSQL_stmt_forq *) stmt, portal, true);
2867 * Close the implicit cursor
2869 SPI_cursor_close(portal);
2876 * exec_stmt_open Execute an OPEN cursor statement
2880 exec_stmt_open(PLpgSQL_execstate *estate, PLpgSQL_stmt_open *stmt)
2882 PLpgSQL_var *curvar;
2883 char *curname = NULL;
2884 PLpgSQL_expr *query;
2891 * Get the cursor variable and if it has an assigned name, check
2892 * that it's not in use currently.
2895 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
2896 if (!curvar->isnull)
2898 curname = TextDatumGetCString(curvar->value);
2899 if (SPI_cursor_find(curname) != NULL)
2901 (errcode(ERRCODE_DUPLICATE_CURSOR),
2902 errmsg("cursor \"%s\" already in use", curname)));
2906 * Process the OPEN according to it's type.
2909 if (stmt->query != NULL)
2912 * This is an OPEN refcursor FOR SELECT ...
2914 * We just make sure the query is planned. The real work is
2918 query = stmt->query;
2919 if (query->plan == NULL)
2920 exec_prepare_plan(estate, query, stmt->cursor_options);
2922 else if (stmt->dynquery != NULL)
2925 * This is an OPEN refcursor FOR EXECUTE ...
2934 * We evaluate the string expression after the
2935 * EXECUTE keyword. It's result is the querystring we have
2939 queryD = exec_eval_expr(estate, stmt->dynquery, &isnull, &restype);
2942 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2943 errmsg("cannot EXECUTE a null querystring")));
2945 /* Get the C-String representation */
2946 querystr = convert_value_to_string(queryD, restype);
2948 exec_eval_cleanup(estate);
2951 * Now we prepare a query plan for it and open a cursor
2954 curplan = SPI_prepare_cursor(querystr, 0, NULL, stmt->cursor_options);
2955 if (curplan == NULL)
2956 elog(ERROR, "SPI_prepare_cursor failed for \"%s\": %s",
2957 querystr, SPI_result_code_string(SPI_result));
2958 portal = SPI_cursor_open(curname, curplan, NULL, NULL,
2959 estate->readonly_func);
2961 elog(ERROR, "could not open cursor for query \"%s\": %s",
2962 querystr, SPI_result_code_string(SPI_result));
2964 SPI_freeplan(curplan);
2967 * If cursor variable was NULL, store the generated portal name in it
2969 if (curname == NULL)
2970 assign_text_var(curvar, portal->name);
2972 return PLPGSQL_RC_OK;
2977 * This is an OPEN cursor
2979 * Note: parser should already have checked that statement supplies
2980 * args iff cursor needs them, but we check again to be safe.
2983 if (stmt->argquery != NULL)
2986 * OPEN CURSOR with args. We fake a SELECT ... INTO ...
2987 * statement to evaluate the args and put 'em into the
2991 PLpgSQL_stmt_execsql set_args;
2993 if (curvar->cursor_explicit_argrow < 0)
2995 (errcode(ERRCODE_SYNTAX_ERROR),
2996 errmsg("arguments given for cursor without arguments")));
2998 memset(&set_args, 0, sizeof(set_args));
2999 set_args.cmd_type = PLPGSQL_STMT_EXECSQL;
3000 set_args.lineno = stmt->lineno;
3001 set_args.sqlstmt = stmt->argquery;
3002 set_args.into = true;
3003 /* XXX historically this has not been STRICT */
3004 set_args.row = (PLpgSQL_row *)
3005 (estate->datums[curvar->cursor_explicit_argrow]);
3007 if (exec_stmt_execsql(estate, &set_args) != PLPGSQL_RC_OK)
3008 elog(ERROR, "open cursor failed during argument processing");
3012 if (curvar->cursor_explicit_argrow >= 0)
3014 (errcode(ERRCODE_SYNTAX_ERROR),
3015 errmsg("arguments required for cursor")));
3018 query = curvar->cursor_explicit_expr;
3019 if (query->plan == NULL)
3020 exec_prepare_plan(estate, query, curvar->cursor_options);
3024 * Now build up the values and nulls arguments for SPI_execute_plan()
3026 eval_expr_params(estate, query, &values, &nulls);
3031 portal = SPI_cursor_open(curname, query->plan, values, nulls,
3032 estate->readonly_func);
3034 elog(ERROR, "could not open cursor: %s",
3035 SPI_result_code_string(SPI_result));
3038 * If cursor variable was NULL, store the generated portal name in it
3040 if (curname == NULL)
3041 assign_text_var(curvar, portal->name);
3048 return PLPGSQL_RC_OK;
3053 * exec_stmt_fetch Fetch from a cursor into a target, or just
3054 * move the current position of the cursor
3058 exec_stmt_fetch(PLpgSQL_execstate *estate, PLpgSQL_stmt_fetch *stmt)
3060 PLpgSQL_var *curvar = NULL;
3061 PLpgSQL_rec *rec = NULL;
3062 PLpgSQL_row *row = NULL;
3063 long how_many = stmt->how_many;
3064 SPITupleTable *tuptab;
3070 * Get the portal of the cursor by name
3073 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
3076 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3077 errmsg("cursor variable \"%s\" is NULL", curvar->refname)));
3078 curname = TextDatumGetCString(curvar->value);
3080 portal = SPI_cursor_find(curname);
3083 (errcode(ERRCODE_UNDEFINED_CURSOR),
3084 errmsg("cursor \"%s\" does not exist", curname)));
3087 /* Calculate position for FETCH_RELATIVE or FETCH_ABSOLUTE */
3092 /* XXX should be doing this in LONG not INT width */
3093 how_many = exec_eval_integer(estate, stmt->expr, &isnull);
3097 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3098 errmsg("relative or absolute cursor position is NULL")));
3100 exec_eval_cleanup(estate);
3106 * Determine if we fetch into a record or a row
3109 if (stmt->rec != NULL)
3110 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
3111 else if (stmt->row != NULL)
3112 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
3114 elog(ERROR, "unsupported target");
3117 * Fetch 1 tuple from the cursor
3120 SPI_scroll_cursor_fetch(portal, stmt->direction, how_many);
3121 tuptab = SPI_tuptable;
3125 * Set the target and the global FOUND variable appropriately.
3130 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
3131 exec_set_found(estate, false);
3135 exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
3136 exec_set_found(estate, true);
3139 SPI_freetuptable(tuptab);
3143 /* Move the cursor */
3144 SPI_scroll_cursor_move(portal, stmt->direction, how_many);
3147 /* Set the global FOUND variable appropriately. */
3148 exec_set_found(estate, n != 0);
3151 return PLPGSQL_RC_OK;
3155 * exec_stmt_close Close a cursor
3159 exec_stmt_close(PLpgSQL_execstate *estate, PLpgSQL_stmt_close *stmt)
3161 PLpgSQL_var *curvar = NULL;
3166 * Get the portal of the cursor by name
3169 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
3172 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3173 errmsg("cursor variable \"%s\" is NULL", curvar->refname)));
3174 curname = TextDatumGetCString(curvar->value);
3176 portal = SPI_cursor_find(curname);
3179 (errcode(ERRCODE_UNDEFINED_CURSOR),
3180 errmsg("cursor \"%s\" does not exist", curname)));
3187 SPI_cursor_close(portal);
3189 return PLPGSQL_RC_OK;
3194 * exec_assign_expr Put an expression's result into
3199 exec_assign_expr(PLpgSQL_execstate *estate, PLpgSQL_datum *target,
3204 bool isnull = false;
3206 value = exec_eval_expr(estate, expr, &isnull, &valtype);
3207 exec_assign_value(estate, target, value, valtype, &isnull);
3208 exec_eval_cleanup(estate);
3213 * exec_assign_value Put a value into a target field
3217 exec_assign_value(PLpgSQL_execstate *estate,
3218 PLpgSQL_datum *target,
3219 Datum value, Oid valtype, bool *isNull)
3221 switch (target->dtype)
3223 case PLPGSQL_DTYPE_VAR:
3226 * Target is a variable
3228 PLpgSQL_var *var = (PLpgSQL_var *) target;
3231 newvalue = exec_cast_value(value, valtype, var->datatype->typoid,
3232 &(var->datatype->typinput),
3233 var->datatype->typioparam,
3234 var->datatype->atttypmod,
3237 if (*isNull && var->notnull)
3239 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3240 errmsg("NULL cannot be assigned to variable \"%s\" declared NOT NULL",
3244 * If type is by-reference, make sure we have a freshly
3245 * palloc'd copy; the originally passed value may not live as
3246 * long as the variable! But we don't need to re-copy if
3247 * exec_cast_value performed a conversion; its output must
3248 * already be palloc'd.
3250 if (!var->datatype->typbyval && !*isNull)
3252 if (newvalue == value)
3253 newvalue = datumCopy(newvalue,
3255 var->datatype->typlen);
3259 * Now free the old value. (We can't do this any earlier
3260 * because of the possibility that we are assigning the var's
3261 * old value to it, eg "foo := foo". We could optimize out
3262 * the assignment altogether in such cases, but it's too
3263 * infrequent to be worth testing for.)
3267 var->value = newvalue;
3268 var->isnull = *isNull;
3269 if (!var->datatype->typbyval && !*isNull)
3270 var->freeval = true;
3274 case PLPGSQL_DTYPE_ROW:
3277 * Target is a row variable
3279 PLpgSQL_row *row = (PLpgSQL_row *) target;
3281 /* Source must be of RECORD or composite type */
3282 if (!type_is_rowtype(valtype))
3284 (errcode(ERRCODE_DATATYPE_MISMATCH),
3285 errmsg("cannot assign non-composite value to a row variable")));
3288 /* If source is null, just assign nulls to the row */
3289 exec_move_row(estate, NULL, row, NULL, NULL);
3297 HeapTupleData tmptup;
3299 /* Else source is a tuple Datum, safe to do this: */
3300 td = DatumGetHeapTupleHeader(value);
3301 /* Extract rowtype info and find a tupdesc */
3302 tupType = HeapTupleHeaderGetTypeId(td);
3303 tupTypmod = HeapTupleHeaderGetTypMod(td);
3304 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
3305 /* Build a temporary HeapTuple control structure */
3306 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
3307 ItemPointerSetInvalid(&(tmptup.t_self));
3308 tmptup.t_tableOid = InvalidOid;
3310 exec_move_row(estate, NULL, row, &tmptup, tupdesc);
3311 ReleaseTupleDesc(tupdesc);
3316 case PLPGSQL_DTYPE_REC:
3319 * Target is a record variable
3321 PLpgSQL_rec *rec = (PLpgSQL_rec *) target;
3323 /* Source must be of RECORD or composite type */
3324 if (!type_is_rowtype(valtype))
3326 (errcode(ERRCODE_DATATYPE_MISMATCH),
3327 errmsg("cannot assign non-composite value to a record variable")));
3330 /* If source is null, just assign nulls to the record */
3331 exec_move_row(estate, rec, NULL, NULL, NULL);
3339 HeapTupleData tmptup;
3341 /* Else source is a tuple Datum, safe to do this: */
3342 td = DatumGetHeapTupleHeader(value);
3343 /* Extract rowtype info and find a tupdesc */
3344 tupType = HeapTupleHeaderGetTypeId(td);
3345 tupTypmod = HeapTupleHeaderGetTypMod(td);
3346 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
3347 /* Build a temporary HeapTuple control structure */
3348 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
3349 ItemPointerSetInvalid(&(tmptup.t_self));
3350 tmptup.t_tableOid = InvalidOid;
3352 exec_move_row(estate, rec, NULL, &tmptup, tupdesc);
3353 ReleaseTupleDesc(tupdesc);
3358 case PLPGSQL_DTYPE_RECFIELD:
3361 * Target is a field of a record
3363 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) target;
3376 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
3379 * Check that there is already a tuple in the record. We need
3380 * that because records don't have any predefined field
3383 if (!HeapTupleIsValid(rec->tup))
3385 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3386 errmsg("record \"%s\" is not assigned yet",
3388 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
3391 * Get the number of the records field to change and the
3392 * number of attributes in the tuple.
3394 fno = SPI_fnumber(rec->tupdesc, recfield->fieldname);
3395 if (fno == SPI_ERROR_NOATTRIBUTE)
3397 (errcode(ERRCODE_UNDEFINED_COLUMN),
3398 errmsg("record \"%s\" has no field \"%s\"",
3399 rec->refname, recfield->fieldname)));
3401 natts = rec->tupdesc->natts;
3404 * Set up values/datums arrays for heap_formtuple. For all
3405 * the attributes except the one we want to replace, use the
3406 * value that's in the old tuple.
3408 values = palloc(sizeof(Datum) * natts);
3409 nulls = palloc(natts);
3411 for (i = 0; i < natts; i++)
3415 values[i] = SPI_getbinval(rec->tup, rec->tupdesc,
3424 * Now insert the new value, being careful to cast it to the
3427 atttype = SPI_gettypeid(rec->tupdesc, fno + 1);
3428 atttypmod = rec->tupdesc->attrs[fno]->atttypmod;
3429 attisnull = *isNull;
3430 values[fno] = exec_simple_cast_value(value,
3441 * Avoid leaking the result of exec_simple_cast_value, if it
3442 * performed a conversion to a pass-by-ref type.
3444 if (!attisnull && values[fno] != value && !get_typbyval(atttype))
3445 mustfree = DatumGetPointer(values[fno]);
3450 * Now call heap_formtuple() to create a new tuple that
3451 * replaces the old one in the record.
3453 newtup = heap_formtuple(rec->tupdesc, values, nulls);
3456 heap_freetuple(rec->tup);
3459 rec->freetup = true;
3469 case PLPGSQL_DTYPE_ARRAYELEM:
3473 PLpgSQL_expr *subscripts[MAXDIM];
3474 int subscriptvals[MAXDIM];
3475 bool oldarrayisnull;
3482 Datum oldarraydatum,
3484 ArrayType *oldarrayval;
3485 ArrayType *newarrayval;
3488 * Target is an element of an array
3490 * To handle constructs like x[1][2] := something, we have to
3491 * be prepared to deal with a chain of arrayelem datums. Chase
3492 * back to find the base array datum, and save the subscript
3493 * expressions as we go. (We are scanning right to left here,
3494 * but want to evaluate the subscripts left-to-right to
3495 * minimize surprises.)
3500 PLpgSQL_arrayelem *arrayelem = (PLpgSQL_arrayelem *) target;
3502 if (nsubscripts >= MAXDIM)
3504 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
3505 errmsg("number of array dimensions exceeds the maximum allowed, %d",
3507 subscripts[nsubscripts++] = arrayelem->subscript;
3508 target = estate->datums[arrayelem->arrayparentno];
3509 } while (target->dtype == PLPGSQL_DTYPE_ARRAYELEM);
3511 /* Fetch current value of array datum */
3512 exec_eval_datum(estate, target, InvalidOid,
3513 &arraytypeid, &oldarraydatum, &oldarrayisnull);
3515 arrayelemtypeid = get_element_type(arraytypeid);
3516 if (!OidIsValid(arrayelemtypeid))
3518 (errcode(ERRCODE_DATATYPE_MISMATCH),
3519 errmsg("subscripted object is not an array")));
3521 get_typlenbyvalalign(arrayelemtypeid,
3525 arraytyplen = get_typlen(arraytypeid);
3528 * Evaluate the subscripts, switch into left-to-right order.
3529 * Like ExecEvalArrayRef(), complain if any subscript is null.
3531 for (i = 0; i < nsubscripts; i++)
3536 exec_eval_integer(estate,
3537 subscripts[nsubscripts - 1 - i],
3541 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3542 errmsg("array subscript in assignment must not be NULL")));
3545 /* Coerce source value to match array element type. */
3546 coerced_value = exec_simple_cast_value(value,
3553 * If the original array is null, cons up an empty array so
3554 * that the assignment can proceed; we'll end with a
3555 * one-element array containing just the assigned-to
3556 * subscript. This only works for varlena arrays, though; for
3557 * fixed-length array types we skip the assignment. We can't
3558 * support assignment of a null entry into a fixed-length
3559 * array, either, so that's a no-op too. This is all ugly but
3560 * corresponds to the current behavior of ExecEvalArrayRef().
3562 if (arraytyplen > 0 && /* fixed-length array? */
3563 (oldarrayisnull || *isNull))
3567 oldarrayval = construct_empty_array(arrayelemtypeid);
3569 oldarrayval = (ArrayType *) DatumGetPointer(oldarraydatum);
3572 * Build the modified array value.
3574 newarrayval = array_set(oldarrayval,
3585 * Avoid leaking the result of exec_simple_cast_value, if it
3586 * performed a conversion to a pass-by-ref type.
3588 if (!*isNull && coerced_value != value && !elemtypbyval)
3589 pfree(DatumGetPointer(coerced_value));
3592 * Assign the new array to the base variable. It's never NULL
3596 exec_assign_value(estate, target,
3597 PointerGetDatum(newarrayval),
3598 arraytypeid, isNull);
3601 * Avoid leaking the modified array value, too.
3608 elog(ERROR, "unrecognized dtype: %d", target->dtype);
3613 * exec_eval_datum Get current value of a PLpgSQL_datum
3615 * The type oid, value in Datum format, and null flag are returned.
3617 * If expectedtypeid isn't InvalidOid, it is checked against the actual type.
3619 * At present this doesn't handle PLpgSQL_expr or PLpgSQL_arrayelem datums.
3621 * NOTE: caller must not modify the returned value, since it points right
3622 * at the stored value in the case of pass-by-reference datatypes. In some
3623 * cases we have to palloc a return value, and in such cases we put it into
3624 * the estate's short-term memory context.
3627 exec_eval_datum(PLpgSQL_execstate *estate,
3628 PLpgSQL_datum *datum,
3634 MemoryContext oldcontext;
3636 switch (datum->dtype)
3638 case PLPGSQL_DTYPE_VAR:
3640 PLpgSQL_var *var = (PLpgSQL_var *) datum;
3642 *typeid = var->datatype->typoid;
3643 *value = var->value;
3644 *isnull = var->isnull;
3645 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3647 (errcode(ERRCODE_DATATYPE_MISMATCH),
3648 errmsg("type of \"%s\" does not match that when preparing the plan",
3653 case PLPGSQL_DTYPE_ROW:
3655 PLpgSQL_row *row = (PLpgSQL_row *) datum;
3658 if (!row->rowtupdesc) /* should not happen */
3659 elog(ERROR, "row variable has no tupdesc");
3660 /* Make sure we have a valid type/typmod setting */
3661 BlessTupleDesc(row->rowtupdesc);
3662 oldcontext = MemoryContextSwitchTo(estate->eval_econtext->ecxt_per_tuple_memory);
3663 tup = make_tuple_from_row(estate, row, row->rowtupdesc);
3664 if (tup == NULL) /* should not happen */
3665 elog(ERROR, "row not compatible with its own tupdesc");
3666 MemoryContextSwitchTo(oldcontext);
3667 *typeid = row->rowtupdesc->tdtypeid;
3668 *value = HeapTupleGetDatum(tup);
3670 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3672 (errcode(ERRCODE_DATATYPE_MISMATCH),
3673 errmsg("type of \"%s\" does not match that when preparing the plan",
3678 case PLPGSQL_DTYPE_REC:
3680 PLpgSQL_rec *rec = (PLpgSQL_rec *) datum;
3681 HeapTupleData worktup;
3683 if (!HeapTupleIsValid(rec->tup))
3685 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3686 errmsg("record \"%s\" is not assigned yet",
3688 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
3689 Assert(rec->tupdesc != NULL);
3690 /* Make sure we have a valid type/typmod setting */
3691 BlessTupleDesc(rec->tupdesc);
3694 * In a trigger, the NEW and OLD parameters are likely to be
3695 * on-disk tuples that don't have the desired Datum fields.
3696 * Copy the tuple body and insert the right values.
3698 oldcontext = MemoryContextSwitchTo(estate->eval_econtext->ecxt_per_tuple_memory);
3699 heap_copytuple_with_tuple(rec->tup, &worktup);
3700 HeapTupleHeaderSetDatumLength(worktup.t_data, worktup.t_len);
3701 HeapTupleHeaderSetTypeId(worktup.t_data, rec->tupdesc->tdtypeid);
3702 HeapTupleHeaderSetTypMod(worktup.t_data, rec->tupdesc->tdtypmod);
3703 MemoryContextSwitchTo(oldcontext);
3704 *typeid = rec->tupdesc->tdtypeid;
3705 *value = HeapTupleGetDatum(&worktup);
3707 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3709 (errcode(ERRCODE_DATATYPE_MISMATCH),
3710 errmsg("type of \"%s\" does not match that when preparing the plan",
3715 case PLPGSQL_DTYPE_RECFIELD:
3717 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) datum;
3721 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
3722 if (!HeapTupleIsValid(rec->tup))
3724 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3725 errmsg("record \"%s\" is not assigned yet",
3727 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
3728 fno = SPI_fnumber(rec->tupdesc, recfield->fieldname);
3729 if (fno == SPI_ERROR_NOATTRIBUTE)
3731 (errcode(ERRCODE_UNDEFINED_COLUMN),
3732 errmsg("record \"%s\" has no field \"%s\"",
3733 rec->refname, recfield->fieldname)));
3734 *typeid = SPI_gettypeid(rec->tupdesc, fno);
3735 *value = SPI_getbinval(rec->tup, rec->tupdesc, fno, isnull);
3736 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3738 (errcode(ERRCODE_DATATYPE_MISMATCH),
3739 errmsg("type of \"%s.%s\" does not match that when preparing the plan",
3740 rec->refname, recfield->fieldname)));
3744 case PLPGSQL_DTYPE_TRIGARG:
3746 PLpgSQL_trigarg *trigarg = (PLpgSQL_trigarg *) datum;
3750 tgargno = exec_eval_integer(estate, trigarg->argnum, isnull);
3751 if (*isnull || tgargno < 0 || tgargno >= estate->trig_nargs)
3758 *value = estate->trig_argv[tgargno];
3761 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3763 (errcode(ERRCODE_DATATYPE_MISMATCH),
3764 errmsg("type of tgargv[%d] does not match that when preparing the plan",
3770 elog(ERROR, "unrecognized dtype: %d", datum->dtype);
3775 * exec_eval_integer Evaluate an expression, coerce result to int4
3777 * Note we do not do exec_eval_cleanup here; the caller must do it at
3778 * some later point. (We do this because the caller may be holding the
3779 * results of other, pass-by-reference, expression evaluations, such as
3780 * an array value to be subscripted. Also see notes in exec_eval_simple_expr
3781 * about allocation of the parameter array.)
3785 exec_eval_integer(PLpgSQL_execstate *estate,
3792 exprdatum = exec_eval_expr(estate, expr, isNull, &exprtypeid);
3793 exprdatum = exec_simple_cast_value(exprdatum, exprtypeid,
3796 return DatumGetInt32(exprdatum);
3800 * exec_eval_boolean Evaluate an expression, coerce result to bool
3802 * Note we do not do exec_eval_cleanup here; the caller must do it at
3807 exec_eval_boolean(PLpgSQL_execstate *estate,
3814 exprdatum = exec_eval_expr(estate, expr, isNull, &exprtypeid);
3815 exprdatum = exec_simple_cast_value(exprdatum, exprtypeid,
3818 return DatumGetBool(exprdatum);
3822 * exec_eval_expr Evaluate an expression and return
3825 * NOTE: caller must do exec_eval_cleanup when done with the Datum.
3829 exec_eval_expr(PLpgSQL_execstate *estate,
3838 * If first time through, create a plan for this expression.
3840 if (expr->plan == NULL)
3841 exec_prepare_plan(estate, expr, 0);
3844 * If this is a simple expression, bypass SPI and use the executor
3847 if (exec_eval_simple_expr(estate, expr, &result, isNull, rettype))
3851 * Else do it the hard way via exec_run_select
3853 rc = exec_run_select(estate, expr, 2, NULL);
3854 if (rc != SPI_OK_SELECT)
3856 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3857 errmsg("query \"%s\" did not return data", expr->query)));
3860 * If there are no rows selected, the result is NULL.
3862 if (estate->eval_processed == 0)
3869 * Check that the expression returned one single Datum
3871 if (estate->eval_processed > 1)
3873 (errcode(ERRCODE_CARDINALITY_VIOLATION),
3874 errmsg("query \"%s\" returned more than one row",
3876 if (estate->eval_tuptable->tupdesc->natts != 1)
3878 (errcode(ERRCODE_SYNTAX_ERROR),
3879 errmsg("query \"%s\" returned %d columns", expr->query,
3880 estate->eval_tuptable->tupdesc->natts)));
3883 * Return the result and its type
3885 *rettype = SPI_gettypeid(estate->eval_tuptable->tupdesc, 1);
3886 return SPI_getbinval(estate->eval_tuptable->vals[0],
3887 estate->eval_tuptable->tupdesc, 1, isNull);
3892 * exec_run_select Execute a select query
3896 exec_run_select(PLpgSQL_execstate *estate,
3897 PLpgSQL_expr *expr, long maxtuples, Portal *portalP)
3904 * On the first call for this expression generate the plan
3906 if (expr->plan == NULL)
3907 exec_prepare_plan(estate, expr, 0);
3910 * Now build up the values and nulls arguments for SPI_execute_plan()
3912 eval_expr_params(estate, expr, &values, &nulls);
3915 * If a portal was requested, put the query into the portal
3917 if (portalP != NULL)
3919 *portalP = SPI_cursor_open(NULL, expr->plan, values, nulls,
3920 estate->readonly_func);
3921 if (*portalP == NULL)
3922 elog(ERROR, "could not open implicit cursor for query \"%s\": %s",
3923 expr->query, SPI_result_code_string(SPI_result));
3926 return SPI_OK_CURSOR;
3932 rc = SPI_execute_plan(expr->plan, values, nulls,
3933 estate->readonly_func, maxtuples);
3934 if (rc != SPI_OK_SELECT)
3936 (errcode(ERRCODE_SYNTAX_ERROR),
3937 errmsg("query \"%s\" is not a SELECT", expr->query)));
3939 /* Save query results for eventual cleanup */
3940 Assert(estate->eval_tuptable == NULL);
3941 estate->eval_tuptable = SPI_tuptable;
3942 estate->eval_processed = SPI_processed;
3943 estate->eval_lastoid = SPI_lastoid;
3953 * exec_for_query --- execute body of FOR loop for each row from a portal
3955 * Used by exec_stmt_fors, exec_stmt_forc and exec_stmt_dynfors
3958 exec_for_query(PLpgSQL_execstate *estate, PLpgSQL_stmt_forq *stmt,
3959 Portal portal, bool prefetch_ok)
3961 PLpgSQL_rec *rec = NULL;
3962 PLpgSQL_row *row = NULL;
3963 SPITupleTable *tuptab;
3965 int rc = PLPGSQL_RC_OK;
3969 * Determine if we assign to a record or a row
3971 if (stmt->rec != NULL)
3972 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
3973 else if (stmt->row != NULL)
3974 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
3976 elog(ERROR, "unsupported target");
3979 * Fetch the initial tuple(s). If prefetching is allowed then we grab
3980 * a few more rows to avoid multiple trips through executor startup
3983 SPI_cursor_fetch(portal, true, prefetch_ok ? 10 : 1);
3984 tuptab = SPI_tuptable;
3988 * If the query didn't return any rows, set the target to NULL and
3989 * fall through with found = false.
3992 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
3994 found = true; /* processed at least one tuple */
4003 for (i = 0; i < n; i++)
4006 * Assign the tuple to the target
4008 exec_move_row(estate, rec, row, tuptab->vals[i], tuptab->tupdesc);
4011 * Execute the statements
4013 rc = exec_stmts(estate, stmt->body);
4015 if (rc != PLPGSQL_RC_OK)
4017 if (rc == PLPGSQL_RC_EXIT)
4019 if (estate->exitlabel == NULL)
4021 /* unlabelled exit, so exit the current loop */
4024 else if (stmt->label != NULL &&
4025 strcmp(stmt->label, estate->exitlabel) == 0)
4027 /* label matches this loop, so exit loop */
4028 estate->exitlabel = NULL;
4033 * otherwise, we processed a labelled exit that does not
4034 * match the current statement's label, if any; return
4035 * RC_EXIT so that the EXIT continues to recurse upward.
4038 else if (rc == PLPGSQL_RC_CONTINUE)
4040 if (estate->exitlabel == NULL)
4042 /* unlabelled continue, so re-run the current loop */
4046 else if (stmt->label != NULL &&
4047 strcmp(stmt->label, estate->exitlabel) == 0)
4049 /* label matches this loop, so re-run loop */
4050 estate->exitlabel = NULL;
4056 * otherwise, we process a labelled continue that does not
4057 * match the current statement's label, if any; return
4058 * RC_CONTINUE so that the CONTINUE will propagate up the
4064 * We're aborting the loop. Need a goto to get out of two
4071 SPI_freetuptable(tuptab);
4074 * Fetch more tuples. If prefetching is allowed, grab 50 at a time.
4076 SPI_cursor_fetch(portal, true, prefetch_ok ? 50 : 1);
4077 tuptab = SPI_tuptable;
4084 * Release last group of tuples (if any)
4086 SPI_freetuptable(tuptab);
4089 * Set the FOUND variable to indicate the result of executing the loop
4090 * (namely, whether we looped one or more times). This must be set last so
4091 * that it does not interfere with the value of the FOUND variable inside
4092 * the loop processing itself.
4094 exec_set_found(estate, found);
4101 * exec_eval_simple_expr - Evaluate a simple expression returning
4102 * a Datum by directly calling ExecEvalExpr().
4104 * If successful, store results into *result, *isNull, *rettype and return
4105 * TRUE. If the expression is not simple (any more), return FALSE.
4107 * It is possible though unlikely for a simple expression to become non-simple
4108 * (consider for example redefining a trivial view). We must handle that for
4109 * correctness; fortunately it's normally inexpensive to do
4110 * RevalidateCachedPlan on a simple expression. We do not consider the other
4111 * direction (non-simple expression becoming simple) because we'll still give
4112 * correct results if that happens, and it's unlikely to be worth the cycles
4115 * Note: if pass-by-reference, the result is in the eval_econtext's
4116 * temporary memory context. It will be freed when exec_eval_cleanup
4121 exec_eval_simple_expr(PLpgSQL_execstate *estate,
4127 ExprContext *econtext = estate->eval_econtext;
4128 CachedPlanSource *plansource;
4130 ParamListInfo paramLI;
4132 MemoryContext oldcontext;
4135 * Forget it if expression wasn't simple before.
4137 if (expr->expr_simple_expr == NULL)
4141 * Revalidate cached plan, so that we will notice if it became stale. (We
4142 * also need to hold a refcount while using the plan.) Note that even if
4143 * replanning occurs, the length of plancache_list can't change, since it
4144 * is a property of the raw parsetree generated from the query text.
4146 Assert(list_length(expr->plan->plancache_list) == 1);
4147 plansource = (CachedPlanSource *) linitial(expr->plan->plancache_list);
4148 cplan = RevalidateCachedPlan(plansource, true);
4149 if (cplan->generation != expr->expr_simple_generation)
4151 /* It got replanned ... is it still simple? */
4152 exec_simple_check_plan(expr);
4153 if (expr->expr_simple_expr == NULL)
4155 /* Ooops, release refcount and fail */
4156 ReleaseCachedPlan(cplan, true);
4162 * Pass back previously-determined result type.
4164 *rettype = expr->expr_simple_type;
4167 * Prepare the expression for execution, if it's not been done already in
4168 * the current eval_estate. (This will be forced to happen if we called
4169 * exec_simple_check_plan above.)
4171 if (expr->expr_simple_id != estate->eval_estate_simple_id)
4173 expr->expr_simple_state = ExecPrepareExpr(expr->expr_simple_expr,
4174 estate->eval_estate);
4175 expr->expr_simple_id = estate->eval_estate_simple_id;
4179 * Param list can live in econtext's temporary memory context.
4181 * XXX think about avoiding repeated palloc's for param lists? Beware
4182 * however that this routine is re-entrant: exec_eval_datum() can call it
4183 * back for subscript evaluation, and so there can be a need to have more
4184 * than one active param list.
4186 if (expr->nparams > 0)
4188 /* sizeof(ParamListInfoData) includes the first array element */
4189 paramLI = (ParamListInfo)
4190 MemoryContextAlloc(econtext->ecxt_per_tuple_memory,
4191 sizeof(ParamListInfoData) +
4192 (expr->nparams - 1) *sizeof(ParamExternData));
4193 paramLI->numParams = expr->nparams;
4195 for (i = 0; i < expr->nparams; i++)
4197 ParamExternData *prm = ¶mLI->params[i];
4198 PLpgSQL_datum *datum = estate->datums[expr->params[i]];
4201 exec_eval_datum(estate, datum, expr->plan_argtypes[i],
4203 &prm->value, &prm->isnull);
4210 * Now we can safely make the econtext point to the param list.
4212 econtext->ecxt_param_list_info = paramLI;
4215 * We have to do some of the things SPI_execute_plan would do, in
4216 * particular advance the snapshot if we are in a non-read-only function.
4217 * Without this, stable functions within the expression would fail to see
4218 * updates made so far by our own function.
4222 oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
4223 if (!estate->readonly_func)
4225 CommandCounterIncrement();
4226 PushActiveSnapshot(GetTransactionSnapshot());
4230 * Finally we can call the executor to evaluate the expression
4232 *result = ExecEvalExpr(expr->expr_simple_state,
4236 MemoryContextSwitchTo(oldcontext);
4238 if (!estate->readonly_func)
4239 PopActiveSnapshot();
4244 * Now we can release our refcount on the cached plan.
4246 ReleaseCachedPlan(cplan, true);
4256 * Build up the values and nulls arguments for SPI_execute_plan()
4259 eval_expr_params(PLpgSQL_execstate *estate,
4260 PLpgSQL_expr *expr, Datum **p_values, char **p_nulls)
4266 *p_values = values = (Datum *) palloc(expr->nparams * sizeof(Datum));
4267 *p_nulls = nulls = (char *) palloc(expr->nparams * sizeof(char));
4269 for (i = 0; i < expr->nparams; i++)
4271 PLpgSQL_datum *datum = estate->datums[expr->params[i]];
4275 exec_eval_datum(estate, datum, expr->plan_argtypes[i],
4276 ¶mtypeid, &values[i], ¶misnull);
4286 * exec_move_row Move one tuple's values into a record or row
4290 exec_move_row(PLpgSQL_execstate *estate,
4293 HeapTuple tup, TupleDesc tupdesc)
4296 * Record is simple - just copy the tuple and its descriptor into the
4302 * copy input first, just in case it is pointing at variable's value
4304 if (HeapTupleIsValid(tup))
4305 tup = heap_copytuple(tup);
4307 tupdesc = CreateTupleDescCopy(tupdesc);
4311 heap_freetuple(rec->tup);
4312 rec->freetup = false;
4314 if (rec->freetupdesc)
4316 FreeTupleDesc(rec->tupdesc);
4317 rec->freetupdesc = false;
4320 if (HeapTupleIsValid(tup))
4323 rec->freetup = true;
4327 /* If we have a tupdesc but no data, form an all-nulls tuple */
4330 nulls = (char *) palloc(tupdesc->natts * sizeof(char));
4331 memset(nulls, 'n', tupdesc->natts * sizeof(char));
4333 rec->tup = heap_formtuple(tupdesc, NULL, nulls);
4334 rec->freetup = true;
4343 rec->tupdesc = tupdesc;
4344 rec->freetupdesc = true;
4347 rec->tupdesc = NULL;
4353 * Row is a bit more complicated in that we assign the individual
4354 * attributes of the tuple to the variables the row points to.
4356 * NOTE: this code used to demand row->nfields ==
4357 * HeapTupleHeaderGetNatts(tup->t_data, but that's wrong. The tuple might
4358 * have more fields than we expected if it's from an inheritance-child
4359 * table of the current table, or it might have fewer if the table has had
4360 * columns added by ALTER TABLE. Ignore extra columns and assume NULL for
4361 * missing columns, the same as heap_getattr would do. We also have to
4362 * skip over dropped columns in either the source or destination.
4364 * If we have no tuple data at all, we'll assign NULL to all columns of
4373 if (HeapTupleIsValid(tup))
4374 t_natts = HeapTupleHeaderGetNatts(tup->t_data);
4379 for (fnum = 0; fnum < row->nfields; fnum++)
4386 if (row->varnos[fnum] < 0)
4387 continue; /* skip dropped column in row struct */
4389 var = (PLpgSQL_var *) (estate->datums[row->varnos[fnum]]);
4391 while (anum < t_natts && tupdesc->attrs[anum]->attisdropped)
4392 anum++; /* skip dropped column in tuple */
4396 value = SPI_getbinval(tup, tupdesc, anum + 1, &isnull);
4397 valtype = SPI_gettypeid(tupdesc, anum + 1);
4404 valtype = InvalidOid;
4407 exec_assign_value(estate, (PLpgSQL_datum *) var,
4408 value, valtype, &isnull);
4414 elog(ERROR, "unsupported target");
4418 * make_tuple_from_row Make a tuple from the values of a row object
4420 * A NULL return indicates rowtype mismatch; caller must raise suitable error
4424 make_tuple_from_row(PLpgSQL_execstate *estate,
4428 int natts = tupdesc->natts;
4434 if (natts != row->nfields)
4437 dvalues = (Datum *) palloc0(natts * sizeof(Datum));
4438 nulls = (bool *) palloc(natts * sizeof(bool));
4440 for (i = 0; i < natts; i++)
4444 if (tupdesc->attrs[i]->attisdropped)
4446 nulls[i] = true; /* leave the column as null */
4449 if (row->varnos[i] < 0) /* should not happen */
4450 elog(ERROR, "dropped rowtype entry for non-dropped column");
4452 exec_eval_datum(estate, estate->datums[row->varnos[i]],
4453 InvalidOid, &fieldtypeid, &dvalues[i], &nulls[i]);
4454 if (fieldtypeid != tupdesc->attrs[i]->atttypid)
4458 tuple = heap_form_tuple(tupdesc, dvalues, nulls);
4467 * convert_value_to_string Convert a non-null Datum to C string
4469 * Note: callers generally assume that the result is a palloc'd string and
4470 * should be pfree'd. This is not all that safe an assumption ...
4472 * Note: not caching the conversion function lookup is bad for performance.
4476 convert_value_to_string(Datum value, Oid valtype)
4482 getTypeOutputInfo(valtype, &typoutput, &typIsVarlena);
4485 * We do SPI_push to allow the datatype output function to use SPI.
4486 * However we do not mess around with CommandCounterIncrement or advancing
4487 * the snapshot, which means that a stable output function would not see
4488 * updates made so far by our own function. The use-case for such
4489 * scenarios seems too narrow to justify the cycles that would be
4494 str = OidOutputFunctionCall(typoutput, value);
4502 * exec_cast_value Cast a value if required
4506 exec_cast_value(Datum value, Oid valtype,
4514 * If the type of the queries return value isn't that of the variable,
4517 if (valtype != reqtype || reqtypmod != -1)
4523 extval = convert_value_to_string(value, valtype);
4525 /* Allow input function to use SPI ... see notes above */
4528 value = InputFunctionCall(reqinput, extval,
4529 reqtypioparam, reqtypmod);
4539 value = InputFunctionCall(reqinput, NULL,
4540 reqtypioparam, reqtypmod);
4550 * exec_simple_cast_value Cast a value if required
4552 * As above, but need not supply details about target type. Note that this
4553 * is slower than exec_cast_value with cached type info, and so should be
4554 * avoided in heavily used code paths.
4558 exec_simple_cast_value(Datum value, Oid valtype,
4559 Oid reqtype, int32 reqtypmod,
4564 if (valtype != reqtype || reqtypmod != -1)
4568 FmgrInfo finfo_input;
4570 getTypeInputInfo(reqtype, &typinput, &typioparam);
4572 fmgr_info(typinput, &finfo_input);
4574 value = exec_cast_value(value,
4589 * exec_simple_check_node - Recursively check if an expression
4590 * is made only of simple things we can
4591 * hand out directly to ExecEvalExpr()
4592 * instead of calling SPI.
4596 exec_simple_check_node(Node *node)
4601 switch (nodeTag(node))
4611 ArrayRef *expr = (ArrayRef *) node;
4613 if (!exec_simple_check_node((Node *) expr->refupperindexpr))
4615 if (!exec_simple_check_node((Node *) expr->reflowerindexpr))
4617 if (!exec_simple_check_node((Node *) expr->refexpr))
4619 if (!exec_simple_check_node((Node *) expr->refassgnexpr))
4627 FuncExpr *expr = (FuncExpr *) node;
4629 if (expr->funcretset)
4631 if (!exec_simple_check_node((Node *) expr->args))
4639 OpExpr *expr = (OpExpr *) node;
4643 if (!exec_simple_check_node((Node *) expr->args))
4649 case T_DistinctExpr:
4651 DistinctExpr *expr = (DistinctExpr *) node;
4655 if (!exec_simple_check_node((Node *) expr->args))
4661 case T_ScalarArrayOpExpr:
4663 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
4665 if (!exec_simple_check_node((Node *) expr->args))
4673 BoolExpr *expr = (BoolExpr *) node;
4675 if (!exec_simple_check_node((Node *) expr->args))
4682 return exec_simple_check_node((Node *) ((FieldSelect *) node)->arg);
4686 FieldStore *expr = (FieldStore *) node;
4688 if (!exec_simple_check_node((Node *) expr->arg))
4690 if (!exec_simple_check_node((Node *) expr->newvals))
4697 return exec_simple_check_node((Node *) ((RelabelType *) node)->arg);
4700 return exec_simple_check_node((Node *) ((CoerceViaIO *) node)->arg);
4702 case T_ArrayCoerceExpr:
4703 return exec_simple_check_node((Node *) ((ArrayCoerceExpr *) node)->arg);
4705 case T_ConvertRowtypeExpr:
4706 return exec_simple_check_node((Node *) ((ConvertRowtypeExpr *) node)->arg);
4710 CaseExpr *expr = (CaseExpr *) node;
4712 if (!exec_simple_check_node((Node *) expr->arg))
4714 if (!exec_simple_check_node((Node *) expr->args))
4716 if (!exec_simple_check_node((Node *) expr->defresult))
4724 CaseWhen *when = (CaseWhen *) node;
4726 if (!exec_simple_check_node((Node *) when->expr))
4728 if (!exec_simple_check_node((Node *) when->result))
4734 case T_CaseTestExpr:
4739 ArrayExpr *expr = (ArrayExpr *) node;
4741 if (!exec_simple_check_node((Node *) expr->elements))
4749 RowExpr *expr = (RowExpr *) node;
4751 if (!exec_simple_check_node((Node *) expr->args))
4757 case T_RowCompareExpr:
4759 RowCompareExpr *expr = (RowCompareExpr *) node;
4761 if (!exec_simple_check_node((Node *) expr->largs))
4763 if (!exec_simple_check_node((Node *) expr->rargs))
4769 case T_CoalesceExpr:
4771 CoalesceExpr *expr = (CoalesceExpr *) node;
4773 if (!exec_simple_check_node((Node *) expr->args))
4781 MinMaxExpr *expr = (MinMaxExpr *) node;
4783 if (!exec_simple_check_node((Node *) expr->args))
4791 XmlExpr *expr = (XmlExpr *) node;
4793 if (!exec_simple_check_node((Node *) expr->named_args))
4795 if (!exec_simple_check_node((Node *) expr->args))
4803 NullIfExpr *expr = (NullIfExpr *) node;
4807 if (!exec_simple_check_node((Node *) expr->args))
4814 return exec_simple_check_node((Node *) ((NullTest *) node)->arg);
4817 return exec_simple_check_node((Node *) ((BooleanTest *) node)->arg);
4819 case T_CoerceToDomain:
4820 return exec_simple_check_node((Node *) ((CoerceToDomain *) node)->arg);
4822 case T_CoerceToDomainValue:
4827 List *expr = (List *) node;
4832 if (!exec_simple_check_node(lfirst(l)))
4846 * exec_simple_check_plan - Check if a plan is simple enough to
4847 * be evaluated by ExecEvalExpr() instead
4852 exec_simple_check_plan(PLpgSQL_expr *expr)
4854 CachedPlanSource *plansource;
4860 * Initialize to "not simple", and remember the plan generation number we
4861 * last checked. (If the query produces more or less than one parsetree
4862 * we just leave expr_simple_generation set to 0.)
4864 expr->expr_simple_expr = NULL;
4865 expr->expr_simple_generation = 0;
4868 * 1. We can only evaluate queries that resulted in one single execution
4871 if (list_length(expr->plan->plancache_list) != 1)
4873 plansource = (CachedPlanSource *) linitial(expr->plan->plancache_list);
4874 expr->expr_simple_generation = plansource->generation;
4875 if (list_length(plansource->plan->stmt_list) != 1)
4878 stmt = (PlannedStmt *) linitial(plansource->plan->stmt_list);
4881 * 2. It must be a RESULT plan --> no scan's required
4883 if (!IsA(stmt, PlannedStmt))
4885 plan = stmt->planTree;
4886 if (!IsA(plan, Result))
4890 * 3. Can't have any subplan or qual clause, either
4892 if (plan->lefttree != NULL ||
4893 plan->righttree != NULL ||
4894 plan->initPlan != NULL ||
4895 plan->qual != NULL ||
4896 ((Result *) plan)->resconstantqual != NULL)
4900 * 4. The plan must have a single attribute as result
4902 if (list_length(plan->targetlist) != 1)
4905 tle = (TargetEntry *) linitial(plan->targetlist);
4908 * 5. Check that all the nodes in the expression are non-scary.
4910 if (!exec_simple_check_node((Node *) tle->expr))
4914 * Yes - this is a simple expression. Mark it as such, and initialize
4915 * state to "not valid in current transaction".
4917 expr->expr_simple_expr = tle->expr;
4918 expr->expr_simple_state = NULL;
4919 expr->expr_simple_id = -1;
4920 /* Also stash away the expression result type */
4921 expr->expr_simple_type = exprType((Node *) tle->expr);
4925 * Check two tupledescs have matching number and types of attributes
4928 compatible_tupdesc(TupleDesc td1, TupleDesc td2)
4932 if (td1->natts != td2->natts)
4935 for (i = 0; i < td1->natts; i++)
4937 if (td1->attrs[i]->atttypid != td2->attrs[i]->atttypid)
4945 * exec_set_found Set the global found variable
4950 exec_set_found(PLpgSQL_execstate *estate, bool state)
4954 var = (PLpgSQL_var *) (estate->datums[estate->found_varno]);
4955 var->value = PointerGetDatum(state);
4956 var->isnull = false;
4960 * plpgsql_create_econtext --- create an eval_econtext for the current function
4962 * We may need to create a new eval_estate too, if there's not one already
4963 * for the current (sub) transaction. The EState will be cleaned up at
4964 * (sub) transaction end.
4967 plpgsql_create_econtext(PLpgSQL_execstate *estate)
4969 SubTransactionId my_subxid = GetCurrentSubTransactionId();
4970 SimpleEstateStackEntry *entry = simple_estate_stack;
4972 /* Create new EState if not one for current subxact */
4973 if (entry == NULL ||
4974 entry->xact_subxid != my_subxid)
4976 MemoryContext oldcontext;
4978 /* Stack entries are kept in TopTransactionContext for simplicity */
4979 entry = (SimpleEstateStackEntry *)
4980 MemoryContextAlloc(TopTransactionContext,
4981 sizeof(SimpleEstateStackEntry));
4983 /* But each EState should be a child of its CurTransactionContext */
4984 oldcontext = MemoryContextSwitchTo(CurTransactionContext);
4985 entry->xact_eval_estate = CreateExecutorState();
4986 MemoryContextSwitchTo(oldcontext);
4988 /* Assign a reasonably-unique ID to this EState */
4989 entry->xact_estate_simple_id = simple_estate_id_counter++;
4990 entry->xact_subxid = my_subxid;
4992 entry->next = simple_estate_stack;
4993 simple_estate_stack = entry;
4996 /* Link plpgsql estate to it */
4997 estate->eval_estate = entry->xact_eval_estate;
4998 estate->eval_estate_simple_id = entry->xact_estate_simple_id;
5000 /* And create a child econtext for the current function */
5001 estate->eval_econtext = CreateExprContext(estate->eval_estate);
5005 * plpgsql_xact_cb --- post-transaction-commit-or-abort cleanup
5007 * If a simple-expression EState was created in the current transaction,
5008 * it has to be cleaned up.
5011 plpgsql_xact_cb(XactEvent event, void *arg)
5014 * If we are doing a clean transaction shutdown, free the EState (so that
5015 * any remaining resources will be released correctly). In an abort, we
5016 * expect the regular abort recovery procedures to release everything of
5017 * interest. We don't need to free the individual stack entries since
5018 * TopTransactionContext is about to go away anyway.
5020 * Note: if plpgsql_subxact_cb is doing its job, there should be at most
5021 * one stack entry, but we may as well code this as a loop.
5023 if (event != XACT_EVENT_ABORT)
5025 while (simple_estate_stack != NULL)
5027 FreeExecutorState(simple_estate_stack->xact_eval_estate);
5028 simple_estate_stack = simple_estate_stack->next;
5032 simple_estate_stack = NULL;
5036 * plpgsql_subxact_cb --- post-subtransaction-commit-or-abort cleanup
5038 * If a simple-expression EState was created in the current subtransaction,
5039 * it has to be cleaned up.
5042 plpgsql_subxact_cb(SubXactEvent event, SubTransactionId mySubid,
5043 SubTransactionId parentSubid, void *arg)
5045 if (event == SUBXACT_EVENT_START_SUB)
5048 if (simple_estate_stack != NULL &&
5049 simple_estate_stack->xact_subxid == mySubid)
5051 SimpleEstateStackEntry *next;
5053 if (event == SUBXACT_EVENT_COMMIT_SUB)
5054 FreeExecutorState(simple_estate_stack->xact_eval_estate);
5055 next = simple_estate_stack->next;
5056 pfree(simple_estate_stack);
5057 simple_estate_stack = next;
5062 * free_var --- pfree any pass-by-reference value of the variable.
5064 * This should always be followed by some assignment to var->value,
5065 * as it leaves a dangling pointer.
5068 free_var(PLpgSQL_var *var)
5072 pfree(DatumGetPointer(var->value));
5073 var->freeval = false;
5078 * free old value of a text variable and assign new value from C string
5081 assign_text_var(PLpgSQL_var *var, const char *str)
5084 var->value = CStringGetTextDatum(str);
5085 var->isnull = false;
5086 var->freeval = true;
5090 * exec_eval_using_params --- evaluate params of USING clause
5092 static PreparedParamsData *
5093 exec_eval_using_params(PLpgSQL_execstate *estate, List *params)
5095 PreparedParamsData *ppd;
5100 ppd = (PreparedParamsData *) palloc(sizeof(PreparedParamsData));
5101 nargs = list_length(params);
5104 ppd->types = (Oid *) palloc(nargs * sizeof(Oid));
5105 ppd->values = (Datum *) palloc(nargs * sizeof(Datum));
5106 ppd->nulls = (char *) palloc(nargs * sizeof(char));
5107 ppd->freevals = (bool *) palloc(nargs * sizeof(bool));
5112 PLpgSQL_expr *param = (PLpgSQL_expr *) lfirst(lc);
5115 ppd->values[i] = exec_eval_expr(estate, param,
5118 ppd->nulls[i] = isnull ? 'n' : ' ';
5119 ppd->freevals[i] = false;
5121 /* pass-by-ref non null values must be copied into plpgsql context */
5127 get_typlenbyval(ppd->types[i], &typLen, &typByVal);
5130 ppd->values[i] = datumCopy(ppd->values[i], typByVal, typLen);
5131 ppd->freevals[i] = true;
5135 exec_eval_cleanup(estate);
5144 * free_params_data --- pfree all pass-by-reference values used in USING clause
5147 free_params_data(PreparedParamsData *ppd)
5151 for (i = 0; i < ppd->nargs; i++)
5153 if (ppd->freevals[i])
5154 pfree(DatumGetPointer(ppd->values[i]));
5160 pfree(ppd->freevals);
5166 * Open portal for dynamic query
5169 exec_dynquery_with_params(PLpgSQL_execstate *estate, PLpgSQL_expr *dynquery,
5179 * Evaluate the string expression after the EXECUTE keyword. Its result
5180 * is the querystring we have to execute.
5182 query = exec_eval_expr(estate, dynquery, &isnull, &restype);
5185 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
5186 errmsg("cannot EXECUTE a null querystring")));
5188 /* Get the C-String representation */
5189 querystr = convert_value_to_string(query, restype);
5191 exec_eval_cleanup(estate);
5194 * Open an implicit cursor for the query. We use SPI_cursor_open_with_args
5195 * even when there are no params, because this avoids making and freeing
5196 * one copy of the plan.
5200 PreparedParamsData *ppd;
5202 ppd = exec_eval_using_params(estate, params);
5203 portal = SPI_cursor_open_with_args(NULL,
5205 ppd->nargs, ppd->types,
5206 ppd->values, ppd->nulls,
5207 estate->readonly_func, 0);
5208 free_params_data(ppd);
5212 portal = SPI_cursor_open_with_args(NULL,
5216 estate->readonly_func, 0);
5220 elog(ERROR, "could not open implicit cursor for query \"%s\": %s",
5221 querystr, SPI_result_code_string(SPI_result));