1 /*-------------------------------------------------------------------------
3 * pl_exec.c - Executor for the PL/pgSQL
6 * Portions Copyright (c) 1996-2007, 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.200 2007/11/15 21:14:46 momjian Exp $
13 *-------------------------------------------------------------------------
21 #include "access/heapam.h"
22 #include "access/transam.h"
23 #include "catalog/pg_proc.h"
24 #include "catalog/pg_type.h"
25 #include "executor/spi_priv.h"
27 #include "optimizer/clauses.h"
28 #include "parser/parse_expr.h"
29 #include "parser/scansup.h"
30 #include "tcop/tcopprot.h"
31 #include "utils/array.h"
32 #include "utils/builtins.h"
33 #include "utils/lsyscache.h"
34 #include "utils/memutils.h"
35 #include "utils/typcache.h"
38 static const char *const raise_skip_msg = "RAISE";
41 * All plpgsql function executions within a single transaction share the same
42 * executor EState for evaluating "simple" expressions. Each function call
43 * creates its own "eval_econtext" ExprContext within this estate for
44 * per-evaluation workspace. eval_econtext is freed at normal function exit,
45 * and the EState is freed at transaction end (in case of error, we assume
46 * that the abort mechanisms clean it all up). In order to be sure
47 * ExprContext callbacks are handled properly, each subtransaction has to have
48 * its own such EState; hence we need a stack. We use a simple counter to
49 * distinguish different instantiations of the EState, so that we can tell
50 * whether we have a current copy of a prepared expression.
52 * This arrangement is a bit tedious to maintain, but it's worth the trouble
53 * so that we don't have to re-prepare simple expressions on each trip through
54 * a function. (We assume the case to optimize is many repetitions of a
55 * function within a transaction.)
57 typedef struct SimpleEstateStackEntry
59 EState *xact_eval_estate; /* EState for current xact level */
60 long int xact_estate_simple_id; /* ID for xact_eval_estate */
61 SubTransactionId xact_subxid; /* ID for current subxact */
62 struct SimpleEstateStackEntry *next; /* next stack entry up */
63 } SimpleEstateStackEntry;
65 static SimpleEstateStackEntry *simple_estate_stack = NULL;
66 static long int simple_estate_id_counter = 0;
68 /************************************************************
69 * Local function forward declarations
70 ************************************************************/
71 static void plpgsql_exec_error_callback(void *arg);
72 static PLpgSQL_datum *copy_plpgsql_datum(PLpgSQL_datum *datum);
74 static int exec_stmt_block(PLpgSQL_execstate *estate,
75 PLpgSQL_stmt_block *block);
76 static int exec_stmts(PLpgSQL_execstate *estate,
78 static int exec_stmt(PLpgSQL_execstate *estate,
80 static int exec_stmt_assign(PLpgSQL_execstate *estate,
81 PLpgSQL_stmt_assign *stmt);
82 static int exec_stmt_perform(PLpgSQL_execstate *estate,
83 PLpgSQL_stmt_perform *stmt);
84 static int exec_stmt_getdiag(PLpgSQL_execstate *estate,
85 PLpgSQL_stmt_getdiag *stmt);
86 static int exec_stmt_if(PLpgSQL_execstate *estate,
87 PLpgSQL_stmt_if *stmt);
88 static int exec_stmt_loop(PLpgSQL_execstate *estate,
89 PLpgSQL_stmt_loop *stmt);
90 static int exec_stmt_while(PLpgSQL_execstate *estate,
91 PLpgSQL_stmt_while *stmt);
92 static int exec_stmt_fori(PLpgSQL_execstate *estate,
93 PLpgSQL_stmt_fori *stmt);
94 static int exec_stmt_fors(PLpgSQL_execstate *estate,
95 PLpgSQL_stmt_fors *stmt);
96 static int exec_stmt_open(PLpgSQL_execstate *estate,
97 PLpgSQL_stmt_open *stmt);
98 static int exec_stmt_fetch(PLpgSQL_execstate *estate,
99 PLpgSQL_stmt_fetch *stmt);
100 static int exec_stmt_close(PLpgSQL_execstate *estate,
101 PLpgSQL_stmt_close *stmt);
102 static int exec_stmt_exit(PLpgSQL_execstate *estate,
103 PLpgSQL_stmt_exit *stmt);
104 static int exec_stmt_return(PLpgSQL_execstate *estate,
105 PLpgSQL_stmt_return *stmt);
106 static int exec_stmt_return_next(PLpgSQL_execstate *estate,
107 PLpgSQL_stmt_return_next *stmt);
108 static int exec_stmt_return_query(PLpgSQL_execstate *estate,
109 PLpgSQL_stmt_return_query * stmt);
110 static int exec_stmt_raise(PLpgSQL_execstate *estate,
111 PLpgSQL_stmt_raise *stmt);
112 static int exec_stmt_execsql(PLpgSQL_execstate *estate,
113 PLpgSQL_stmt_execsql *stmt);
114 static int exec_stmt_dynexecute(PLpgSQL_execstate *estate,
115 PLpgSQL_stmt_dynexecute *stmt);
116 static int exec_stmt_dynfors(PLpgSQL_execstate *estate,
117 PLpgSQL_stmt_dynfors *stmt);
119 static void plpgsql_estate_setup(PLpgSQL_execstate *estate,
120 PLpgSQL_function *func,
122 static void exec_eval_cleanup(PLpgSQL_execstate *estate);
124 static void exec_prepare_plan(PLpgSQL_execstate *estate,
125 PLpgSQL_expr *expr, int cursorOptions);
126 static bool exec_simple_check_node(Node *node);
127 static void exec_simple_check_plan(PLpgSQL_expr *expr);
128 static bool exec_eval_simple_expr(PLpgSQL_execstate *estate,
134 static void exec_assign_expr(PLpgSQL_execstate *estate,
135 PLpgSQL_datum *target,
137 static void exec_assign_value(PLpgSQL_execstate *estate,
138 PLpgSQL_datum *target,
139 Datum value, Oid valtype, bool *isNull);
140 static void exec_eval_datum(PLpgSQL_execstate *estate,
141 PLpgSQL_datum *datum,
146 static int exec_eval_integer(PLpgSQL_execstate *estate,
149 static bool exec_eval_boolean(PLpgSQL_execstate *estate,
152 static Datum exec_eval_expr(PLpgSQL_execstate *estate,
156 static int exec_run_select(PLpgSQL_execstate *estate,
157 PLpgSQL_expr *expr, long maxtuples, Portal *portalP);
158 static void exec_move_row(PLpgSQL_execstate *estate,
161 HeapTuple tup, TupleDesc tupdesc);
162 static HeapTuple make_tuple_from_row(PLpgSQL_execstate *estate,
165 static char *convert_value_to_string(Datum value, Oid valtype);
166 static Datum exec_cast_value(Datum value, Oid valtype,
172 static Datum exec_simple_cast_value(Datum value, Oid valtype,
173 Oid reqtype, int32 reqtypmod,
175 static void exec_init_tuple_store(PLpgSQL_execstate *estate);
176 static bool compatible_tupdesc(TupleDesc td1, TupleDesc td2);
177 static void exec_set_found(PLpgSQL_execstate *estate, bool state);
178 static void plpgsql_create_econtext(PLpgSQL_execstate *estate);
179 static void free_var(PLpgSQL_var *var);
183 * plpgsql_exec_function Called by the call handler for
184 * function execution.
188 plpgsql_exec_function(PLpgSQL_function *func, FunctionCallInfo fcinfo)
190 PLpgSQL_execstate estate;
191 ErrorContextCallback plerrcontext;
196 * Setup the execution state
198 plpgsql_estate_setup(&estate, func, (ReturnSetInfo *) fcinfo->resultinfo);
201 * Setup error traceback support for ereport()
203 plerrcontext.callback = plpgsql_exec_error_callback;
204 plerrcontext.arg = &estate;
205 plerrcontext.previous = error_context_stack;
206 error_context_stack = &plerrcontext;
209 * Make local execution copies of all the datums
211 estate.err_text = gettext_noop("during initialization of execution state");
212 for (i = 0; i < estate.ndatums; i++)
213 estate.datums[i] = copy_plpgsql_datum(func->datums[i]);
216 * Store the actual call argument values into the appropriate variables
218 estate.err_text = gettext_noop("while storing call arguments into local variables");
219 for (i = 0; i < func->fn_nargs; i++)
221 int n = func->fn_argvarnos[i];
223 switch (estate.datums[n]->dtype)
225 case PLPGSQL_DTYPE_VAR:
227 PLpgSQL_var *var = (PLpgSQL_var *) estate.datums[n];
229 var->value = fcinfo->arg[i];
230 var->isnull = fcinfo->argnull[i];
231 var->freeval = false;
235 case PLPGSQL_DTYPE_ROW:
237 PLpgSQL_row *row = (PLpgSQL_row *) estate.datums[n];
239 if (!fcinfo->argnull[i])
245 HeapTupleData tmptup;
247 td = DatumGetHeapTupleHeader(fcinfo->arg[i]);
248 /* Extract rowtype info and find a tupdesc */
249 tupType = HeapTupleHeaderGetTypeId(td);
250 tupTypmod = HeapTupleHeaderGetTypMod(td);
251 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
252 /* Build a temporary HeapTuple control structure */
253 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
254 ItemPointerSetInvalid(&(tmptup.t_self));
255 tmptup.t_tableOid = InvalidOid;
257 exec_move_row(&estate, NULL, row, &tmptup, tupdesc);
258 ReleaseTupleDesc(tupdesc);
262 /* If arg is null, treat it as an empty row */
263 exec_move_row(&estate, NULL, row, NULL, NULL);
269 elog(ERROR, "unrecognized dtype: %d", func->datums[i]->dtype);
273 estate.err_text = gettext_noop("during function entry");
276 * Set the magic variable FOUND to false
278 exec_set_found(&estate, false);
281 * Let the instrumentation plugin peek at this function
283 if (*plugin_ptr && (*plugin_ptr)->func_beg)
284 ((*plugin_ptr)->func_beg) (&estate, func);
287 * Now call the toplevel block of statements
289 estate.err_text = NULL;
290 estate.err_stmt = (PLpgSQL_stmt *) (func->action);
291 rc = exec_stmt_block(&estate, func->action);
292 if (rc != PLPGSQL_RC_RETURN)
294 estate.err_stmt = NULL;
295 estate.err_text = NULL;
298 * Provide a more helpful message if a CONTINUE has been used outside
301 if (rc == PLPGSQL_RC_CONTINUE)
303 (errcode(ERRCODE_SYNTAX_ERROR),
304 errmsg("CONTINUE cannot be used outside a loop")));
307 (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
308 errmsg("control reached end of function without RETURN")));
312 * We got a return value - process it
314 estate.err_stmt = NULL;
315 estate.err_text = gettext_noop("while casting return value to function's return type");
317 fcinfo->isnull = estate.retisnull;
321 ReturnSetInfo *rsi = estate.rsi;
323 /* Check caller can handle a set result */
324 if (!rsi || !IsA(rsi, ReturnSetInfo) ||
325 (rsi->allowedModes & SFRM_Materialize) == 0)
327 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
328 errmsg("set-valued function called in context that cannot accept a set")));
329 rsi->returnMode = SFRM_Materialize;
331 /* If we produced any tuples, send back the result */
332 if (estate.tuple_store)
334 rsi->setResult = estate.tuple_store;
335 if (estate.rettupdesc)
337 MemoryContext oldcxt;
339 oldcxt = MemoryContextSwitchTo(estate.tuple_store_cxt);
340 rsi->setDesc = CreateTupleDescCopy(estate.rettupdesc);
341 MemoryContextSwitchTo(oldcxt);
344 estate.retval = (Datum) 0;
345 fcinfo->isnull = true;
347 else if (!estate.retisnull)
349 if (estate.retistuple)
352 * We have to check that the returned tuple actually matches the
353 * expected result type. XXX would be better to cache the tupdesc
354 * instead of repeating get_call_result_type()
358 switch (get_call_result_type(fcinfo, NULL, &tupdesc))
360 case TYPEFUNC_COMPOSITE:
361 /* got the expected result rowtype, now check it */
362 if (estate.rettupdesc == NULL ||
363 !compatible_tupdesc(estate.rettupdesc, tupdesc))
365 (errcode(ERRCODE_DATATYPE_MISMATCH),
366 errmsg("returned record type does not match expected record type")));
368 case TYPEFUNC_RECORD:
371 * Failed to determine actual type of RECORD. We could
372 * raise an error here, but what this means in practice is
373 * that the caller is expecting any old generic rowtype,
374 * so we don't really need to be restrictive. Pass back
375 * the generated result type, instead.
377 tupdesc = estate.rettupdesc;
378 if (tupdesc == NULL) /* shouldn't happen */
379 elog(ERROR, "return type must be a row type");
382 /* shouldn't get here if retistuple is true ... */
383 elog(ERROR, "return type must be a row type");
388 * Copy tuple to upper executor memory, as a tuple Datum. Make
389 * sure it is labeled with the caller-supplied tuple type.
392 PointerGetDatum(SPI_returntuple((HeapTuple) (estate.retval),
397 /* Cast value to proper type */
398 estate.retval = exec_cast_value(estate.retval, estate.rettype,
400 &(func->fn_retinput),
401 func->fn_rettypioparam,
406 * If the function's return type isn't by value, copy the value
407 * into upper executor memory context.
409 if (!fcinfo->isnull && !func->fn_retbyval)
414 len = datumGetSize(estate.retval, false, func->fn_rettyplen);
415 tmp = SPI_palloc(len);
416 memcpy(tmp, DatumGetPointer(estate.retval), len);
417 estate.retval = PointerGetDatum(tmp);
422 estate.err_text = gettext_noop("during function exit");
425 * Let the instrumentation plugin peek at this function
427 if (*plugin_ptr && (*plugin_ptr)->func_end)
428 ((*plugin_ptr)->func_end) (&estate, func);
430 /* Clean up any leftover temporary memory */
431 FreeExprContext(estate.eval_econtext);
432 estate.eval_econtext = NULL;
433 exec_eval_cleanup(&estate);
436 * Pop the error context stack
438 error_context_stack = plerrcontext.previous;
441 * Return the function's result
443 return estate.retval;
448 * plpgsql_exec_trigger Called by the call handler for
453 plpgsql_exec_trigger(PLpgSQL_function *func,
454 TriggerData *trigdata)
456 PLpgSQL_execstate estate;
457 ErrorContextCallback plerrcontext;
461 PLpgSQL_rec *rec_new,
466 * Setup the execution state
468 plpgsql_estate_setup(&estate, func, NULL);
471 * Setup error traceback support for ereport()
473 plerrcontext.callback = plpgsql_exec_error_callback;
474 plerrcontext.arg = &estate;
475 plerrcontext.previous = error_context_stack;
476 error_context_stack = &plerrcontext;
479 * Make local execution copies of all the datums
481 estate.err_text = gettext_noop("during initialization of execution state");
482 for (i = 0; i < estate.ndatums; i++)
483 estate.datums[i] = copy_plpgsql_datum(func->datums[i]);
486 * Put the OLD and NEW tuples into record variables
488 rec_new = (PLpgSQL_rec *) (estate.datums[func->new_varno]);
489 rec_new->freetup = false;
490 rec_new->freetupdesc = false;
491 rec_old = (PLpgSQL_rec *) (estate.datums[func->old_varno]);
492 rec_old->freetup = false;
493 rec_old->freetupdesc = false;
495 if (TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
498 * Per-statement triggers don't use OLD/NEW variables
501 rec_new->tupdesc = NULL;
503 rec_old->tupdesc = NULL;
505 else if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
507 rec_new->tup = trigdata->tg_trigtuple;
508 rec_new->tupdesc = trigdata->tg_relation->rd_att;
510 rec_old->tupdesc = NULL;
512 else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
514 rec_new->tup = trigdata->tg_newtuple;
515 rec_new->tupdesc = trigdata->tg_relation->rd_att;
516 rec_old->tup = trigdata->tg_trigtuple;
517 rec_old->tupdesc = trigdata->tg_relation->rd_att;
519 else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
522 rec_new->tupdesc = NULL;
523 rec_old->tup = trigdata->tg_trigtuple;
524 rec_old->tupdesc = trigdata->tg_relation->rd_att;
527 elog(ERROR, "unrecognized trigger action: not INSERT, DELETE, or UPDATE");
530 * Assign the special tg_ variables
533 var = (PLpgSQL_var *) (estate.datums[func->tg_op_varno]);
534 if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
535 var->value = DirectFunctionCall1(textin, CStringGetDatum("INSERT"));
536 else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
537 var->value = DirectFunctionCall1(textin, CStringGetDatum("UPDATE"));
538 else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
539 var->value = DirectFunctionCall1(textin, CStringGetDatum("DELETE"));
541 elog(ERROR, "unrecognized trigger action: not INSERT, DELETE, or UPDATE");
545 var = (PLpgSQL_var *) (estate.datums[func->tg_name_varno]);
546 var->value = DirectFunctionCall1(namein,
547 CStringGetDatum(trigdata->tg_trigger->tgname));
551 var = (PLpgSQL_var *) (estate.datums[func->tg_when_varno]);
552 if (TRIGGER_FIRED_BEFORE(trigdata->tg_event))
553 var->value = DirectFunctionCall1(textin, CStringGetDatum("BEFORE"));
554 else if (TRIGGER_FIRED_AFTER(trigdata->tg_event))
555 var->value = DirectFunctionCall1(textin, CStringGetDatum("AFTER"));
557 elog(ERROR, "unrecognized trigger execution time: not BEFORE or AFTER");
561 var = (PLpgSQL_var *) (estate.datums[func->tg_level_varno]);
562 if (TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
563 var->value = DirectFunctionCall1(textin, CStringGetDatum("ROW"));
564 else if (TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
565 var->value = DirectFunctionCall1(textin, CStringGetDatum("STATEMENT"));
567 elog(ERROR, "unrecognized trigger event type: not ROW or STATEMENT");
571 var = (PLpgSQL_var *) (estate.datums[func->tg_relid_varno]);
572 var->value = ObjectIdGetDatum(trigdata->tg_relation->rd_id);
574 var->freeval = false;
576 var = (PLpgSQL_var *) (estate.datums[func->tg_relname_varno]);
577 var->value = DirectFunctionCall1(namein,
578 CStringGetDatum(RelationGetRelationName(trigdata->tg_relation)));
582 var = (PLpgSQL_var *) (estate.datums[func->tg_table_name_varno]);
583 var->value = DirectFunctionCall1(namein,
584 CStringGetDatum(RelationGetRelationName(trigdata->tg_relation)));
588 var = (PLpgSQL_var *) (estate.datums[func->tg_table_schema_varno]);
589 var->value = DirectFunctionCall1(namein,
592 RelationGetNamespace(
593 trigdata->tg_relation))));
597 var = (PLpgSQL_var *) (estate.datums[func->tg_nargs_varno]);
598 var->value = Int16GetDatum(trigdata->tg_trigger->tgnargs);
600 var->freeval = false;
603 * Store the trigger argument values into the special execution state
606 estate.err_text = gettext_noop("while storing call arguments into local variables");
607 estate.trig_nargs = trigdata->tg_trigger->tgnargs;
608 if (estate.trig_nargs == 0)
609 estate.trig_argv = NULL;
612 estate.trig_argv = palloc(sizeof(Datum) * estate.trig_nargs);
613 for (i = 0; i < trigdata->tg_trigger->tgnargs; i++)
614 estate.trig_argv[i] = DirectFunctionCall1(textin,
615 CStringGetDatum(trigdata->tg_trigger->tgargs[i]));
618 estate.err_text = gettext_noop("during function entry");
621 * Set the magic variable FOUND to false
623 exec_set_found(&estate, false);
626 * Let the instrumentation plugin peek at this function
628 if (*plugin_ptr && (*plugin_ptr)->func_beg)
629 ((*plugin_ptr)->func_beg) (&estate, func);
632 * Now call the toplevel block of statements
634 estate.err_text = NULL;
635 estate.err_stmt = (PLpgSQL_stmt *) (func->action);
636 rc = exec_stmt_block(&estate, func->action);
637 if (rc != PLPGSQL_RC_RETURN)
639 estate.err_stmt = NULL;
640 estate.err_text = NULL;
643 * Provide a more helpful message if a CONTINUE has been used outside
646 if (rc == PLPGSQL_RC_CONTINUE)
648 (errcode(ERRCODE_SYNTAX_ERROR),
649 errmsg("CONTINUE cannot be used outside a loop")));
652 (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
653 errmsg("control reached end of trigger procedure without RETURN")));
656 estate.err_stmt = NULL;
657 estate.err_text = gettext_noop("during function exit");
661 (errcode(ERRCODE_DATATYPE_MISMATCH),
662 errmsg("trigger procedure cannot return a set")));
665 * Check that the returned tuple structure has the same attributes, the
666 * relation that fired the trigger has. A per-statement trigger always
667 * needs to return NULL, so we ignore any return value the function itself
668 * produces (XXX: is this a good idea?)
670 * XXX This way it is possible, that the trigger returns a tuple where
671 * attributes don't have the correct atttypmod's length. It's up to the
672 * trigger's programmer to ensure that this doesn't happen. Jan
674 if (estate.retisnull || TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
678 if (!compatible_tupdesc(estate.rettupdesc,
679 trigdata->tg_relation->rd_att))
681 (errcode(ERRCODE_DATATYPE_MISMATCH),
682 errmsg("returned tuple structure does not match table of trigger event")));
683 /* Copy tuple to upper executor memory */
684 rettup = SPI_copytuple((HeapTuple) (estate.retval));
688 * Let the instrumentation plugin peek at this function
690 if (*plugin_ptr && (*plugin_ptr)->func_end)
691 ((*plugin_ptr)->func_end) (&estate, func);
693 /* Clean up any leftover temporary memory */
694 FreeExprContext(estate.eval_econtext);
695 estate.eval_econtext = NULL;
696 exec_eval_cleanup(&estate);
699 * Pop the error context stack
701 error_context_stack = plerrcontext.previous;
704 * Return the trigger's result
711 * error context callback to let us supply a call-stack traceback
714 plpgsql_exec_error_callback(void *arg)
716 PLpgSQL_execstate *estate = (PLpgSQL_execstate *) arg;
718 /* safety check, shouldn't happen */
719 if (estate->err_func == NULL)
722 /* if we are doing RAISE, don't report its location */
723 if (estate->err_text == raise_skip_msg)
726 if (estate->err_text != NULL)
729 * We don't expend the cycles to run gettext() on err_text unless we
730 * actually need it. Therefore, places that set up err_text should
731 * use gettext_noop() to ensure the strings get recorded in the
732 * message dictionary.
734 * If both err_text and err_stmt are set, use the err_text as
735 * description, but report the err_stmt's line number. When err_stmt
736 * is not set, we're in function entry/exit, or some such place not
737 * attached to a specific line number.
739 if (estate->err_stmt != NULL)
742 * translator: last %s is a phrase such as "during statement block
743 * local variable initialization"
745 errcontext("PL/pgSQL function \"%s\" line %d %s",
746 estate->err_func->fn_name,
747 estate->err_stmt->lineno,
748 gettext(estate->err_text));
753 * translator: last %s is a phrase such as "while storing call
754 * arguments into local variables"
756 errcontext("PL/pgSQL function \"%s\" %s",
757 estate->err_func->fn_name,
758 gettext(estate->err_text));
761 else if (estate->err_stmt != NULL)
763 /* translator: last %s is a plpgsql statement type name */
764 errcontext("PL/pgSQL function \"%s\" line %d at %s",
765 estate->err_func->fn_name,
766 estate->err_stmt->lineno,
767 plpgsql_stmt_typename(estate->err_stmt));
770 errcontext("PL/pgSQL function \"%s\"",
771 estate->err_func->fn_name);
776 * Support function for initializing local execution variables
779 static PLpgSQL_datum *
780 copy_plpgsql_datum(PLpgSQL_datum *datum)
782 PLpgSQL_datum *result;
784 switch (datum->dtype)
786 case PLPGSQL_DTYPE_VAR:
788 PLpgSQL_var *new = palloc(sizeof(PLpgSQL_var));
790 memcpy(new, datum, sizeof(PLpgSQL_var));
791 /* Ensure the value is null (possibly not needed?) */
794 new->freeval = false;
796 result = (PLpgSQL_datum *) new;
800 case PLPGSQL_DTYPE_REC:
802 PLpgSQL_rec *new = palloc(sizeof(PLpgSQL_rec));
804 memcpy(new, datum, sizeof(PLpgSQL_rec));
805 /* Ensure the value is null (possibly not needed?) */
808 new->freetup = false;
809 new->freetupdesc = false;
811 result = (PLpgSQL_datum *) new;
815 case PLPGSQL_DTYPE_ROW:
816 case PLPGSQL_DTYPE_RECFIELD:
817 case PLPGSQL_DTYPE_ARRAYELEM:
818 case PLPGSQL_DTYPE_TRIGARG:
821 * These datum records are read-only at runtime, so no need to
828 elog(ERROR, "unrecognized dtype: %d", datum->dtype);
829 result = NULL; /* keep compiler quiet */
838 exception_matches_conditions(ErrorData *edata, PLpgSQL_condition *cond)
840 for (; cond != NULL; cond = cond->next)
842 int sqlerrstate = cond->sqlerrstate;
845 * OTHERS matches everything *except* query-canceled; if you're
846 * foolish enough, you can match that explicitly.
848 if (sqlerrstate == 0)
850 if (edata->sqlerrcode != ERRCODE_QUERY_CANCELED)
854 else if (edata->sqlerrcode == sqlerrstate)
856 /* Category match? */
857 else if (ERRCODE_IS_CATEGORY(sqlerrstate) &&
858 ERRCODE_TO_CATEGORY(edata->sqlerrcode) == sqlerrstate)
866 * exec_stmt_block Execute a block of statements
870 exec_stmt_block(PLpgSQL_execstate *estate, PLpgSQL_stmt_block *block)
872 volatile int rc = -1;
877 * First initialize all variables declared in this block
879 estate->err_text = gettext_noop("during statement block local variable initialization");
881 for (i = 0; i < block->n_initvars; i++)
883 n = block->initvarnos[i];
885 switch (estate->datums[n]->dtype)
887 case PLPGSQL_DTYPE_VAR:
889 PLpgSQL_var *var = (PLpgSQL_var *) (estate->datums[n]);
891 /* free any old value, in case re-entering block */
894 /* Initially it contains a NULL */
895 var->value = (Datum) 0;
898 if (var->default_val == NULL)
901 * If needed, give the datatype a chance to reject
902 * NULLs, by assigning a NULL to the variable. We
903 * claim the value is of type UNKNOWN, not the var's
904 * datatype, else coercion will be skipped. (Do this
905 * before the notnull check to be consistent with
906 * exec_assign_value.)
908 if (!var->datatype->typinput.fn_strict)
910 bool valIsNull = true;
912 exec_assign_value(estate,
913 (PLpgSQL_datum *) var,
920 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
921 errmsg("variable \"%s\" declared NOT NULL cannot default to NULL",
926 exec_assign_expr(estate, (PLpgSQL_datum *) var,
932 case PLPGSQL_DTYPE_REC:
934 PLpgSQL_rec *rec = (PLpgSQL_rec *) (estate->datums[n]);
938 heap_freetuple(rec->tup);
939 FreeTupleDesc(rec->tupdesc);
940 rec->freetup = false;
948 case PLPGSQL_DTYPE_RECFIELD:
949 case PLPGSQL_DTYPE_ARRAYELEM:
953 elog(ERROR, "unrecognized dtype: %d",
954 estate->datums[n]->dtype);
958 if (block->exceptions)
961 * Execute the statements in the block's body inside a sub-transaction
963 MemoryContext oldcontext = CurrentMemoryContext;
964 ResourceOwner oldowner = CurrentResourceOwner;
965 ExprContext *old_eval_econtext = estate->eval_econtext;
966 EState *old_eval_estate = estate->eval_estate;
967 long int old_eval_estate_simple_id = estate->eval_estate_simple_id;
969 estate->err_text = gettext_noop("during statement block entry");
971 BeginInternalSubTransaction(NULL);
972 /* Want to run statements inside function's memory context */
973 MemoryContextSwitchTo(oldcontext);
978 * We need to run the block's statements with a new eval_econtext
979 * that belongs to the current subtransaction; if we try to use
980 * the outer econtext then ExprContext shutdown callbacks will be
981 * called at the wrong times.
983 plpgsql_create_econtext(estate);
985 estate->err_text = NULL;
987 /* Run the block's statements */
988 rc = exec_stmts(estate, block->body);
990 estate->err_text = gettext_noop("during statement block exit");
993 * If the block ended with RETURN, we may need to copy the return
994 * value out of the subtransaction eval_context. This is
995 * currently only needed for scalar result types --- rowtype
996 * values will always exist in the function's own memory context.
998 if (rc == PLPGSQL_RC_RETURN &&
1000 !estate->retisnull &&
1001 estate->rettupdesc == NULL)
1006 get_typlenbyval(estate->rettype, &resTypLen, &resTypByVal);
1007 estate->retval = datumCopy(estate->retval,
1008 resTypByVal, resTypLen);
1011 /* Commit the inner transaction, return to outer xact context */
1012 ReleaseCurrentSubTransaction();
1013 MemoryContextSwitchTo(oldcontext);
1014 CurrentResourceOwner = oldowner;
1016 /* Revert to outer eval_econtext */
1017 estate->eval_econtext = old_eval_econtext;
1018 estate->eval_estate = old_eval_estate;
1019 estate->eval_estate_simple_id = old_eval_estate_simple_id;
1022 * AtEOSubXact_SPI() should not have popped any SPI context, but
1023 * just in case it did, make sure we remain connected.
1025 SPI_restore_connection();
1032 estate->err_text = gettext_noop("during exception cleanup");
1034 /* Save error info */
1035 MemoryContextSwitchTo(oldcontext);
1036 edata = CopyErrorData();
1039 /* Abort the inner transaction */
1040 RollbackAndReleaseCurrentSubTransaction();
1041 MemoryContextSwitchTo(oldcontext);
1042 CurrentResourceOwner = oldowner;
1044 /* Revert to outer eval_econtext */
1045 estate->eval_econtext = old_eval_econtext;
1046 estate->eval_estate = old_eval_estate;
1047 estate->eval_estate_simple_id = old_eval_estate_simple_id;
1050 * If AtEOSubXact_SPI() popped any SPI context of the subxact, it
1051 * will have left us in a disconnected state. We need this hack
1052 * to return to connected state.
1054 SPI_restore_connection();
1056 /* Look for a matching exception handler */
1057 foreach(e, block->exceptions->exc_list)
1059 PLpgSQL_exception *exception = (PLpgSQL_exception *) lfirst(e);
1061 if (exception_matches_conditions(edata, exception->conditions))
1064 * Initialize the magic SQLSTATE and SQLERRM variables for
1065 * the exception block. We needn't do this until we have
1066 * found a matching exception.
1068 PLpgSQL_var *state_var;
1069 PLpgSQL_var *errm_var;
1071 state_var = (PLpgSQL_var *)
1072 estate->datums[block->exceptions->sqlstate_varno];
1073 state_var->value = DirectFunctionCall1(textin,
1074 CStringGetDatum(unpack_sql_state(edata->sqlerrcode)));
1075 state_var->freeval = true;
1076 state_var->isnull = false;
1078 errm_var = (PLpgSQL_var *)
1079 estate->datums[block->exceptions->sqlerrm_varno];
1080 errm_var->value = DirectFunctionCall1(textin,
1081 CStringGetDatum(edata->message));
1082 errm_var->freeval = true;
1083 errm_var->isnull = false;
1085 estate->err_text = NULL;
1087 rc = exec_stmts(estate, exception->action);
1089 free_var(state_var);
1090 state_var->value = (Datum) 0;
1092 errm_var->value = (Datum) 0;
1097 /* If no match found, re-throw the error */
1099 ReThrowError(edata);
1101 FreeErrorData(edata);
1108 * Just execute the statements in the block's body
1110 estate->err_text = NULL;
1112 rc = exec_stmts(estate, block->body);
1115 estate->err_text = NULL;
1118 * Handle the return code.
1123 case PLPGSQL_RC_CONTINUE:
1124 case PLPGSQL_RC_RETURN:
1127 case PLPGSQL_RC_EXIT:
1128 if (estate->exitlabel == NULL)
1129 return PLPGSQL_RC_OK;
1130 if (block->label == NULL)
1131 return PLPGSQL_RC_EXIT;
1132 if (strcmp(block->label, estate->exitlabel))
1133 return PLPGSQL_RC_EXIT;
1134 estate->exitlabel = NULL;
1135 return PLPGSQL_RC_OK;
1138 elog(ERROR, "unrecognized rc: %d", rc);
1141 return PLPGSQL_RC_OK;
1146 * exec_stmts Iterate over a list of statements
1147 * as long as their return code is OK
1151 exec_stmts(PLpgSQL_execstate *estate, List *stmts)
1158 * Ensure we do a CHECK_FOR_INTERRUPTS() even though there is no
1159 * statement. This prevents hangup in a tight loop if, for instance,
1160 * there is a LOOP construct with an empty body.
1162 CHECK_FOR_INTERRUPTS();
1163 return PLPGSQL_RC_OK;
1168 PLpgSQL_stmt *stmt = (PLpgSQL_stmt *) lfirst(s);
1169 int rc = exec_stmt(estate, stmt);
1171 if (rc != PLPGSQL_RC_OK)
1175 return PLPGSQL_RC_OK;
1180 * exec_stmt Distribute one statement to the statements
1181 * type specific execution function.
1185 exec_stmt(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
1187 PLpgSQL_stmt *save_estmt;
1190 save_estmt = estate->err_stmt;
1191 estate->err_stmt = stmt;
1193 /* Let the plugin know that we are about to execute this statement */
1194 if (*plugin_ptr && (*plugin_ptr)->stmt_beg)
1195 ((*plugin_ptr)->stmt_beg) (estate, stmt);
1197 CHECK_FOR_INTERRUPTS();
1199 switch (stmt->cmd_type)
1201 case PLPGSQL_STMT_BLOCK:
1202 rc = exec_stmt_block(estate, (PLpgSQL_stmt_block *) stmt);
1205 case PLPGSQL_STMT_ASSIGN:
1206 rc = exec_stmt_assign(estate, (PLpgSQL_stmt_assign *) stmt);
1209 case PLPGSQL_STMT_PERFORM:
1210 rc = exec_stmt_perform(estate, (PLpgSQL_stmt_perform *) stmt);
1213 case PLPGSQL_STMT_GETDIAG:
1214 rc = exec_stmt_getdiag(estate, (PLpgSQL_stmt_getdiag *) stmt);
1217 case PLPGSQL_STMT_IF:
1218 rc = exec_stmt_if(estate, (PLpgSQL_stmt_if *) stmt);
1221 case PLPGSQL_STMT_LOOP:
1222 rc = exec_stmt_loop(estate, (PLpgSQL_stmt_loop *) stmt);
1225 case PLPGSQL_STMT_WHILE:
1226 rc = exec_stmt_while(estate, (PLpgSQL_stmt_while *) stmt);
1229 case PLPGSQL_STMT_FORI:
1230 rc = exec_stmt_fori(estate, (PLpgSQL_stmt_fori *) stmt);
1233 case PLPGSQL_STMT_FORS:
1234 rc = exec_stmt_fors(estate, (PLpgSQL_stmt_fors *) stmt);
1237 case PLPGSQL_STMT_EXIT:
1238 rc = exec_stmt_exit(estate, (PLpgSQL_stmt_exit *) stmt);
1241 case PLPGSQL_STMT_RETURN:
1242 rc = exec_stmt_return(estate, (PLpgSQL_stmt_return *) stmt);
1245 case PLPGSQL_STMT_RETURN_NEXT:
1246 rc = exec_stmt_return_next(estate, (PLpgSQL_stmt_return_next *) stmt);
1249 case PLPGSQL_STMT_RETURN_QUERY:
1250 rc = exec_stmt_return_query(estate, (PLpgSQL_stmt_return_query *) stmt);
1253 case PLPGSQL_STMT_RAISE:
1254 rc = exec_stmt_raise(estate, (PLpgSQL_stmt_raise *) stmt);
1257 case PLPGSQL_STMT_EXECSQL:
1258 rc = exec_stmt_execsql(estate, (PLpgSQL_stmt_execsql *) stmt);
1261 case PLPGSQL_STMT_DYNEXECUTE:
1262 rc = exec_stmt_dynexecute(estate, (PLpgSQL_stmt_dynexecute *) stmt);
1265 case PLPGSQL_STMT_DYNFORS:
1266 rc = exec_stmt_dynfors(estate, (PLpgSQL_stmt_dynfors *) stmt);
1269 case PLPGSQL_STMT_OPEN:
1270 rc = exec_stmt_open(estate, (PLpgSQL_stmt_open *) stmt);
1273 case PLPGSQL_STMT_FETCH:
1274 rc = exec_stmt_fetch(estate, (PLpgSQL_stmt_fetch *) stmt);
1277 case PLPGSQL_STMT_CLOSE:
1278 rc = exec_stmt_close(estate, (PLpgSQL_stmt_close *) stmt);
1282 estate->err_stmt = save_estmt;
1283 elog(ERROR, "unrecognized cmdtype: %d", stmt->cmd_type);
1286 /* Let the plugin know that we have finished executing this statement */
1287 if (*plugin_ptr && (*plugin_ptr)->stmt_end)
1288 ((*plugin_ptr)->stmt_end) (estate, stmt);
1290 estate->err_stmt = save_estmt;
1297 * exec_stmt_assign Evaluate an expression and
1298 * put the result into a variable.
1302 exec_stmt_assign(PLpgSQL_execstate *estate, PLpgSQL_stmt_assign *stmt)
1304 Assert(stmt->varno >= 0);
1306 exec_assign_expr(estate, estate->datums[stmt->varno], stmt->expr);
1308 return PLPGSQL_RC_OK;
1312 * exec_stmt_perform Evaluate query and discard result (but set
1313 * FOUND depending on whether at least one row
1318 exec_stmt_perform(PLpgSQL_execstate *estate, PLpgSQL_stmt_perform *stmt)
1320 PLpgSQL_expr *expr = stmt->expr;
1322 (void) exec_run_select(estate, expr, 0, NULL);
1323 exec_set_found(estate, (estate->eval_processed != 0));
1324 exec_eval_cleanup(estate);
1326 return PLPGSQL_RC_OK;
1330 * exec_stmt_getdiag Put internal PG information into
1331 * specified variables.
1335 exec_stmt_getdiag(PLpgSQL_execstate *estate, PLpgSQL_stmt_getdiag *stmt)
1339 foreach(lc, stmt->diag_items)
1341 PLpgSQL_diag_item *diag_item = (PLpgSQL_diag_item *) lfirst(lc);
1343 bool isnull = false;
1345 if (diag_item->target <= 0)
1348 var = estate->datums[diag_item->target];
1353 switch (diag_item->kind)
1355 case PLPGSQL_GETDIAG_ROW_COUNT:
1357 exec_assign_value(estate, var,
1358 UInt32GetDatum(estate->eval_processed),
1362 case PLPGSQL_GETDIAG_RESULT_OID:
1364 exec_assign_value(estate, var,
1365 ObjectIdGetDatum(estate->eval_lastoid),
1370 elog(ERROR, "unrecognized attribute request: %d",
1375 return PLPGSQL_RC_OK;
1379 * exec_stmt_if Evaluate a bool expression and
1380 * execute the true or false body
1385 exec_stmt_if(PLpgSQL_execstate *estate, PLpgSQL_stmt_if *stmt)
1390 value = exec_eval_boolean(estate, stmt->cond, &isnull);
1391 exec_eval_cleanup(estate);
1393 if (!isnull && value)
1395 if (stmt->true_body != NIL)
1396 return exec_stmts(estate, stmt->true_body);
1400 if (stmt->false_body != NIL)
1401 return exec_stmts(estate, stmt->false_body);
1404 return PLPGSQL_RC_OK;
1409 * exec_stmt_loop Loop over statements until
1414 exec_stmt_loop(PLpgSQL_execstate *estate, PLpgSQL_stmt_loop *stmt)
1418 int rc = exec_stmts(estate, stmt->body);
1425 case PLPGSQL_RC_EXIT:
1426 if (estate->exitlabel == NULL)
1427 return PLPGSQL_RC_OK;
1428 if (stmt->label == NULL)
1429 return PLPGSQL_RC_EXIT;
1430 if (strcmp(stmt->label, estate->exitlabel) != 0)
1431 return PLPGSQL_RC_EXIT;
1432 estate->exitlabel = NULL;
1433 return PLPGSQL_RC_OK;
1435 case PLPGSQL_RC_CONTINUE:
1436 if (estate->exitlabel == NULL)
1437 /* anonymous continue, so re-run the loop */
1439 else if (stmt->label != NULL &&
1440 strcmp(stmt->label, estate->exitlabel) == 0)
1441 /* label matches named continue, so re-run loop */
1442 estate->exitlabel = NULL;
1444 /* label doesn't match named continue, so propagate upward */
1445 return PLPGSQL_RC_CONTINUE;
1448 case PLPGSQL_RC_RETURN:
1449 return PLPGSQL_RC_RETURN;
1452 elog(ERROR, "unrecognized rc: %d", rc);
1456 return PLPGSQL_RC_OK;
1461 * exec_stmt_while Loop over statements as long
1462 * as an expression evaluates to
1463 * true or an exit occurs.
1467 exec_stmt_while(PLpgSQL_execstate *estate, PLpgSQL_stmt_while *stmt)
1475 value = exec_eval_boolean(estate, stmt->cond, &isnull);
1476 exec_eval_cleanup(estate);
1478 if (isnull || !value)
1481 rc = exec_stmts(estate, stmt->body);
1488 case PLPGSQL_RC_EXIT:
1489 if (estate->exitlabel == NULL)
1490 return PLPGSQL_RC_OK;
1491 if (stmt->label == NULL)
1492 return PLPGSQL_RC_EXIT;
1493 if (strcmp(stmt->label, estate->exitlabel))
1494 return PLPGSQL_RC_EXIT;
1495 estate->exitlabel = NULL;
1496 return PLPGSQL_RC_OK;
1498 case PLPGSQL_RC_CONTINUE:
1499 if (estate->exitlabel == NULL)
1500 /* anonymous continue, so re-run loop */
1502 else if (stmt->label != NULL &&
1503 strcmp(stmt->label, estate->exitlabel) == 0)
1504 /* label matches named continue, so re-run loop */
1505 estate->exitlabel = NULL;
1507 /* label doesn't match named continue, propagate upward */
1508 return PLPGSQL_RC_CONTINUE;
1511 case PLPGSQL_RC_RETURN:
1512 return PLPGSQL_RC_RETURN;
1515 elog(ERROR, "unrecognized rc: %d", rc);
1519 return PLPGSQL_RC_OK;
1524 * exec_stmt_fori Iterate an integer variable
1525 * from a lower to an upper value
1526 * incrementing or decrementing by the BY value
1530 exec_stmt_fori(PLpgSQL_execstate *estate, PLpgSQL_stmt_fori *stmt)
1540 int rc = PLPGSQL_RC_OK;
1542 var = (PLpgSQL_var *) (estate->datums[stmt->var->varno]);
1545 * Get the value of the lower bound
1547 value = exec_eval_expr(estate, stmt->lower, &isnull, &valtype);
1548 value = exec_cast_value(value, valtype, var->datatype->typoid,
1549 &(var->datatype->typinput),
1550 var->datatype->typioparam,
1551 var->datatype->atttypmod, isnull);
1554 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1555 errmsg("lower bound of FOR loop cannot be NULL")));
1556 loop_value = DatumGetInt32(value);
1557 exec_eval_cleanup(estate);
1560 * Get the value of the upper bound
1562 value = exec_eval_expr(estate, stmt->upper, &isnull, &valtype);
1563 value = exec_cast_value(value, valtype, var->datatype->typoid,
1564 &(var->datatype->typinput),
1565 var->datatype->typioparam,
1566 var->datatype->atttypmod, isnull);
1569 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1570 errmsg("upper bound of FOR loop cannot be NULL")));
1571 end_value = DatumGetInt32(value);
1572 exec_eval_cleanup(estate);
1575 * Get the step value
1579 value = exec_eval_expr(estate, stmt->step, &isnull, &valtype);
1580 value = exec_cast_value(value, valtype, var->datatype->typoid,
1581 &(var->datatype->typinput),
1582 var->datatype->typioparam,
1583 var->datatype->atttypmod, isnull);
1586 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1587 errmsg("BY value of FOR loop cannot be NULL")));
1588 step_value = DatumGetInt32(value);
1589 exec_eval_cleanup(estate);
1590 if (step_value <= 0)
1592 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1593 errmsg("BY value of FOR loop must be greater than zero")));
1604 * Check against upper bound
1608 if (loop_value < end_value)
1613 if (loop_value > end_value)
1617 found = true; /* looped at least once */
1620 * Assign current value to loop var
1622 var->value = Int32GetDatum(loop_value);
1623 var->isnull = false;
1626 * Execute the statements
1628 rc = exec_stmts(estate, stmt->body);
1630 if (rc == PLPGSQL_RC_RETURN)
1631 break; /* return from function */
1632 else if (rc == PLPGSQL_RC_EXIT)
1634 if (estate->exitlabel == NULL)
1635 /* unlabelled exit, finish the current loop */
1637 else if (stmt->label != NULL &&
1638 strcmp(stmt->label, estate->exitlabel) == 0)
1640 /* labelled exit, matches the current stmt's label */
1641 estate->exitlabel = NULL;
1646 * otherwise, this is a labelled exit that does not match the
1647 * current statement's label, if any: return RC_EXIT so that the
1648 * EXIT continues to propagate up the stack.
1652 else if (rc == PLPGSQL_RC_CONTINUE)
1654 if (estate->exitlabel == NULL)
1655 /* unlabelled continue, so re-run the current loop */
1657 else if (stmt->label != NULL &&
1658 strcmp(stmt->label, estate->exitlabel) == 0)
1660 /* label matches named continue, so re-run loop */
1661 estate->exitlabel = NULL;
1667 * otherwise, this is a named continue that does not match the
1668 * current statement's label, if any: return RC_CONTINUE so
1669 * that the CONTINUE will propagate up the stack.
1676 * Increase/decrease loop value, unless it would overflow, in which
1677 * case exit the loop.
1681 if ((int32) (loop_value - step_value) > loop_value)
1683 loop_value -= step_value;
1687 if ((int32) (loop_value + step_value) < loop_value)
1689 loop_value += step_value;
1694 * Set the FOUND variable to indicate the result of executing the loop
1695 * (namely, whether we looped one or more times). This must be set here so
1696 * that it does not interfere with the value of the FOUND variable inside
1697 * the loop processing itself.
1699 exec_set_found(estate, found);
1706 * exec_stmt_fors Execute a query, assign each
1707 * tuple to a record or row and
1708 * execute a group of statements
1713 exec_stmt_fors(PLpgSQL_execstate *estate, PLpgSQL_stmt_fors *stmt)
1715 PLpgSQL_rec *rec = NULL;
1716 PLpgSQL_row *row = NULL;
1717 SPITupleTable *tuptab;
1720 int rc = PLPGSQL_RC_OK;
1725 * Determine if we assign to a record or a row
1727 if (stmt->rec != NULL)
1728 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
1729 else if (stmt->row != NULL)
1730 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
1732 elog(ERROR, "unsupported target");
1735 * Open the implicit cursor for the statement and fetch the initial 10
1738 exec_run_select(estate, stmt->query, 0, &portal);
1740 SPI_cursor_fetch(portal, true, 10);
1741 tuptab = SPI_tuptable;
1745 * If the query didn't return any rows, set the target to NULL and return
1746 * with FOUND = false.
1749 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
1751 found = true; /* processed at least one tuple */
1758 for (i = 0; i < n; i++)
1761 * Assign the tuple to the target
1763 exec_move_row(estate, rec, row, tuptab->vals[i], tuptab->tupdesc);
1766 * Execute the statements
1768 rc = exec_stmts(estate, stmt->body);
1769 if (rc != PLPGSQL_RC_OK)
1771 if (rc == PLPGSQL_RC_EXIT)
1773 if (estate->exitlabel == NULL)
1774 /* unlabelled exit, finish the current loop */
1776 else if (stmt->label != NULL &&
1777 strcmp(stmt->label, estate->exitlabel) == 0)
1779 /* labelled exit, matches the current stmt's label */
1780 estate->exitlabel = NULL;
1785 * otherwise, we processed a labelled exit that does not
1786 * match the current statement's label, if any: return
1787 * RC_EXIT so that the EXIT continues to recurse upward.
1790 else if (rc == PLPGSQL_RC_CONTINUE)
1792 if (estate->exitlabel == NULL)
1794 /* anonymous continue, so re-run the current loop */
1798 else if (stmt->label != NULL &&
1799 strcmp(stmt->label, estate->exitlabel) == 0)
1801 /* label matches named continue, so re-run loop */
1803 estate->exitlabel = NULL;
1808 * otherwise, we processed a named continue that does not
1809 * match the current statement's label, if any: return
1810 * RC_CONTINUE so that the CONTINUE will propagate up the
1816 * We're aborting the loop, so cleanup and set FOUND. (This
1817 * code should match the code after the loop.)
1819 SPI_freetuptable(tuptab);
1820 SPI_cursor_close(portal);
1821 exec_set_found(estate, found);
1827 SPI_freetuptable(tuptab);
1830 * Fetch the next 50 tuples
1832 SPI_cursor_fetch(portal, true, 50);
1834 tuptab = SPI_tuptable;
1838 * Release last group of tuples
1840 SPI_freetuptable(tuptab);
1843 * Close the implicit cursor
1845 SPI_cursor_close(portal);
1848 * Set the FOUND variable to indicate the result of executing the loop
1849 * (namely, whether we looped one or more times). This must be set here so
1850 * that it does not interfere with the value of the FOUND variable inside
1851 * the loop processing itself.
1853 exec_set_found(estate, found);
1860 * exec_stmt_exit Implements EXIT and CONTINUE
1862 * This begins the process of exiting / restarting a loop.
1866 exec_stmt_exit(PLpgSQL_execstate *estate, PLpgSQL_stmt_exit *stmt)
1869 * If the exit / continue has a condition, evaluate it
1871 if (stmt->cond != NULL)
1876 value = exec_eval_boolean(estate, stmt->cond, &isnull);
1877 exec_eval_cleanup(estate);
1878 if (isnull || value == false)
1879 return PLPGSQL_RC_OK;
1882 estate->exitlabel = stmt->label;
1884 return PLPGSQL_RC_EXIT;
1886 return PLPGSQL_RC_CONTINUE;
1891 * exec_stmt_return Evaluate an expression and start
1892 * returning from the function.
1896 exec_stmt_return(PLpgSQL_execstate *estate, PLpgSQL_stmt_return *stmt)
1899 * If processing a set-returning PL/PgSQL function, the final RETURN
1900 * indicates that the function is finished producing tuples. The rest of
1901 * the work will be done at the top level.
1903 if (estate->retisset)
1904 return PLPGSQL_RC_RETURN;
1906 /* initialize for null result (possibly a tuple) */
1907 estate->retval = (Datum) 0;
1908 estate->rettupdesc = NULL;
1909 estate->retisnull = true;
1911 if (stmt->retvarno >= 0)
1913 PLpgSQL_datum *retvar = estate->datums[stmt->retvarno];
1915 switch (retvar->dtype)
1917 case PLPGSQL_DTYPE_VAR:
1919 PLpgSQL_var *var = (PLpgSQL_var *) retvar;
1921 estate->retval = var->value;
1922 estate->retisnull = var->isnull;
1923 estate->rettype = var->datatype->typoid;
1927 case PLPGSQL_DTYPE_REC:
1929 PLpgSQL_rec *rec = (PLpgSQL_rec *) retvar;
1931 if (HeapTupleIsValid(rec->tup))
1933 estate->retval = (Datum) rec->tup;
1934 estate->rettupdesc = rec->tupdesc;
1935 estate->retisnull = false;
1940 case PLPGSQL_DTYPE_ROW:
1942 PLpgSQL_row *row = (PLpgSQL_row *) retvar;
1944 Assert(row->rowtupdesc);
1945 estate->retval = (Datum) make_tuple_from_row(estate, row,
1947 if (estate->retval == (Datum) NULL) /* should not happen */
1948 elog(ERROR, "row not compatible with its own tupdesc");
1949 estate->rettupdesc = row->rowtupdesc;
1950 estate->retisnull = false;
1955 elog(ERROR, "unrecognized dtype: %d", retvar->dtype);
1958 return PLPGSQL_RC_RETURN;
1961 if (stmt->expr != NULL)
1963 if (estate->retistuple)
1965 exec_run_select(estate, stmt->expr, 1, NULL);
1966 if (estate->eval_processed > 0)
1968 estate->retval = (Datum) estate->eval_tuptable->vals[0];
1969 estate->rettupdesc = estate->eval_tuptable->tupdesc;
1970 estate->retisnull = false;
1975 /* Normal case for scalar results */
1976 estate->retval = exec_eval_expr(estate, stmt->expr,
1977 &(estate->retisnull),
1978 &(estate->rettype));
1981 return PLPGSQL_RC_RETURN;
1985 * Special hack for function returning VOID: instead of NULL, return a
1986 * non-null VOID value. This is of dubious importance but is kept for
1987 * backwards compatibility. Note that the only other way to get here is
1988 * to have written "RETURN NULL" in a function returning tuple.
1990 if (estate->fn_rettype == VOIDOID)
1992 estate->retval = (Datum) 0;
1993 estate->retisnull = false;
1994 estate->rettype = VOIDOID;
1997 return PLPGSQL_RC_RETURN;
2001 * exec_stmt_return_next Evaluate an expression and add it to the
2002 * list of tuples returned by the current
2007 exec_stmt_return_next(PLpgSQL_execstate *estate,
2008 PLpgSQL_stmt_return_next *stmt)
2013 bool free_tuple = false;
2015 if (!estate->retisset)
2017 (errcode(ERRCODE_SYNTAX_ERROR),
2018 errmsg("cannot use RETURN NEXT in a non-SETOF function")));
2020 if (estate->tuple_store == NULL)
2021 exec_init_tuple_store(estate);
2023 /* rettupdesc will be filled by exec_init_tuple_store */
2024 tupdesc = estate->rettupdesc;
2025 natts = tupdesc->natts;
2027 if (stmt->retvarno >= 0)
2029 PLpgSQL_datum *retvar = estate->datums[stmt->retvarno];
2031 switch (retvar->dtype)
2033 case PLPGSQL_DTYPE_VAR:
2035 PLpgSQL_var *var = (PLpgSQL_var *) retvar;
2036 Datum retval = var->value;
2037 bool isNull = var->isnull;
2041 (errcode(ERRCODE_DATATYPE_MISMATCH),
2042 errmsg("wrong result type supplied in RETURN NEXT")));
2044 /* coerce type if needed */
2045 retval = exec_simple_cast_value(retval,
2046 var->datatype->typoid,
2047 tupdesc->attrs[0]->atttypid,
2048 tupdesc->attrs[0]->atttypmod,
2051 tuple = heap_form_tuple(tupdesc, &retval, &isNull);
2057 case PLPGSQL_DTYPE_REC:
2059 PLpgSQL_rec *rec = (PLpgSQL_rec *) retvar;
2061 if (!HeapTupleIsValid(rec->tup))
2063 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2064 errmsg("record \"%s\" is not assigned yet",
2066 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
2067 if (!compatible_tupdesc(tupdesc, rec->tupdesc))
2069 (errcode(ERRCODE_DATATYPE_MISMATCH),
2070 errmsg("wrong record type supplied in RETURN NEXT")));
2075 case PLPGSQL_DTYPE_ROW:
2077 PLpgSQL_row *row = (PLpgSQL_row *) retvar;
2079 tuple = make_tuple_from_row(estate, row, tupdesc);
2082 (errcode(ERRCODE_DATATYPE_MISMATCH),
2083 errmsg("wrong record type supplied in RETURN NEXT")));
2089 elog(ERROR, "unrecognized dtype: %d", retvar->dtype);
2090 tuple = NULL; /* keep compiler quiet */
2094 else if (stmt->expr)
2102 (errcode(ERRCODE_DATATYPE_MISMATCH),
2103 errmsg("wrong result type supplied in RETURN NEXT")));
2105 retval = exec_eval_expr(estate,
2110 /* coerce type if needed */
2111 retval = exec_simple_cast_value(retval,
2113 tupdesc->attrs[0]->atttypid,
2114 tupdesc->attrs[0]->atttypmod,
2117 tuple = heap_form_tuple(tupdesc, &retval, &isNull);
2121 exec_eval_cleanup(estate);
2126 (errcode(ERRCODE_SYNTAX_ERROR),
2127 errmsg("RETURN NEXT must have a parameter")));
2128 tuple = NULL; /* keep compiler quiet */
2131 if (HeapTupleIsValid(tuple))
2133 MemoryContext oldcxt;
2135 oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
2136 tuplestore_puttuple(estate->tuple_store, tuple);
2137 MemoryContextSwitchTo(oldcxt);
2140 heap_freetuple(tuple);
2143 return PLPGSQL_RC_OK;
2147 * exec_stmt_return_query Evaluate a query and add it to the
2148 * list of tuples returned by the current
2153 exec_stmt_return_query(PLpgSQL_execstate *estate,
2154 PLpgSQL_stmt_return_query * stmt)
2158 if (!estate->retisset)
2160 (errcode(ERRCODE_SYNTAX_ERROR),
2161 errmsg("cannot use RETURN QUERY in a non-SETOF function")));
2163 if (estate->tuple_store == NULL)
2164 exec_init_tuple_store(estate);
2166 exec_run_select(estate, stmt->query, 0, &portal);
2168 if (!compatible_tupdesc(estate->rettupdesc, portal->tupDesc))
2170 (errcode(ERRCODE_DATATYPE_MISMATCH),
2171 errmsg("structure of query does not match function result type")));
2175 MemoryContext old_cxt;
2178 SPI_cursor_fetch(portal, true, 50);
2179 if (SPI_processed == 0)
2182 old_cxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
2183 for (i = 0; i < SPI_processed; i++)
2185 HeapTuple tuple = SPI_tuptable->vals[i];
2187 tuplestore_puttuple(estate->tuple_store, tuple);
2189 MemoryContextSwitchTo(old_cxt);
2191 SPI_freetuptable(SPI_tuptable);
2194 SPI_freetuptable(SPI_tuptable);
2195 SPI_cursor_close(portal);
2197 return PLPGSQL_RC_OK;
2201 exec_init_tuple_store(PLpgSQL_execstate *estate)
2203 ReturnSetInfo *rsi = estate->rsi;
2204 MemoryContext oldcxt;
2207 * Check caller can handle a set result in the way we want
2209 if (!rsi || !IsA(rsi, ReturnSetInfo) ||
2210 (rsi->allowedModes & SFRM_Materialize) == 0 ||
2211 rsi->expectedDesc == NULL)
2213 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2214 errmsg("set-valued function called in context that cannot accept a set")));
2216 estate->tuple_store_cxt = rsi->econtext->ecxt_per_query_memory;
2218 oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
2219 estate->tuple_store = tuplestore_begin_heap(true, false, work_mem);
2220 MemoryContextSwitchTo(oldcxt);
2222 estate->rettupdesc = rsi->expectedDesc;
2226 * exec_stmt_raise Build a message and throw it with elog()
2230 exec_stmt_raise(PLpgSQL_execstate *estate, PLpgSQL_stmt_raise *stmt)
2234 ListCell *current_param;
2236 plpgsql_dstring_init(&ds);
2237 current_param = list_head(stmt->params);
2239 for (cp = stmt->message; *cp; cp++)
2242 * Occurrences of a single % are replaced by the next parameter's
2243 * external representation. Double %'s are converted to one %.
2254 plpgsql_dstring_append_char(&ds, cp[1]);
2259 if (current_param == NULL)
2261 (errcode(ERRCODE_SYNTAX_ERROR),
2262 errmsg("too few parameters specified for RAISE")));
2264 paramvalue = exec_eval_expr(estate,
2265 (PLpgSQL_expr *) lfirst(current_param),
2272 extval = convert_value_to_string(paramvalue, paramtypeid);
2273 plpgsql_dstring_append(&ds, extval);
2274 current_param = lnext(current_param);
2275 exec_eval_cleanup(estate);
2279 plpgsql_dstring_append_char(&ds, cp[0]);
2283 * If more parameters were specified than were required to process the
2284 * format string, throw an error
2286 if (current_param != NULL)
2288 (errcode(ERRCODE_SYNTAX_ERROR),
2289 errmsg("too many parameters specified for RAISE")));
2292 * Throw the error (may or may not come back)
2294 estate->err_text = raise_skip_msg; /* suppress traceback of raise */
2296 ereport(stmt->elog_level,
2297 ((stmt->elog_level >= ERROR) ? errcode(ERRCODE_RAISE_EXCEPTION) : 0,
2298 errmsg_internal("%s", plpgsql_dstring_get(&ds))));
2300 estate->err_text = NULL; /* un-suppress... */
2302 plpgsql_dstring_free(&ds);
2304 return PLPGSQL_RC_OK;
2309 * Initialize a mostly empty execution state
2313 plpgsql_estate_setup(PLpgSQL_execstate *estate,
2314 PLpgSQL_function *func,
2317 estate->retval = (Datum) 0;
2318 estate->retisnull = true;
2319 estate->rettype = InvalidOid;
2321 estate->fn_rettype = func->fn_rettype;
2322 estate->retistuple = func->fn_retistuple;
2323 estate->retisset = func->fn_retset;
2325 estate->readonly_func = func->fn_readonly;
2327 estate->rettupdesc = NULL;
2328 estate->exitlabel = NULL;
2330 estate->tuple_store = NULL;
2331 estate->tuple_store_cxt = NULL;
2334 estate->trig_nargs = 0;
2335 estate->trig_argv = NULL;
2337 estate->found_varno = func->found_varno;
2338 estate->ndatums = func->ndatums;
2339 estate->datums = palloc(sizeof(PLpgSQL_datum *) * estate->ndatums);
2340 /* caller is expected to fill the datums array */
2342 estate->eval_tuptable = NULL;
2343 estate->eval_processed = 0;
2344 estate->eval_lastoid = InvalidOid;
2346 estate->err_func = func;
2347 estate->err_stmt = NULL;
2348 estate->err_text = NULL;
2351 * Create an EState and ExprContext for evaluation of simple expressions.
2353 plpgsql_create_econtext(estate);
2356 * Let the plugin see this function before we initialize any local
2357 * PL/pgSQL variables - note that we also give the plugin a few function
2358 * pointers so it can call back into PL/pgSQL for doing things like
2359 * variable assignments and stack traces
2363 (*plugin_ptr)->error_callback = plpgsql_exec_error_callback;
2364 (*plugin_ptr)->assign_expr = exec_assign_expr;
2366 if ((*plugin_ptr)->func_setup)
2367 ((*plugin_ptr)->func_setup) (estate, func);
2372 * Release temporary memory used by expression/subselect evaluation
2374 * NB: the result of the evaluation is no longer valid after this is done,
2375 * unless it is a pass-by-value datatype.
2379 exec_eval_cleanup(PLpgSQL_execstate *estate)
2381 /* Clear result of a full SPI_execute */
2382 if (estate->eval_tuptable != NULL)
2383 SPI_freetuptable(estate->eval_tuptable);
2384 estate->eval_tuptable = NULL;
2386 /* Clear result of exec_eval_simple_expr (but keep the econtext) */
2387 if (estate->eval_econtext != NULL)
2388 ResetExprContext(estate->eval_econtext);
2393 * Generate a prepared plan
2397 exec_prepare_plan(PLpgSQL_execstate *estate,
2398 PLpgSQL_expr *expr, int cursorOptions)
2405 * We need a temporary argtypes array to load with data. (The finished
2406 * plan structure will contain a copy of it.)
2408 argtypes = (Oid *) palloc(expr->nparams * sizeof(Oid));
2410 for (i = 0; i < expr->nparams; i++)
2415 exec_eval_datum(estate, estate->datums[expr->params[i]],
2417 &argtypes[i], ¶mval, ¶misnull);
2421 * Generate and save the plan
2423 plan = SPI_prepare_cursor(expr->query, expr->nparams, argtypes,
2427 /* Some SPI errors deserve specific error messages */
2430 case SPI_ERROR_COPY:
2432 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2433 errmsg("cannot COPY to/from client in PL/pgSQL")));
2434 case SPI_ERROR_TRANSACTION:
2436 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2437 errmsg("cannot begin/end transactions in PL/pgSQL"),
2438 errhint("Use a BEGIN block with an EXCEPTION clause instead.")));
2440 elog(ERROR, "SPI_prepare_cursor failed for \"%s\": %s",
2441 expr->query, SPI_result_code_string(SPI_result));
2444 expr->plan = SPI_saveplan(plan);
2447 expr->plan_argtypes = plan->argtypes;
2448 exec_simple_check_plan(expr);
2455 * exec_stmt_execsql Execute an SQL statement (possibly with INTO).
2459 exec_stmt_execsql(PLpgSQL_execstate *estate,
2460 PLpgSQL_stmt_execsql *stmt)
2467 PLpgSQL_expr *expr = stmt->sqlstmt;
2470 * On the first call for this statement generate the plan, and detect
2471 * whether the statement is INSERT/UPDATE/DELETE
2473 if (expr->plan == NULL)
2477 exec_prepare_plan(estate, expr, 0);
2478 stmt->mod_stmt = false;
2479 foreach(l, expr->plan->plancache_list)
2481 CachedPlanSource *plansource = (CachedPlanSource *) lfirst(l);
2484 foreach(l2, plansource->plan->stmt_list)
2486 PlannedStmt *p = (PlannedStmt *) lfirst(l2);
2488 if (IsA(p, PlannedStmt) &&
2491 if (p->commandType == CMD_INSERT ||
2492 p->commandType == CMD_UPDATE ||
2493 p->commandType == CMD_DELETE)
2494 stmt->mod_stmt = true;
2501 * Now build up the values and nulls arguments for SPI_execute_plan()
2503 values = (Datum *) palloc(expr->nparams * sizeof(Datum));
2504 nulls = (char *) palloc(expr->nparams * sizeof(char));
2506 for (i = 0; i < expr->nparams; i++)
2508 PLpgSQL_datum *datum = estate->datums[expr->params[i]];
2512 exec_eval_datum(estate, datum, expr->plan_argtypes[i],
2513 ¶mtypeid, &values[i], ¶misnull);
2521 * If we have INTO, then we only need one row back ... but if we have INTO
2522 * STRICT, ask for two rows, so that we can verify the statement returns
2523 * only one. INSERT/UPDATE/DELETE are always treated strictly. Without
2524 * INTO, just run the statement to completion (tcount = 0).
2526 * We could just ask for two rows always when using INTO, but there are
2527 * some cases where demanding the extra row costs significant time, eg by
2528 * forcing completion of a sequential scan. So don't do it unless we need
2529 * to enforce strictness.
2533 if (stmt->strict || stmt->mod_stmt)
2544 rc = SPI_execute_plan(expr->plan, values, nulls,
2545 estate->readonly_func, tcount);
2548 * Check for error, and set FOUND if appropriate (for historical reasons
2549 * we set FOUND only for certain query types). Also Assert that we
2550 * identified the statement type the same as SPI did.
2555 Assert(!stmt->mod_stmt);
2556 exec_set_found(estate, (SPI_processed != 0));
2562 case SPI_OK_INSERT_RETURNING:
2563 case SPI_OK_UPDATE_RETURNING:
2564 case SPI_OK_DELETE_RETURNING:
2565 Assert(stmt->mod_stmt);
2566 exec_set_found(estate, (SPI_processed != 0));
2569 case SPI_OK_SELINTO:
2570 case SPI_OK_UTILITY:
2571 Assert(!stmt->mod_stmt);
2575 elog(ERROR, "SPI_execute_plan failed executing query \"%s\": %s",
2576 expr->query, SPI_result_code_string(rc));
2579 /* All variants should save result info for GET DIAGNOSTICS */
2580 estate->eval_processed = SPI_processed;
2581 estate->eval_lastoid = SPI_lastoid;
2583 /* Process INTO if present */
2586 SPITupleTable *tuptab = SPI_tuptable;
2587 uint32 n = SPI_processed;
2588 PLpgSQL_rec *rec = NULL;
2589 PLpgSQL_row *row = NULL;
2591 /* If the statement did not return a tuple table, complain */
2594 (errcode(ERRCODE_SYNTAX_ERROR),
2595 errmsg("INTO used with a command that cannot return data")));
2597 /* Determine if we assign to a record or a row */
2598 if (stmt->rec != NULL)
2599 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
2600 else if (stmt->row != NULL)
2601 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
2603 elog(ERROR, "unsupported target");
2606 * If SELECT ... INTO specified STRICT, and the query didn't find
2607 * exactly one row, throw an error. If STRICT was not specified, then
2608 * allow the query to find any number of rows.
2614 (errcode(ERRCODE_NO_DATA_FOUND),
2615 errmsg("query returned no rows")));
2616 /* set the target to NULL(s) */
2617 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
2621 if (n > 1 && (stmt->strict || stmt->mod_stmt))
2623 (errcode(ERRCODE_TOO_MANY_ROWS),
2624 errmsg("query returned more than one row")));
2625 /* Put the first result row into the target */
2626 exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
2630 SPI_freetuptable(SPI_tuptable);
2634 /* If the statement returned a tuple table, complain */
2635 if (SPI_tuptable != NULL)
2637 (errcode(ERRCODE_SYNTAX_ERROR),
2638 errmsg("query has no destination for result data"),
2639 (rc == SPI_OK_SELECT) ? errhint("If you want to discard the results of a SELECT, use PERFORM instead.") : 0));
2645 return PLPGSQL_RC_OK;
2650 * exec_stmt_dynexecute Execute a dynamic SQL query
2651 * (possibly with INTO).
2655 exec_stmt_dynexecute(PLpgSQL_execstate *estate,
2656 PLpgSQL_stmt_dynexecute *stmt)
2659 bool isnull = false;
2665 * First we evaluate the string expression after the EXECUTE keyword. Its
2666 * result is the querystring we have to execute.
2668 query = exec_eval_expr(estate, stmt->query, &isnull, &restype);
2671 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2672 errmsg("cannot EXECUTE a null querystring")));
2674 /* Get the C-String representation */
2675 querystr = convert_value_to_string(query, restype);
2677 exec_eval_cleanup(estate);
2680 * Call SPI_execute() without preparing a saved plan.
2682 exec_res = SPI_execute(querystr, estate->readonly_func, 0);
2690 case SPI_OK_INSERT_RETURNING:
2691 case SPI_OK_UPDATE_RETURNING:
2692 case SPI_OK_DELETE_RETURNING:
2693 case SPI_OK_UTILITY:
2699 * Also allow a zero return, which implies the querystring
2700 * contained no commands.
2704 case SPI_OK_SELINTO:
2707 * We want to disallow SELECT INTO for now, because its behavior
2708 * is not consistent with SELECT INTO in a normal plpgsql context.
2709 * (We need to reimplement EXECUTE to parse the string as a
2710 * plpgsql command, not just feed it to SPI_execute.) However,
2711 * CREATE AS should be allowed ... and since it produces the same
2712 * parsetree as SELECT INTO, there's no way to tell the difference
2713 * except to look at the source text. Wotta kluge!
2718 for (ptr = querystr; *ptr; ptr++)
2719 if (!scanner_isspace(*ptr))
2721 if (*ptr == 'S' || *ptr == 's')
2723 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2724 errmsg("EXECUTE of SELECT ... INTO is not implemented yet")));
2728 /* Some SPI errors deserve specific error messages */
2729 case SPI_ERROR_COPY:
2731 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2732 errmsg("cannot COPY to/from client in PL/pgSQL")));
2733 case SPI_ERROR_TRANSACTION:
2735 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2736 errmsg("cannot begin/end transactions in PL/pgSQL"),
2737 errhint("Use a BEGIN block with an EXCEPTION clause instead.")));
2740 elog(ERROR, "SPI_execute failed executing query \"%s\": %s",
2741 querystr, SPI_result_code_string(exec_res));
2745 /* Save result info for GET DIAGNOSTICS */
2746 estate->eval_processed = SPI_processed;
2747 estate->eval_lastoid = SPI_lastoid;
2749 /* Process INTO if present */
2752 SPITupleTable *tuptab = SPI_tuptable;
2753 uint32 n = SPI_processed;
2754 PLpgSQL_rec *rec = NULL;
2755 PLpgSQL_row *row = NULL;
2757 /* If the statement did not return a tuple table, complain */
2760 (errcode(ERRCODE_SYNTAX_ERROR),
2761 errmsg("INTO used with a command that cannot return data")));
2763 /* Determine if we assign to a record or a row */
2764 if (stmt->rec != NULL)
2765 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
2766 else if (stmt->row != NULL)
2767 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
2769 elog(ERROR, "unsupported target");
2772 * If SELECT ... INTO specified STRICT, and the query didn't find
2773 * exactly one row, throw an error. If STRICT was not specified, then
2774 * allow the query to find any number of rows.
2780 (errcode(ERRCODE_NO_DATA_FOUND),
2781 errmsg("query returned no rows")));
2782 /* set the target to NULL(s) */
2783 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
2787 if (n > 1 && stmt->strict)
2789 (errcode(ERRCODE_TOO_MANY_ROWS),
2790 errmsg("query returned more than one row")));
2791 /* Put the first result row into the target */
2792 exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
2798 * It might be a good idea to raise an error if the query returned
2799 * tuples that are being ignored, but historically we have not done
2804 /* Release any result from SPI_execute, as well as the querystring */
2805 SPI_freetuptable(SPI_tuptable);
2808 return PLPGSQL_RC_OK;
2813 * exec_stmt_dynfors Execute a dynamic query, assign each
2814 * tuple to a record or row and
2815 * execute a group of statements
2820 exec_stmt_dynfors(PLpgSQL_execstate *estate, PLpgSQL_stmt_dynfors *stmt)
2826 PLpgSQL_rec *rec = NULL;
2827 PLpgSQL_row *row = NULL;
2828 SPITupleTable *tuptab;
2835 * Determine if we assign to a record or a row
2837 if (stmt->rec != NULL)
2838 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
2839 else if (stmt->row != NULL)
2840 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
2842 elog(ERROR, "unsupported target");
2845 * Evaluate the string expression after the EXECUTE keyword. It's result
2846 * is the querystring we have to execute.
2848 query = exec_eval_expr(estate, stmt->query, &isnull, &restype);
2851 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2852 errmsg("cannot EXECUTE a null querystring")));
2854 /* Get the C-String representation */
2855 querystr = convert_value_to_string(query, restype);
2857 exec_eval_cleanup(estate);
2860 * Prepare a plan and open an implicit cursor for the query
2862 plan = SPI_prepare(querystr, 0, NULL);
2864 elog(ERROR, "SPI_prepare failed for \"%s\": %s",
2865 querystr, SPI_result_code_string(SPI_result));
2866 portal = SPI_cursor_open(NULL, plan, NULL, NULL,
2867 estate->readonly_func);
2869 elog(ERROR, "could not open implicit cursor for query \"%s\": %s",
2870 querystr, SPI_result_code_string(SPI_result));
2875 * Fetch the initial 10 tuples
2877 SPI_cursor_fetch(portal, true, 10);
2878 tuptab = SPI_tuptable;
2882 * If the query didn't return any rows, set the target to NULL and return
2883 * with FOUND = false.
2886 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
2888 found = true; /* processed at least one tuple */
2897 for (i = 0; i < n; i++)
2902 * Assign the tuple to the target
2904 exec_move_row(estate, rec, row, tuptab->vals[i], tuptab->tupdesc);
2907 * Execute the statements
2909 rc = exec_stmts(estate, stmt->body);
2911 if (rc != PLPGSQL_RC_OK)
2913 if (rc == PLPGSQL_RC_EXIT)
2915 if (estate->exitlabel == NULL)
2916 /* unlabelled exit, finish the current loop */
2918 else if (stmt->label != NULL &&
2919 strcmp(stmt->label, estate->exitlabel) == 0)
2921 /* labelled exit, matches the current stmt's label */
2922 estate->exitlabel = NULL;
2927 * otherwise, we processed a labelled exit that does not
2928 * match the current statement's label, if any: return
2929 * RC_EXIT so that the EXIT continues to recurse upward.
2932 else if (rc == PLPGSQL_RC_CONTINUE)
2934 if (estate->exitlabel == NULL)
2935 /* unlabelled continue, continue the current loop */
2937 else if (stmt->label != NULL &&
2938 strcmp(stmt->label, estate->exitlabel) == 0)
2940 /* labelled continue, matches the current stmt's label */
2941 estate->exitlabel = NULL;
2946 * otherwise, we process a labelled continue that does not
2947 * match the current statement's label, so propagate
2948 * RC_CONTINUE upward in the stack.
2953 * We're aborting the loop, so cleanup and set FOUND. (This
2954 * code should match the code after the loop.)
2956 SPI_freetuptable(tuptab);
2957 SPI_cursor_close(portal);
2958 exec_set_found(estate, found);
2964 SPI_freetuptable(tuptab);
2967 * Fetch the next 50 tuples
2969 SPI_cursor_fetch(portal, true, 50);
2971 tuptab = SPI_tuptable;
2975 * Release last group of tuples
2977 SPI_freetuptable(tuptab);
2980 * Close the implicit cursor
2982 SPI_cursor_close(portal);
2985 * Set the FOUND variable to indicate the result of executing the loop
2986 * (namely, whether we looped one or more times). This must be set here so
2987 * that it does not interfere with the value of the FOUND variable inside
2988 * the loop processing itself.
2990 exec_set_found(estate, found);
2992 return PLPGSQL_RC_OK;
2997 * exec_stmt_open Execute an OPEN cursor statement
3001 exec_stmt_open(PLpgSQL_execstate *estate, PLpgSQL_stmt_open *stmt)
3003 PLpgSQL_var *curvar = NULL;
3004 char *curname = NULL;
3005 PLpgSQL_expr *query = NULL;
3014 * Get the cursor variable and if it has an assigned name, check
3015 * that it's not in use currently.
3018 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
3019 if (!curvar->isnull)
3021 curname = DatumGetCString(DirectFunctionCall1(textout, curvar->value));
3022 if (SPI_cursor_find(curname) != NULL)
3024 (errcode(ERRCODE_DUPLICATE_CURSOR),
3025 errmsg("cursor \"%s\" already in use", curname)));
3029 * Process the OPEN according to it's type.
3032 if (stmt->query != NULL)
3035 * This is an OPEN refcursor FOR SELECT ...
3037 * We just make sure the query is planned. The real work is
3041 query = stmt->query;
3042 if (query->plan == NULL)
3043 exec_prepare_plan(estate, query, stmt->cursor_options);
3045 else if (stmt->dynquery != NULL)
3048 * This is an OPEN refcursor FOR EXECUTE ...
3057 * We evaluate the string expression after the
3058 * EXECUTE keyword. It's result is the querystring we have
3062 queryD = exec_eval_expr(estate, stmt->dynquery, &isnull, &restype);
3065 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3066 errmsg("cannot EXECUTE a null querystring")));
3068 /* Get the C-String representation */
3069 querystr = convert_value_to_string(queryD, restype);
3071 exec_eval_cleanup(estate);
3074 * Now we prepare a query plan for it and open a cursor
3077 curplan = SPI_prepare_cursor(querystr, 0, NULL, stmt->cursor_options);
3078 if (curplan == NULL)
3079 elog(ERROR, "SPI_prepare_cursor failed for \"%s\": %s",
3080 querystr, SPI_result_code_string(SPI_result));
3081 portal = SPI_cursor_open(curname, curplan, NULL, NULL,
3082 estate->readonly_func);
3084 elog(ERROR, "could not open cursor for query \"%s\": %s",
3085 querystr, SPI_result_code_string(SPI_result));
3087 SPI_freeplan(curplan);
3090 * Store the eventually assigned cursor name in the cursor variable
3094 curvar->value = DirectFunctionCall1(textin, CStringGetDatum(portal->name));
3095 curvar->isnull = false;
3096 curvar->freeval = true;
3098 return PLPGSQL_RC_OK;
3103 * This is an OPEN cursor
3105 * Note: parser should already have checked that statement supplies
3106 * args iff cursor needs them, but we check again to be safe.
3109 if (stmt->argquery != NULL)
3112 * OPEN CURSOR with args. We fake a SELECT ... INTO ...
3113 * statement to evaluate the args and put 'em into the
3117 PLpgSQL_stmt_execsql set_args;
3119 if (curvar->cursor_explicit_argrow < 0)
3121 (errcode(ERRCODE_SYNTAX_ERROR),
3122 errmsg("arguments given for cursor without arguments")));
3124 memset(&set_args, 0, sizeof(set_args));
3125 set_args.cmd_type = PLPGSQL_STMT_EXECSQL;
3126 set_args.lineno = stmt->lineno;
3127 set_args.sqlstmt = stmt->argquery;
3128 set_args.into = true;
3129 /* XXX historically this has not been STRICT */
3130 set_args.row = (PLpgSQL_row *)
3131 (estate->datums[curvar->cursor_explicit_argrow]);
3133 if (exec_stmt_execsql(estate, &set_args) != PLPGSQL_RC_OK)
3134 elog(ERROR, "open cursor failed during argument processing");
3138 if (curvar->cursor_explicit_argrow >= 0)
3140 (errcode(ERRCODE_SYNTAX_ERROR),
3141 errmsg("arguments required for cursor")));
3144 query = curvar->cursor_explicit_expr;
3145 if (query->plan == NULL)
3146 exec_prepare_plan(estate, query, curvar->cursor_options);
3150 * Here we go if we have a saved plan where we have to put
3151 * values into, either from an explicit cursor or from a
3152 * refcursor opened with OPEN ... FOR SELECT ...;
3155 values = (Datum *) palloc(query->nparams * sizeof(Datum));
3156 nulls = (char *) palloc(query->nparams * sizeof(char));
3158 for (i = 0; i < query->nparams; i++)
3160 PLpgSQL_datum *datum = estate->datums[query->params[i]];
3164 exec_eval_datum(estate, datum, query->plan_argtypes[i],
3165 ¶mtypeid, &values[i], ¶misnull);
3176 portal = SPI_cursor_open(curname, query->plan, values, nulls,
3177 estate->readonly_func);
3179 elog(ERROR, "could not open cursor: %s",
3180 SPI_result_code_string(SPI_result));
3188 * Store the eventually assigned portal name in the cursor variable
3192 curvar->value = DirectFunctionCall1(textin, CStringGetDatum(portal->name));
3193 curvar->isnull = false;
3194 curvar->freeval = true;
3196 return PLPGSQL_RC_OK;
3201 * exec_stmt_fetch Fetch from a cursor into a target, or just
3202 * move the current position of the cursor
3206 exec_stmt_fetch(PLpgSQL_execstate *estate, PLpgSQL_stmt_fetch *stmt)
3208 PLpgSQL_var *curvar = NULL;
3209 PLpgSQL_rec *rec = NULL;
3210 PLpgSQL_row *row = NULL;
3211 long how_many = stmt->how_many;
3212 SPITupleTable *tuptab;
3218 * Get the portal of the cursor by name
3221 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
3224 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3225 errmsg("cursor variable \"%s\" is NULL", curvar->refname)));
3226 curname = DatumGetCString(DirectFunctionCall1(textout, curvar->value));
3228 portal = SPI_cursor_find(curname);
3231 (errcode(ERRCODE_UNDEFINED_CURSOR),
3232 errmsg("cursor \"%s\" does not exist", curname)));
3235 /* Calculate position for FETCH_RELATIVE or FETCH_ABSOLUTE */
3240 /* XXX should be doing this in LONG not INT width */
3241 how_many = exec_eval_integer(estate, stmt->expr, &isnull);
3245 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3246 errmsg("relative or absolute cursor position is NULL")));
3248 exec_eval_cleanup(estate);
3254 * Determine if we fetch into a record or a row
3257 if (stmt->rec != NULL)
3258 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
3259 else if (stmt->row != NULL)
3260 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
3262 elog(ERROR, "unsupported target");
3265 * Fetch 1 tuple from the cursor
3268 SPI_scroll_cursor_fetch(portal, stmt->direction, how_many);
3269 tuptab = SPI_tuptable;
3273 * Set the target and the global FOUND variable appropriately.
3278 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
3279 exec_set_found(estate, false);
3283 exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
3284 exec_set_found(estate, true);
3287 SPI_freetuptable(tuptab);
3291 /* Move the cursor */
3292 SPI_scroll_cursor_move(portal, stmt->direction, how_many);
3295 /* Set the global FOUND variable appropriately. */
3296 exec_set_found(estate, n != 0);
3299 return PLPGSQL_RC_OK;
3303 * exec_stmt_close Close a cursor
3307 exec_stmt_close(PLpgSQL_execstate *estate, PLpgSQL_stmt_close *stmt)
3309 PLpgSQL_var *curvar = NULL;
3314 * Get the portal of the cursor by name
3317 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
3320 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3321 errmsg("cursor variable \"%s\" is NULL", curvar->refname)));
3322 curname = DatumGetCString(DirectFunctionCall1(textout, curvar->value));
3324 portal = SPI_cursor_find(curname);
3327 (errcode(ERRCODE_UNDEFINED_CURSOR),
3328 errmsg("cursor \"%s\" does not exist", curname)));
3335 SPI_cursor_close(portal);
3337 return PLPGSQL_RC_OK;
3342 * exec_assign_expr Put an expression's result into
3347 exec_assign_expr(PLpgSQL_execstate *estate, PLpgSQL_datum *target,
3352 bool isnull = false;
3354 value = exec_eval_expr(estate, expr, &isnull, &valtype);
3355 exec_assign_value(estate, target, value, valtype, &isnull);
3356 exec_eval_cleanup(estate);
3361 * exec_assign_value Put a value into a target field
3365 exec_assign_value(PLpgSQL_execstate *estate,
3366 PLpgSQL_datum *target,
3367 Datum value, Oid valtype, bool *isNull)
3369 switch (target->dtype)
3371 case PLPGSQL_DTYPE_VAR:
3374 * Target is a variable
3376 PLpgSQL_var *var = (PLpgSQL_var *) target;
3379 newvalue = exec_cast_value(value, valtype, var->datatype->typoid,
3380 &(var->datatype->typinput),
3381 var->datatype->typioparam,
3382 var->datatype->atttypmod,
3385 if (*isNull && var->notnull)
3387 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3388 errmsg("NULL cannot be assigned to variable \"%s\" declared NOT NULL",
3392 * If type is by-reference, make sure we have a freshly
3393 * palloc'd copy; the originally passed value may not live as
3394 * long as the variable! But we don't need to re-copy if
3395 * exec_cast_value performed a conversion; its output must
3396 * already be palloc'd.
3398 if (!var->datatype->typbyval && !*isNull)
3400 if (newvalue == value)
3401 newvalue = datumCopy(newvalue,
3403 var->datatype->typlen);
3407 * Now free the old value. (We can't do this any earlier
3408 * because of the possibility that we are assigning the var's
3409 * old value to it, eg "foo := foo". We could optimize out
3410 * the assignment altogether in such cases, but it's too
3411 * infrequent to be worth testing for.)
3415 var->value = newvalue;
3416 var->isnull = *isNull;
3417 if (!var->datatype->typbyval && !*isNull)
3418 var->freeval = true;
3422 case PLPGSQL_DTYPE_ROW:
3425 * Target is a row variable
3427 PLpgSQL_row *row = (PLpgSQL_row *) target;
3429 /* Source must be of RECORD or composite type */
3430 if (!type_is_rowtype(valtype))
3432 (errcode(ERRCODE_DATATYPE_MISMATCH),
3433 errmsg("cannot assign non-composite value to a row variable")));
3436 /* If source is null, just assign nulls to the row */
3437 exec_move_row(estate, NULL, row, NULL, NULL);
3445 HeapTupleData tmptup;
3447 /* Else source is a tuple Datum, safe to do this: */
3448 td = DatumGetHeapTupleHeader(value);
3449 /* Extract rowtype info and find a tupdesc */
3450 tupType = HeapTupleHeaderGetTypeId(td);
3451 tupTypmod = HeapTupleHeaderGetTypMod(td);
3452 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
3453 /* Build a temporary HeapTuple control structure */
3454 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
3455 ItemPointerSetInvalid(&(tmptup.t_self));
3456 tmptup.t_tableOid = InvalidOid;
3458 exec_move_row(estate, NULL, row, &tmptup, tupdesc);
3459 ReleaseTupleDesc(tupdesc);
3464 case PLPGSQL_DTYPE_REC:
3467 * Target is a record variable
3469 PLpgSQL_rec *rec = (PLpgSQL_rec *) target;
3471 /* Source must be of RECORD or composite type */
3472 if (!type_is_rowtype(valtype))
3474 (errcode(ERRCODE_DATATYPE_MISMATCH),
3475 errmsg("cannot assign non-composite value to a record variable")));
3478 /* If source is null, just assign nulls to the record */
3479 exec_move_row(estate, rec, NULL, NULL, NULL);
3487 HeapTupleData tmptup;
3489 /* Else source is a tuple Datum, safe to do this: */
3490 td = DatumGetHeapTupleHeader(value);
3491 /* Extract rowtype info and find a tupdesc */
3492 tupType = HeapTupleHeaderGetTypeId(td);
3493 tupTypmod = HeapTupleHeaderGetTypMod(td);
3494 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
3495 /* Build a temporary HeapTuple control structure */
3496 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
3497 ItemPointerSetInvalid(&(tmptup.t_self));
3498 tmptup.t_tableOid = InvalidOid;
3500 exec_move_row(estate, rec, NULL, &tmptup, tupdesc);
3501 ReleaseTupleDesc(tupdesc);
3506 case PLPGSQL_DTYPE_RECFIELD:
3509 * Target is a field of a record
3511 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) target;
3524 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
3527 * Check that there is already a tuple in the record. We need
3528 * that because records don't have any predefined field
3531 if (!HeapTupleIsValid(rec->tup))
3533 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3534 errmsg("record \"%s\" is not assigned yet",
3536 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
3539 * Get the number of the records field to change and the
3540 * number of attributes in the tuple.
3542 fno = SPI_fnumber(rec->tupdesc, recfield->fieldname);
3543 if (fno == SPI_ERROR_NOATTRIBUTE)
3545 (errcode(ERRCODE_UNDEFINED_COLUMN),
3546 errmsg("record \"%s\" has no field \"%s\"",
3547 rec->refname, recfield->fieldname)));
3549 natts = rec->tupdesc->natts;
3552 * Set up values/datums arrays for heap_formtuple. For all
3553 * the attributes except the one we want to replace, use the
3554 * value that's in the old tuple.
3556 values = palloc(sizeof(Datum) * natts);
3557 nulls = palloc(natts);
3559 for (i = 0; i < natts; i++)
3563 values[i] = SPI_getbinval(rec->tup, rec->tupdesc,
3572 * Now insert the new value, being careful to cast it to the
3575 atttype = SPI_gettypeid(rec->tupdesc, fno + 1);
3576 atttypmod = rec->tupdesc->attrs[fno]->atttypmod;
3577 attisnull = *isNull;
3578 values[fno] = exec_simple_cast_value(value,
3589 * Avoid leaking the result of exec_simple_cast_value, if it
3590 * performed a conversion to a pass-by-ref type.
3592 if (!attisnull && values[fno] != value && !get_typbyval(atttype))
3593 mustfree = DatumGetPointer(values[fno]);
3598 * Now call heap_formtuple() to create a new tuple that
3599 * replaces the old one in the record.
3601 newtup = heap_formtuple(rec->tupdesc, values, nulls);
3604 heap_freetuple(rec->tup);
3607 rec->freetup = true;
3617 case PLPGSQL_DTYPE_ARRAYELEM:
3621 PLpgSQL_expr *subscripts[MAXDIM];
3622 int subscriptvals[MAXDIM];
3623 bool oldarrayisnull;
3630 Datum oldarraydatum,
3632 ArrayType *oldarrayval;
3633 ArrayType *newarrayval;
3636 * Target is an element of an array
3638 * To handle constructs like x[1][2] := something, we have to
3639 * be prepared to deal with a chain of arrayelem datums. Chase
3640 * back to find the base array datum, and save the subscript
3641 * expressions as we go. (We are scanning right to left here,
3642 * but want to evaluate the subscripts left-to-right to
3643 * minimize surprises.)
3648 PLpgSQL_arrayelem *arrayelem = (PLpgSQL_arrayelem *) target;
3650 if (nsubscripts >= MAXDIM)
3652 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
3653 errmsg("number of array dimensions exceeds the maximum allowed, %d",
3655 subscripts[nsubscripts++] = arrayelem->subscript;
3656 target = estate->datums[arrayelem->arrayparentno];
3657 } while (target->dtype == PLPGSQL_DTYPE_ARRAYELEM);
3659 /* Fetch current value of array datum */
3660 exec_eval_datum(estate, target, InvalidOid,
3661 &arraytypeid, &oldarraydatum, &oldarrayisnull);
3663 arrayelemtypeid = get_element_type(arraytypeid);
3664 if (!OidIsValid(arrayelemtypeid))
3666 (errcode(ERRCODE_DATATYPE_MISMATCH),
3667 errmsg("subscripted object is not an array")));
3669 get_typlenbyvalalign(arrayelemtypeid,
3673 arraytyplen = get_typlen(arraytypeid);
3676 * Evaluate the subscripts, switch into left-to-right order.
3677 * Like ExecEvalArrayRef(), complain if any subscript is null.
3679 for (i = 0; i < nsubscripts; i++)
3684 exec_eval_integer(estate,
3685 subscripts[nsubscripts - 1 - i],
3689 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3690 errmsg("array subscript in assignment must not be NULL")));
3693 /* Coerce source value to match array element type. */
3694 coerced_value = exec_simple_cast_value(value,
3701 * If the original array is null, cons up an empty array so
3702 * that the assignment can proceed; we'll end with a
3703 * one-element array containing just the assigned-to
3704 * subscript. This only works for varlena arrays, though; for
3705 * fixed-length array types we skip the assignment. We can't
3706 * support assignment of a null entry into a fixed-length
3707 * array, either, so that's a no-op too. This is all ugly but
3708 * corresponds to the current behavior of ExecEvalArrayRef().
3710 if (arraytyplen > 0 && /* fixed-length array? */
3711 (oldarrayisnull || *isNull))
3715 oldarrayval = construct_empty_array(arrayelemtypeid);
3717 oldarrayval = (ArrayType *) DatumGetPointer(oldarraydatum);
3720 * Build the modified array value.
3722 newarrayval = array_set(oldarrayval,
3733 * Avoid leaking the result of exec_simple_cast_value, if it
3734 * performed a conversion to a pass-by-ref type.
3736 if (!*isNull && coerced_value != value && !elemtypbyval)
3737 pfree(DatumGetPointer(coerced_value));
3740 * Assign the new array to the base variable. It's never NULL
3744 exec_assign_value(estate, target,
3745 PointerGetDatum(newarrayval),
3746 arraytypeid, isNull);
3749 * Avoid leaking the modified array value, too.
3756 elog(ERROR, "unrecognized dtype: %d", target->dtype);
3761 * exec_eval_datum Get current value of a PLpgSQL_datum
3763 * The type oid, value in Datum format, and null flag are returned.
3765 * If expectedtypeid isn't InvalidOid, it is checked against the actual type.
3767 * At present this doesn't handle PLpgSQL_expr or PLpgSQL_arrayelem datums.
3769 * NOTE: caller must not modify the returned value, since it points right
3770 * at the stored value in the case of pass-by-reference datatypes. In some
3771 * cases we have to palloc a return value, and in such cases we put it into
3772 * the estate's short-term memory context.
3775 exec_eval_datum(PLpgSQL_execstate *estate,
3776 PLpgSQL_datum *datum,
3782 MemoryContext oldcontext;
3784 switch (datum->dtype)
3786 case PLPGSQL_DTYPE_VAR:
3788 PLpgSQL_var *var = (PLpgSQL_var *) datum;
3790 *typeid = var->datatype->typoid;
3791 *value = var->value;
3792 *isnull = var->isnull;
3793 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3795 (errcode(ERRCODE_DATATYPE_MISMATCH),
3796 errmsg("type of \"%s\" does not match that when preparing the plan",
3801 case PLPGSQL_DTYPE_ROW:
3803 PLpgSQL_row *row = (PLpgSQL_row *) datum;
3806 if (!row->rowtupdesc) /* should not happen */
3807 elog(ERROR, "row variable has no tupdesc");
3808 /* Make sure we have a valid type/typmod setting */
3809 BlessTupleDesc(row->rowtupdesc);
3810 oldcontext = MemoryContextSwitchTo(estate->eval_econtext->ecxt_per_tuple_memory);
3811 tup = make_tuple_from_row(estate, row, row->rowtupdesc);
3812 if (tup == NULL) /* should not happen */
3813 elog(ERROR, "row not compatible with its own tupdesc");
3814 MemoryContextSwitchTo(oldcontext);
3815 *typeid = row->rowtupdesc->tdtypeid;
3816 *value = HeapTupleGetDatum(tup);
3818 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3820 (errcode(ERRCODE_DATATYPE_MISMATCH),
3821 errmsg("type of \"%s\" does not match that when preparing the plan",
3826 case PLPGSQL_DTYPE_REC:
3828 PLpgSQL_rec *rec = (PLpgSQL_rec *) datum;
3829 HeapTupleData worktup;
3831 if (!HeapTupleIsValid(rec->tup))
3833 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3834 errmsg("record \"%s\" is not assigned yet",
3836 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
3837 Assert(rec->tupdesc != NULL);
3838 /* Make sure we have a valid type/typmod setting */
3839 BlessTupleDesc(rec->tupdesc);
3842 * In a trigger, the NEW and OLD parameters are likely to be
3843 * on-disk tuples that don't have the desired Datum fields.
3844 * Copy the tuple body and insert the right values.
3846 oldcontext = MemoryContextSwitchTo(estate->eval_econtext->ecxt_per_tuple_memory);
3847 heap_copytuple_with_tuple(rec->tup, &worktup);
3848 HeapTupleHeaderSetDatumLength(worktup.t_data, worktup.t_len);
3849 HeapTupleHeaderSetTypeId(worktup.t_data, rec->tupdesc->tdtypeid);
3850 HeapTupleHeaderSetTypMod(worktup.t_data, rec->tupdesc->tdtypmod);
3851 MemoryContextSwitchTo(oldcontext);
3852 *typeid = rec->tupdesc->tdtypeid;
3853 *value = HeapTupleGetDatum(&worktup);
3855 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3857 (errcode(ERRCODE_DATATYPE_MISMATCH),
3858 errmsg("type of \"%s\" does not match that when preparing the plan",
3863 case PLPGSQL_DTYPE_RECFIELD:
3865 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) datum;
3869 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
3870 if (!HeapTupleIsValid(rec->tup))
3872 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3873 errmsg("record \"%s\" is not assigned yet",
3875 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
3876 fno = SPI_fnumber(rec->tupdesc, recfield->fieldname);
3877 if (fno == SPI_ERROR_NOATTRIBUTE)
3879 (errcode(ERRCODE_UNDEFINED_COLUMN),
3880 errmsg("record \"%s\" has no field \"%s\"",
3881 rec->refname, recfield->fieldname)));
3882 *typeid = SPI_gettypeid(rec->tupdesc, fno);
3883 *value = SPI_getbinval(rec->tup, rec->tupdesc, fno, isnull);
3884 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3886 (errcode(ERRCODE_DATATYPE_MISMATCH),
3887 errmsg("type of \"%s.%s\" does not match that when preparing the plan",
3888 rec->refname, recfield->fieldname)));
3892 case PLPGSQL_DTYPE_TRIGARG:
3894 PLpgSQL_trigarg *trigarg = (PLpgSQL_trigarg *) datum;
3898 tgargno = exec_eval_integer(estate, trigarg->argnum, isnull);
3899 if (*isnull || tgargno < 0 || tgargno >= estate->trig_nargs)
3906 *value = estate->trig_argv[tgargno];
3909 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3911 (errcode(ERRCODE_DATATYPE_MISMATCH),
3912 errmsg("type of tgargv[%d] does not match that when preparing the plan",
3918 elog(ERROR, "unrecognized dtype: %d", datum->dtype);
3923 * exec_eval_integer Evaluate an expression, coerce result to int4
3925 * Note we do not do exec_eval_cleanup here; the caller must do it at
3926 * some later point. (We do this because the caller may be holding the
3927 * results of other, pass-by-reference, expression evaluations, such as
3928 * an array value to be subscripted. Also see notes in exec_eval_simple_expr
3929 * about allocation of the parameter array.)
3933 exec_eval_integer(PLpgSQL_execstate *estate,
3940 exprdatum = exec_eval_expr(estate, expr, isNull, &exprtypeid);
3941 exprdatum = exec_simple_cast_value(exprdatum, exprtypeid,
3944 return DatumGetInt32(exprdatum);
3948 * exec_eval_boolean Evaluate an expression, coerce result to bool
3950 * Note we do not do exec_eval_cleanup here; the caller must do it at
3955 exec_eval_boolean(PLpgSQL_execstate *estate,
3962 exprdatum = exec_eval_expr(estate, expr, isNull, &exprtypeid);
3963 exprdatum = exec_simple_cast_value(exprdatum, exprtypeid,
3966 return DatumGetBool(exprdatum);
3970 * exec_eval_expr Evaluate an expression and return
3973 * NOTE: caller must do exec_eval_cleanup when done with the Datum.
3977 exec_eval_expr(PLpgSQL_execstate *estate,
3986 * If first time through, create a plan for this expression.
3988 if (expr->plan == NULL)
3989 exec_prepare_plan(estate, expr, 0);
3992 * If this is a simple expression, bypass SPI and use the executor
3995 if (exec_eval_simple_expr(estate, expr, &result, isNull, rettype))
3999 * Else do it the hard way via exec_run_select
4001 rc = exec_run_select(estate, expr, 2, NULL);
4002 if (rc != SPI_OK_SELECT)
4004 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
4005 errmsg("query \"%s\" did not return data", expr->query)));
4008 * If there are no rows selected, the result is NULL.
4010 if (estate->eval_processed == 0)
4017 * Check that the expression returned one single Datum
4019 if (estate->eval_processed > 1)
4021 (errcode(ERRCODE_CARDINALITY_VIOLATION),
4022 errmsg("query \"%s\" returned more than one row",
4024 if (estate->eval_tuptable->tupdesc->natts != 1)
4026 (errcode(ERRCODE_SYNTAX_ERROR),
4027 errmsg("query \"%s\" returned %d columns", expr->query,
4028 estate->eval_tuptable->tupdesc->natts)));
4031 * Return the result and its type
4033 *rettype = SPI_gettypeid(estate->eval_tuptable->tupdesc, 1);
4034 return SPI_getbinval(estate->eval_tuptable->vals[0],
4035 estate->eval_tuptable->tupdesc, 1, isNull);
4040 * exec_run_select Execute a select query
4044 exec_run_select(PLpgSQL_execstate *estate,
4045 PLpgSQL_expr *expr, long maxtuples, Portal *portalP)
4053 * On the first call for this expression generate the plan
4055 if (expr->plan == NULL)
4056 exec_prepare_plan(estate, expr, 0);
4059 * Now build up the values and nulls arguments for SPI_execute_plan()
4061 values = (Datum *) palloc(expr->nparams * sizeof(Datum));
4062 nulls = (char *) palloc(expr->nparams * sizeof(char));
4064 for (i = 0; i < expr->nparams; i++)
4066 PLpgSQL_datum *datum = estate->datums[expr->params[i]];
4070 exec_eval_datum(estate, datum, expr->plan_argtypes[i],
4071 ¶mtypeid, &values[i], ¶misnull);
4079 * If a portal was requested, put the query into the portal
4081 if (portalP != NULL)
4083 *portalP = SPI_cursor_open(NULL, expr->plan, values, nulls,
4084 estate->readonly_func);
4085 if (*portalP == NULL)
4086 elog(ERROR, "could not open implicit cursor for query \"%s\": %s",
4087 expr->query, SPI_result_code_string(SPI_result));
4090 return SPI_OK_CURSOR;
4096 rc = SPI_execute_plan(expr->plan, values, nulls,
4097 estate->readonly_func, maxtuples);
4098 if (rc != SPI_OK_SELECT)
4100 (errcode(ERRCODE_SYNTAX_ERROR),
4101 errmsg("query \"%s\" is not a SELECT", expr->query)));
4103 /* Save query results for eventual cleanup */
4104 Assert(estate->eval_tuptable == NULL);
4105 estate->eval_tuptable = SPI_tuptable;
4106 estate->eval_processed = SPI_processed;
4107 estate->eval_lastoid = SPI_lastoid;
4117 * exec_eval_simple_expr - Evaluate a simple expression returning
4118 * a Datum by directly calling ExecEvalExpr().
4120 * If successful, store results into *result, *isNull, *rettype and return
4121 * TRUE. If the expression is not simple (any more), return FALSE.
4123 * It is possible though unlikely for a simple expression to become non-simple
4124 * (consider for example redefining a trivial view). We must handle that for
4125 * correctness; fortunately it's normally inexpensive to do
4126 * RevalidateCachedPlan on a simple expression. We do not consider the other
4127 * direction (non-simple expression becoming simple) because we'll still give
4128 * correct results if that happens, and it's unlikely to be worth the cycles
4131 * Note: if pass-by-reference, the result is in the eval_econtext's
4132 * temporary memory context. It will be freed when exec_eval_cleanup
4137 exec_eval_simple_expr(PLpgSQL_execstate *estate,
4143 ExprContext *econtext = estate->eval_econtext;
4144 CachedPlanSource *plansource;
4146 ParamListInfo paramLI;
4148 Snapshot saveActiveSnapshot;
4151 * Forget it if expression wasn't simple before.
4153 if (expr->expr_simple_expr == NULL)
4157 * Revalidate cached plan, so that we will notice if it became stale. (We
4158 * also need to hold a refcount while using the plan.) Note that even if
4159 * replanning occurs, the length of plancache_list can't change, since it
4160 * is a property of the raw parsetree generated from the query text.
4162 Assert(list_length(expr->plan->plancache_list) == 1);
4163 plansource = (CachedPlanSource *) linitial(expr->plan->plancache_list);
4164 cplan = RevalidateCachedPlan(plansource, true);
4165 if (cplan->generation != expr->expr_simple_generation)
4167 /* It got replanned ... is it still simple? */
4168 exec_simple_check_plan(expr);
4169 if (expr->expr_simple_expr == NULL)
4171 /* Ooops, release refcount and fail */
4172 ReleaseCachedPlan(cplan, true);
4178 * Pass back previously-determined result type.
4180 *rettype = expr->expr_simple_type;
4183 * Prepare the expression for execution, if it's not been done already in
4184 * the current eval_estate. (This will be forced to happen if we called
4185 * exec_simple_check_plan above.)
4187 if (expr->expr_simple_id != estate->eval_estate_simple_id)
4189 expr->expr_simple_state = ExecPrepareExpr(expr->expr_simple_expr,
4190 estate->eval_estate);
4191 expr->expr_simple_id = estate->eval_estate_simple_id;
4195 * Param list can live in econtext's temporary memory context.
4197 * XXX think about avoiding repeated palloc's for param lists? Beware
4198 * however that this routine is re-entrant: exec_eval_datum() can call it
4199 * back for subscript evaluation, and so there can be a need to have more
4200 * than one active param list.
4202 if (expr->nparams > 0)
4204 /* sizeof(ParamListInfoData) includes the first array element */
4205 paramLI = (ParamListInfo)
4206 MemoryContextAlloc(econtext->ecxt_per_tuple_memory,
4207 sizeof(ParamListInfoData) +
4208 (expr->nparams - 1) *sizeof(ParamExternData));
4209 paramLI->numParams = expr->nparams;
4211 for (i = 0; i < expr->nparams; i++)
4213 ParamExternData *prm = ¶mLI->params[i];
4214 PLpgSQL_datum *datum = estate->datums[expr->params[i]];
4217 exec_eval_datum(estate, datum, expr->plan_argtypes[i],
4219 &prm->value, &prm->isnull);
4226 * Now we can safely make the econtext point to the param list.
4228 econtext->ecxt_param_list_info = paramLI;
4231 * We have to do some of the things SPI_execute_plan would do, in
4232 * particular advance the snapshot if we are in a non-read-only function.
4233 * Without this, stable functions within the expression would fail to see
4234 * updates made so far by our own function.
4237 saveActiveSnapshot = ActiveSnapshot;
4241 MemoryContext oldcontext;
4243 oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
4244 if (!estate->readonly_func)
4246 CommandCounterIncrement();
4247 ActiveSnapshot = CopySnapshot(GetTransactionSnapshot());
4251 * Finally we can call the executor to evaluate the expression
4253 *result = ExecEvalExpr(expr->expr_simple_state,
4257 MemoryContextSwitchTo(oldcontext);
4261 /* Restore global vars and propagate error */
4262 ActiveSnapshot = saveActiveSnapshot;
4267 ActiveSnapshot = saveActiveSnapshot;
4271 * Now we can release our refcount on the cached plan.
4273 ReleaseCachedPlan(cplan, true);
4283 * exec_move_row Move one tuple's values into a record or row
4287 exec_move_row(PLpgSQL_execstate *estate,
4290 HeapTuple tup, TupleDesc tupdesc)
4293 * Record is simple - just copy the tuple and its descriptor into the
4299 * copy input first, just in case it is pointing at variable's value
4301 if (HeapTupleIsValid(tup))
4302 tup = heap_copytuple(tup);
4304 tupdesc = CreateTupleDescCopy(tupdesc);
4308 heap_freetuple(rec->tup);
4309 rec->freetup = false;
4311 if (rec->freetupdesc)
4313 FreeTupleDesc(rec->tupdesc);
4314 rec->freetupdesc = false;
4317 if (HeapTupleIsValid(tup))
4320 rec->freetup = true;
4324 /* If we have a tupdesc but no data, form an all-nulls tuple */
4327 nulls = (char *) palloc(tupdesc->natts * sizeof(char));
4328 memset(nulls, 'n', tupdesc->natts * sizeof(char));
4330 rec->tup = heap_formtuple(tupdesc, NULL, nulls);
4331 rec->freetup = true;
4340 rec->tupdesc = tupdesc;
4341 rec->freetupdesc = true;
4344 rec->tupdesc = NULL;
4350 * Row is a bit more complicated in that we assign the individual
4351 * attributes of the tuple to the variables the row points to.
4353 * NOTE: this code used to demand row->nfields ==
4354 * HeapTupleHeaderGetNatts(tup->t_data, but that's wrong. The tuple might
4355 * have more fields than we expected if it's from an inheritance-child
4356 * table of the current table, or it might have fewer if the table has had
4357 * columns added by ALTER TABLE. Ignore extra columns and assume NULL for
4358 * missing columns, the same as heap_getattr would do. We also have to
4359 * skip over dropped columns in either the source or destination.
4361 * If we have no tuple data at all, we'll assign NULL to all columns of
4370 if (HeapTupleIsValid(tup))
4371 t_natts = HeapTupleHeaderGetNatts(tup->t_data);
4376 for (fnum = 0; fnum < row->nfields; fnum++)
4383 if (row->varnos[fnum] < 0)
4384 continue; /* skip dropped column in row struct */
4386 var = (PLpgSQL_var *) (estate->datums[row->varnos[fnum]]);
4388 while (anum < t_natts && tupdesc->attrs[anum]->attisdropped)
4389 anum++; /* skip dropped column in tuple */
4393 value = SPI_getbinval(tup, tupdesc, anum + 1, &isnull);
4394 valtype = SPI_gettypeid(tupdesc, anum + 1);
4401 valtype = InvalidOid;
4404 exec_assign_value(estate, (PLpgSQL_datum *) var,
4405 value, valtype, &isnull);
4411 elog(ERROR, "unsupported target");
4415 * make_tuple_from_row Make a tuple from the values of a row object
4417 * A NULL return indicates rowtype mismatch; caller must raise suitable error
4421 make_tuple_from_row(PLpgSQL_execstate *estate,
4425 int natts = tupdesc->natts;
4431 if (natts != row->nfields)
4434 dvalues = (Datum *) palloc0(natts * sizeof(Datum));
4435 nulls = (bool *) palloc(natts * sizeof(bool));
4437 for (i = 0; i < natts; i++)
4441 if (tupdesc->attrs[i]->attisdropped)
4443 nulls[i] = true; /* leave the column as null */
4446 if (row->varnos[i] < 0) /* should not happen */
4447 elog(ERROR, "dropped rowtype entry for non-dropped column");
4449 exec_eval_datum(estate, estate->datums[row->varnos[i]],
4450 InvalidOid, &fieldtypeid, &dvalues[i], &nulls[i]);
4451 if (fieldtypeid != tupdesc->attrs[i]->atttypid)
4455 tuple = heap_form_tuple(tupdesc, dvalues, nulls);
4464 * convert_value_to_string Convert a non-null Datum to C string
4466 * Note: callers generally assume that the result is a palloc'd string and
4467 * should be pfree'd. This is not all that safe an assumption ...
4469 * Note: not caching the conversion function lookup is bad for performance.
4473 convert_value_to_string(Datum value, Oid valtype)
4479 getTypeOutputInfo(valtype, &typoutput, &typIsVarlena);
4482 * We do SPI_push to allow the datatype output function to use SPI.
4483 * However we do not mess around with CommandCounterIncrement or advancing
4484 * the snapshot, which means that a stable output function would not see
4485 * updates made so far by our own function. The use-case for such
4486 * scenarios seems too narrow to justify the cycles that would be
4491 str = OidOutputFunctionCall(typoutput, value);
4499 * exec_cast_value Cast a value if required
4503 exec_cast_value(Datum value, Oid valtype,
4511 * If the type of the queries return value isn't that of the variable,
4514 if (valtype != reqtype || reqtypmod != -1)
4520 extval = convert_value_to_string(value, valtype);
4522 /* Allow input function to use SPI ... see notes above */
4525 value = InputFunctionCall(reqinput, extval,
4526 reqtypioparam, reqtypmod);
4536 value = InputFunctionCall(reqinput, NULL,
4537 reqtypioparam, reqtypmod);
4547 * exec_simple_cast_value Cast a value if required
4549 * As above, but need not supply details about target type. Note that this
4550 * is slower than exec_cast_value with cached type info, and so should be
4551 * avoided in heavily used code paths.
4555 exec_simple_cast_value(Datum value, Oid valtype,
4556 Oid reqtype, int32 reqtypmod,
4561 if (valtype != reqtype || reqtypmod != -1)
4565 FmgrInfo finfo_input;
4567 getTypeInputInfo(reqtype, &typinput, &typioparam);
4569 fmgr_info(typinput, &finfo_input);
4571 value = exec_cast_value(value,
4586 * exec_simple_check_node - Recursively check if an expression
4587 * is made only of simple things we can
4588 * hand out directly to ExecEvalExpr()
4589 * instead of calling SPI.
4593 exec_simple_check_node(Node *node)
4598 switch (nodeTag(node))
4608 ArrayRef *expr = (ArrayRef *) node;
4610 if (!exec_simple_check_node((Node *) expr->refupperindexpr))
4612 if (!exec_simple_check_node((Node *) expr->reflowerindexpr))
4614 if (!exec_simple_check_node((Node *) expr->refexpr))
4616 if (!exec_simple_check_node((Node *) expr->refassgnexpr))
4624 FuncExpr *expr = (FuncExpr *) node;
4626 if (expr->funcretset)
4628 if (!exec_simple_check_node((Node *) expr->args))
4636 OpExpr *expr = (OpExpr *) node;
4640 if (!exec_simple_check_node((Node *) expr->args))
4646 case T_DistinctExpr:
4648 DistinctExpr *expr = (DistinctExpr *) node;
4652 if (!exec_simple_check_node((Node *) expr->args))
4658 case T_ScalarArrayOpExpr:
4660 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
4662 if (!exec_simple_check_node((Node *) expr->args))
4670 BoolExpr *expr = (BoolExpr *) node;
4672 if (!exec_simple_check_node((Node *) expr->args))
4679 return exec_simple_check_node((Node *) ((FieldSelect *) node)->arg);
4683 FieldStore *expr = (FieldStore *) node;
4685 if (!exec_simple_check_node((Node *) expr->arg))
4687 if (!exec_simple_check_node((Node *) expr->newvals))
4694 return exec_simple_check_node((Node *) ((RelabelType *) node)->arg);
4697 return exec_simple_check_node((Node *) ((CoerceViaIO *) node)->arg);
4699 case T_ArrayCoerceExpr:
4700 return exec_simple_check_node((Node *) ((ArrayCoerceExpr *) node)->arg);
4702 case T_ConvertRowtypeExpr:
4703 return exec_simple_check_node((Node *) ((ConvertRowtypeExpr *) node)->arg);
4707 CaseExpr *expr = (CaseExpr *) node;
4709 if (!exec_simple_check_node((Node *) expr->arg))
4711 if (!exec_simple_check_node((Node *) expr->args))
4713 if (!exec_simple_check_node((Node *) expr->defresult))
4721 CaseWhen *when = (CaseWhen *) node;
4723 if (!exec_simple_check_node((Node *) when->expr))
4725 if (!exec_simple_check_node((Node *) when->result))
4731 case T_CaseTestExpr:
4736 ArrayExpr *expr = (ArrayExpr *) node;
4738 if (!exec_simple_check_node((Node *) expr->elements))
4746 RowExpr *expr = (RowExpr *) node;
4748 if (!exec_simple_check_node((Node *) expr->args))
4754 case T_RowCompareExpr:
4756 RowCompareExpr *expr = (RowCompareExpr *) node;
4758 if (!exec_simple_check_node((Node *) expr->largs))
4760 if (!exec_simple_check_node((Node *) expr->rargs))
4766 case T_CoalesceExpr:
4768 CoalesceExpr *expr = (CoalesceExpr *) node;
4770 if (!exec_simple_check_node((Node *) expr->args))
4778 MinMaxExpr *expr = (MinMaxExpr *) node;
4780 if (!exec_simple_check_node((Node *) expr->args))
4788 XmlExpr *expr = (XmlExpr *) node;
4790 if (!exec_simple_check_node((Node *) expr->named_args))
4792 if (!exec_simple_check_node((Node *) expr->args))
4800 NullIfExpr *expr = (NullIfExpr *) node;
4804 if (!exec_simple_check_node((Node *) expr->args))
4811 return exec_simple_check_node((Node *) ((NullTest *) node)->arg);
4814 return exec_simple_check_node((Node *) ((BooleanTest *) node)->arg);
4816 case T_CoerceToDomain:
4817 return exec_simple_check_node((Node *) ((CoerceToDomain *) node)->arg);
4819 case T_CoerceToDomainValue:
4824 List *expr = (List *) node;
4829 if (!exec_simple_check_node(lfirst(l)))
4843 * exec_simple_check_plan - Check if a plan is simple enough to
4844 * be evaluated by ExecEvalExpr() instead
4849 exec_simple_check_plan(PLpgSQL_expr *expr)
4851 CachedPlanSource *plansource;
4857 * Initialize to "not simple", and remember the plan generation number we
4858 * last checked. (If the query produces more or less than one parsetree
4859 * we just leave expr_simple_generation set to 0.)
4861 expr->expr_simple_expr = NULL;
4862 expr->expr_simple_generation = 0;
4865 * 1. We can only evaluate queries that resulted in one single execution
4868 if (list_length(expr->plan->plancache_list) != 1)
4870 plansource = (CachedPlanSource *) linitial(expr->plan->plancache_list);
4871 expr->expr_simple_generation = plansource->generation;
4872 if (list_length(plansource->plan->stmt_list) != 1)
4875 stmt = (PlannedStmt *) linitial(plansource->plan->stmt_list);
4878 * 2. It must be a RESULT plan --> no scan's required
4880 if (!IsA(stmt, PlannedStmt))
4882 plan = stmt->planTree;
4883 if (!IsA(plan, Result))
4887 * 3. Can't have any subplan or qual clause, either
4889 if (plan->lefttree != NULL ||
4890 plan->righttree != NULL ||
4891 plan->initPlan != NULL ||
4892 plan->qual != NULL ||
4893 ((Result *) plan)->resconstantqual != NULL)
4897 * 4. The plan must have a single attribute as result
4899 if (list_length(plan->targetlist) != 1)
4902 tle = (TargetEntry *) linitial(plan->targetlist);
4905 * 5. Check that all the nodes in the expression are non-scary.
4907 if (!exec_simple_check_node((Node *) tle->expr))
4911 * Yes - this is a simple expression. Mark it as such, and initialize
4912 * state to "not valid in current transaction".
4914 expr->expr_simple_expr = tle->expr;
4915 expr->expr_simple_state = NULL;
4916 expr->expr_simple_id = -1;
4917 /* Also stash away the expression result type */
4918 expr->expr_simple_type = exprType((Node *) tle->expr);
4922 * Check two tupledescs have matching number and types of attributes
4925 compatible_tupdesc(TupleDesc td1, TupleDesc td2)
4929 if (td1->natts != td2->natts)
4932 for (i = 0; i < td1->natts; i++)
4934 if (td1->attrs[i]->atttypid != td2->attrs[i]->atttypid)
4942 * exec_set_found Set the global found variable
4947 exec_set_found(PLpgSQL_execstate *estate, bool state)
4951 var = (PLpgSQL_var *) (estate->datums[estate->found_varno]);
4952 var->value = (Datum) state;
4953 var->isnull = false;
4957 * plpgsql_create_econtext --- create an eval_econtext for the current function
4959 * We may need to create a new eval_estate too, if there's not one already
4960 * for the current (sub) transaction. The EState will be cleaned up at
4961 * (sub) transaction end.
4964 plpgsql_create_econtext(PLpgSQL_execstate *estate)
4966 SubTransactionId my_subxid = GetCurrentSubTransactionId();
4967 SimpleEstateStackEntry *entry = simple_estate_stack;
4969 /* Create new EState if not one for current subxact */
4970 if (entry == NULL ||
4971 entry->xact_subxid != my_subxid)
4973 MemoryContext oldcontext;
4975 /* Stack entries are kept in TopTransactionContext for simplicity */
4976 entry = (SimpleEstateStackEntry *)
4977 MemoryContextAlloc(TopTransactionContext,
4978 sizeof(SimpleEstateStackEntry));
4980 /* But each EState should be a child of its CurTransactionContext */
4981 oldcontext = MemoryContextSwitchTo(CurTransactionContext);
4982 entry->xact_eval_estate = CreateExecutorState();
4983 MemoryContextSwitchTo(oldcontext);
4985 /* Assign a reasonably-unique ID to this EState */
4986 entry->xact_estate_simple_id = simple_estate_id_counter++;
4987 entry->xact_subxid = my_subxid;
4989 entry->next = simple_estate_stack;
4990 simple_estate_stack = entry;
4993 /* Link plpgsql estate to it */
4994 estate->eval_estate = entry->xact_eval_estate;
4995 estate->eval_estate_simple_id = entry->xact_estate_simple_id;
4997 /* And create a child econtext for the current function */
4998 estate->eval_econtext = CreateExprContext(estate->eval_estate);
5002 * plpgsql_xact_cb --- post-transaction-commit-or-abort cleanup
5004 * If a simple-expression EState was created in the current transaction,
5005 * it has to be cleaned up.
5008 plpgsql_xact_cb(XactEvent event, void *arg)
5011 * If we are doing a clean transaction shutdown, free the EState (so that
5012 * any remaining resources will be released correctly). In an abort, we
5013 * expect the regular abort recovery procedures to release everything of
5014 * interest. We don't need to free the individual stack entries since
5015 * TopTransactionContext is about to go away anyway.
5017 * Note: if plpgsql_subxact_cb is doing its job, there should be at most
5018 * one stack entry, but we may as well code this as a loop.
5020 if (event != XACT_EVENT_ABORT)
5022 while (simple_estate_stack != NULL)
5024 FreeExecutorState(simple_estate_stack->xact_eval_estate);
5025 simple_estate_stack = simple_estate_stack->next;
5029 simple_estate_stack = NULL;
5033 * plpgsql_subxact_cb --- post-subtransaction-commit-or-abort cleanup
5035 * If a simple-expression EState was created in the current subtransaction,
5036 * it has to be cleaned up.
5039 plpgsql_subxact_cb(SubXactEvent event, SubTransactionId mySubid,
5040 SubTransactionId parentSubid, void *arg)
5042 if (event == SUBXACT_EVENT_START_SUB)
5045 if (simple_estate_stack != NULL &&
5046 simple_estate_stack->xact_subxid == mySubid)
5048 SimpleEstateStackEntry *next;
5050 if (event == SUBXACT_EVENT_COMMIT_SUB)
5051 FreeExecutorState(simple_estate_stack->xact_eval_estate);
5052 next = simple_estate_stack->next;
5053 pfree(simple_estate_stack);
5054 simple_estate_stack = next;
5059 * free_var --- pfree any pass-by-reference value of the variable.
5061 * This should always be followed by some assignment to var->value,
5062 * as it leaves a dangling pointer.
5065 free_var(PLpgSQL_var *var)
5069 pfree(DatumGetPointer(var->value));
5070 var->freeval = false;