1 /*-------------------------------------------------------------------------
3 * pl_exec.c - Executor for the PL/pgSQL
6 * Portions Copyright (c) 1996-2008, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $PostgreSQL: pgsql/src/pl/plpgsql/src/pl_exec.c,v 1.207 2008/03/28 00:21:56 tgl 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/snapmgr.h"
36 #include "utils/typcache.h"
39 static const char *const raise_skip_msg = "RAISE";
42 * All plpgsql function executions within a single transaction share the same
43 * executor EState for evaluating "simple" expressions. Each function call
44 * creates its own "eval_econtext" ExprContext within this estate for
45 * per-evaluation workspace. eval_econtext is freed at normal function exit,
46 * and the EState is freed at transaction end (in case of error, we assume
47 * that the abort mechanisms clean it all up). In order to be sure
48 * ExprContext callbacks are handled properly, each subtransaction has to have
49 * its own such EState; hence we need a stack. We use a simple counter to
50 * distinguish different instantiations of the EState, so that we can tell
51 * whether we have a current copy of a prepared expression.
53 * This arrangement is a bit tedious to maintain, but it's worth the trouble
54 * so that we don't have to re-prepare simple expressions on each trip through
55 * a function. (We assume the case to optimize is many repetitions of a
56 * function within a transaction.)
58 typedef struct SimpleEstateStackEntry
60 EState *xact_eval_estate; /* EState for current xact level */
61 long int xact_estate_simple_id; /* ID for xact_eval_estate */
62 SubTransactionId xact_subxid; /* ID for current subxact */
63 struct SimpleEstateStackEntry *next; /* next stack entry up */
64 } SimpleEstateStackEntry;
66 static SimpleEstateStackEntry *simple_estate_stack = NULL;
67 static long int simple_estate_id_counter = 0;
69 /************************************************************
70 * Local function forward declarations
71 ************************************************************/
72 static void plpgsql_exec_error_callback(void *arg);
73 static PLpgSQL_datum *copy_plpgsql_datum(PLpgSQL_datum *datum);
75 static int exec_stmt_block(PLpgSQL_execstate *estate,
76 PLpgSQL_stmt_block *block);
77 static int exec_stmts(PLpgSQL_execstate *estate,
79 static int exec_stmt(PLpgSQL_execstate *estate,
81 static int exec_stmt_assign(PLpgSQL_execstate *estate,
82 PLpgSQL_stmt_assign *stmt);
83 static int exec_stmt_perform(PLpgSQL_execstate *estate,
84 PLpgSQL_stmt_perform *stmt);
85 static int exec_stmt_getdiag(PLpgSQL_execstate *estate,
86 PLpgSQL_stmt_getdiag *stmt);
87 static int exec_stmt_if(PLpgSQL_execstate *estate,
88 PLpgSQL_stmt_if *stmt);
89 static int exec_stmt_loop(PLpgSQL_execstate *estate,
90 PLpgSQL_stmt_loop *stmt);
91 static int exec_stmt_while(PLpgSQL_execstate *estate,
92 PLpgSQL_stmt_while *stmt);
93 static int exec_stmt_fori(PLpgSQL_execstate *estate,
94 PLpgSQL_stmt_fori *stmt);
95 static int exec_stmt_fors(PLpgSQL_execstate *estate,
96 PLpgSQL_stmt_fors *stmt);
97 static int exec_stmt_open(PLpgSQL_execstate *estate,
98 PLpgSQL_stmt_open *stmt);
99 static int exec_stmt_fetch(PLpgSQL_execstate *estate,
100 PLpgSQL_stmt_fetch *stmt);
101 static int exec_stmt_close(PLpgSQL_execstate *estate,
102 PLpgSQL_stmt_close *stmt);
103 static int exec_stmt_exit(PLpgSQL_execstate *estate,
104 PLpgSQL_stmt_exit *stmt);
105 static int exec_stmt_return(PLpgSQL_execstate *estate,
106 PLpgSQL_stmt_return *stmt);
107 static int exec_stmt_return_next(PLpgSQL_execstate *estate,
108 PLpgSQL_stmt_return_next *stmt);
109 static int exec_stmt_return_query(PLpgSQL_execstate *estate,
110 PLpgSQL_stmt_return_query *stmt);
111 static int exec_stmt_raise(PLpgSQL_execstate *estate,
112 PLpgSQL_stmt_raise *stmt);
113 static int exec_stmt_execsql(PLpgSQL_execstate *estate,
114 PLpgSQL_stmt_execsql *stmt);
115 static int exec_stmt_dynexecute(PLpgSQL_execstate *estate,
116 PLpgSQL_stmt_dynexecute *stmt);
117 static int exec_stmt_dynfors(PLpgSQL_execstate *estate,
118 PLpgSQL_stmt_dynfors *stmt);
120 static void plpgsql_estate_setup(PLpgSQL_execstate *estate,
121 PLpgSQL_function *func,
123 static void exec_eval_cleanup(PLpgSQL_execstate *estate);
125 static void exec_prepare_plan(PLpgSQL_execstate *estate,
126 PLpgSQL_expr *expr, int cursorOptions);
127 static bool exec_simple_check_node(Node *node);
128 static void exec_simple_check_plan(PLpgSQL_expr *expr);
129 static bool exec_eval_simple_expr(PLpgSQL_execstate *estate,
135 static void exec_assign_expr(PLpgSQL_execstate *estate,
136 PLpgSQL_datum *target,
138 static void exec_assign_value(PLpgSQL_execstate *estate,
139 PLpgSQL_datum *target,
140 Datum value, Oid valtype, bool *isNull);
141 static void exec_eval_datum(PLpgSQL_execstate *estate,
142 PLpgSQL_datum *datum,
147 static int exec_eval_integer(PLpgSQL_execstate *estate,
150 static bool exec_eval_boolean(PLpgSQL_execstate *estate,
153 static Datum exec_eval_expr(PLpgSQL_execstate *estate,
157 static int exec_run_select(PLpgSQL_execstate *estate,
158 PLpgSQL_expr *expr, long maxtuples, Portal *portalP);
159 static void exec_move_row(PLpgSQL_execstate *estate,
162 HeapTuple tup, TupleDesc tupdesc);
163 static HeapTuple make_tuple_from_row(PLpgSQL_execstate *estate,
166 static char *convert_value_to_string(Datum value, Oid valtype);
167 static Datum exec_cast_value(Datum value, Oid valtype,
173 static Datum exec_simple_cast_value(Datum value, Oid valtype,
174 Oid reqtype, int32 reqtypmod,
176 static void exec_init_tuple_store(PLpgSQL_execstate *estate);
177 static bool compatible_tupdesc(TupleDesc td1, TupleDesc td2);
178 static void exec_set_found(PLpgSQL_execstate *estate, bool state);
179 static void plpgsql_create_econtext(PLpgSQL_execstate *estate);
180 static void free_var(PLpgSQL_var *var);
184 * plpgsql_exec_function Called by the call handler for
185 * function execution.
189 plpgsql_exec_function(PLpgSQL_function *func, FunctionCallInfo fcinfo)
191 PLpgSQL_execstate estate;
192 ErrorContextCallback plerrcontext;
197 * Setup the execution state
199 plpgsql_estate_setup(&estate, func, (ReturnSetInfo *) fcinfo->resultinfo);
202 * Setup error traceback support for ereport()
204 plerrcontext.callback = plpgsql_exec_error_callback;
205 plerrcontext.arg = &estate;
206 plerrcontext.previous = error_context_stack;
207 error_context_stack = &plerrcontext;
210 * Make local execution copies of all the datums
212 estate.err_text = gettext_noop("during initialization of execution state");
213 for (i = 0; i < estate.ndatums; i++)
214 estate.datums[i] = copy_plpgsql_datum(func->datums[i]);
217 * Store the actual call argument values into the appropriate variables
219 estate.err_text = gettext_noop("while storing call arguments into local variables");
220 for (i = 0; i < func->fn_nargs; i++)
222 int n = func->fn_argvarnos[i];
224 switch (estate.datums[n]->dtype)
226 case PLPGSQL_DTYPE_VAR:
228 PLpgSQL_var *var = (PLpgSQL_var *) estate.datums[n];
230 var->value = fcinfo->arg[i];
231 var->isnull = fcinfo->argnull[i];
232 var->freeval = false;
236 case PLPGSQL_DTYPE_ROW:
238 PLpgSQL_row *row = (PLpgSQL_row *) estate.datums[n];
240 if (!fcinfo->argnull[i])
246 HeapTupleData tmptup;
248 td = DatumGetHeapTupleHeader(fcinfo->arg[i]);
249 /* Extract rowtype info and find a tupdesc */
250 tupType = HeapTupleHeaderGetTypeId(td);
251 tupTypmod = HeapTupleHeaderGetTypMod(td);
252 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
253 /* Build a temporary HeapTuple control structure */
254 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
255 ItemPointerSetInvalid(&(tmptup.t_self));
256 tmptup.t_tableOid = InvalidOid;
258 exec_move_row(&estate, NULL, row, &tmptup, tupdesc);
259 ReleaseTupleDesc(tupdesc);
263 /* If arg is null, treat it as an empty row */
264 exec_move_row(&estate, NULL, row, NULL, NULL);
270 elog(ERROR, "unrecognized dtype: %d", func->datums[i]->dtype);
274 estate.err_text = gettext_noop("during function entry");
277 * Set the magic variable FOUND to false
279 exec_set_found(&estate, false);
282 * Let the instrumentation plugin peek at this function
284 if (*plugin_ptr && (*plugin_ptr)->func_beg)
285 ((*plugin_ptr)->func_beg) (&estate, func);
288 * Now call the toplevel block of statements
290 estate.err_text = NULL;
291 estate.err_stmt = (PLpgSQL_stmt *) (func->action);
292 rc = exec_stmt_block(&estate, func->action);
293 if (rc != PLPGSQL_RC_RETURN)
295 estate.err_stmt = NULL;
296 estate.err_text = NULL;
299 * Provide a more helpful message if a CONTINUE has been used outside
302 if (rc == PLPGSQL_RC_CONTINUE)
304 (errcode(ERRCODE_SYNTAX_ERROR),
305 errmsg("CONTINUE cannot be used outside a loop")));
308 (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
309 errmsg("control reached end of function without RETURN")));
313 * We got a return value - process it
315 estate.err_stmt = NULL;
316 estate.err_text = gettext_noop("while casting return value to function's return type");
318 fcinfo->isnull = estate.retisnull;
322 ReturnSetInfo *rsi = estate.rsi;
324 /* Check caller can handle a set result */
325 if (!rsi || !IsA(rsi, ReturnSetInfo) ||
326 (rsi->allowedModes & SFRM_Materialize) == 0)
328 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
329 errmsg("set-valued function called in context that cannot accept a set")));
330 rsi->returnMode = SFRM_Materialize;
332 /* If we produced any tuples, send back the result */
333 if (estate.tuple_store)
335 rsi->setResult = estate.tuple_store;
336 if (estate.rettupdesc)
338 MemoryContext oldcxt;
340 oldcxt = MemoryContextSwitchTo(estate.tuple_store_cxt);
341 rsi->setDesc = CreateTupleDescCopy(estate.rettupdesc);
342 MemoryContextSwitchTo(oldcxt);
345 estate.retval = (Datum) 0;
346 fcinfo->isnull = true;
348 else if (!estate.retisnull)
350 if (estate.retistuple)
353 * We have to check that the returned tuple actually matches the
354 * expected result type. XXX would be better to cache the tupdesc
355 * instead of repeating get_call_result_type()
359 switch (get_call_result_type(fcinfo, NULL, &tupdesc))
361 case TYPEFUNC_COMPOSITE:
362 /* got the expected result rowtype, now check it */
363 if (estate.rettupdesc == NULL ||
364 !compatible_tupdesc(estate.rettupdesc, tupdesc))
366 (errcode(ERRCODE_DATATYPE_MISMATCH),
367 errmsg("returned record type does not match expected record type")));
369 case TYPEFUNC_RECORD:
372 * Failed to determine actual type of RECORD. We could
373 * raise an error here, but what this means in practice is
374 * that the caller is expecting any old generic rowtype,
375 * so we don't really need to be restrictive. Pass back
376 * the generated result type, instead.
378 tupdesc = estate.rettupdesc;
379 if (tupdesc == NULL) /* shouldn't happen */
380 elog(ERROR, "return type must be a row type");
383 /* shouldn't get here if retistuple is true ... */
384 elog(ERROR, "return type must be a row type");
389 * Copy tuple to upper executor memory, as a tuple Datum. Make
390 * sure it is labeled with the caller-supplied tuple type.
393 PointerGetDatum(SPI_returntuple((HeapTuple) (estate.retval),
398 /* Cast value to proper type */
399 estate.retval = exec_cast_value(estate.retval, estate.rettype,
401 &(func->fn_retinput),
402 func->fn_rettypioparam,
407 * If the function's return type isn't by value, copy the value
408 * into upper executor memory context.
410 if (!fcinfo->isnull && !func->fn_retbyval)
415 len = datumGetSize(estate.retval, false, func->fn_rettyplen);
416 tmp = SPI_palloc(len);
417 memcpy(tmp, DatumGetPointer(estate.retval), len);
418 estate.retval = PointerGetDatum(tmp);
423 estate.err_text = gettext_noop("during function exit");
426 * Let the instrumentation plugin peek at this function
428 if (*plugin_ptr && (*plugin_ptr)->func_end)
429 ((*plugin_ptr)->func_end) (&estate, func);
431 /* Clean up any leftover temporary memory */
432 FreeExprContext(estate.eval_econtext);
433 estate.eval_econtext = NULL;
434 exec_eval_cleanup(&estate);
437 * Pop the error context stack
439 error_context_stack = plerrcontext.previous;
442 * Return the function's result
444 return estate.retval;
449 * plpgsql_exec_trigger Called by the call handler for
454 plpgsql_exec_trigger(PLpgSQL_function *func,
455 TriggerData *trigdata)
457 PLpgSQL_execstate estate;
458 ErrorContextCallback plerrcontext;
462 PLpgSQL_rec *rec_new,
467 * Setup the execution state
469 plpgsql_estate_setup(&estate, func, NULL);
472 * Setup error traceback support for ereport()
474 plerrcontext.callback = plpgsql_exec_error_callback;
475 plerrcontext.arg = &estate;
476 plerrcontext.previous = error_context_stack;
477 error_context_stack = &plerrcontext;
480 * Make local execution copies of all the datums
482 estate.err_text = gettext_noop("during initialization of execution state");
483 for (i = 0; i < estate.ndatums; i++)
484 estate.datums[i] = copy_plpgsql_datum(func->datums[i]);
487 * Put the OLD and NEW tuples into record variables
489 rec_new = (PLpgSQL_rec *) (estate.datums[func->new_varno]);
490 rec_new->freetup = false;
491 rec_new->freetupdesc = false;
492 rec_old = (PLpgSQL_rec *) (estate.datums[func->old_varno]);
493 rec_old->freetup = false;
494 rec_old->freetupdesc = false;
496 if (TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
499 * Per-statement triggers don't use OLD/NEW variables
502 rec_new->tupdesc = NULL;
504 rec_old->tupdesc = NULL;
506 else if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
508 rec_new->tup = trigdata->tg_trigtuple;
509 rec_new->tupdesc = trigdata->tg_relation->rd_att;
511 rec_old->tupdesc = NULL;
513 else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
515 rec_new->tup = trigdata->tg_newtuple;
516 rec_new->tupdesc = trigdata->tg_relation->rd_att;
517 rec_old->tup = trigdata->tg_trigtuple;
518 rec_old->tupdesc = trigdata->tg_relation->rd_att;
520 else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
523 rec_new->tupdesc = NULL;
524 rec_old->tup = trigdata->tg_trigtuple;
525 rec_old->tupdesc = trigdata->tg_relation->rd_att;
528 elog(ERROR, "unrecognized trigger action: not INSERT, DELETE, or UPDATE");
531 * Assign the special tg_ variables
534 var = (PLpgSQL_var *) (estate.datums[func->tg_op_varno]);
535 if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
536 var->value = CStringGetTextDatum("INSERT");
537 else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
538 var->value = CStringGetTextDatum("UPDATE");
539 else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
540 var->value = CStringGetTextDatum("DELETE");
541 else if (TRIGGER_FIRED_BY_TRUNCATE(trigdata->tg_event))
542 var->value = CStringGetTextDatum("TRUNCATE");
544 elog(ERROR, "unrecognized trigger action: not INSERT, DELETE, UPDATE, or TRUNCATE");
548 var = (PLpgSQL_var *) (estate.datums[func->tg_name_varno]);
549 var->value = DirectFunctionCall1(namein,
550 CStringGetDatum(trigdata->tg_trigger->tgname));
554 var = (PLpgSQL_var *) (estate.datums[func->tg_when_varno]);
555 if (TRIGGER_FIRED_BEFORE(trigdata->tg_event))
556 var->value = CStringGetTextDatum("BEFORE");
557 else if (TRIGGER_FIRED_AFTER(trigdata->tg_event))
558 var->value = CStringGetTextDatum("AFTER");
560 elog(ERROR, "unrecognized trigger execution time: not BEFORE or AFTER");
564 var = (PLpgSQL_var *) (estate.datums[func->tg_level_varno]);
565 if (TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
566 var->value = CStringGetTextDatum("ROW");
567 else if (TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
568 var->value = CStringGetTextDatum("STATEMENT");
570 elog(ERROR, "unrecognized trigger event type: not ROW or STATEMENT");
574 var = (PLpgSQL_var *) (estate.datums[func->tg_relid_varno]);
575 var->value = ObjectIdGetDatum(trigdata->tg_relation->rd_id);
577 var->freeval = false;
579 var = (PLpgSQL_var *) (estate.datums[func->tg_relname_varno]);
580 var->value = DirectFunctionCall1(namein,
581 CStringGetDatum(RelationGetRelationName(trigdata->tg_relation)));
585 var = (PLpgSQL_var *) (estate.datums[func->tg_table_name_varno]);
586 var->value = DirectFunctionCall1(namein,
587 CStringGetDatum(RelationGetRelationName(trigdata->tg_relation)));
591 var = (PLpgSQL_var *) (estate.datums[func->tg_table_schema_varno]);
592 var->value = DirectFunctionCall1(namein,
595 RelationGetNamespace(
596 trigdata->tg_relation))));
600 var = (PLpgSQL_var *) (estate.datums[func->tg_nargs_varno]);
601 var->value = Int16GetDatum(trigdata->tg_trigger->tgnargs);
603 var->freeval = false;
606 * Store the trigger argument values into the special execution state
609 estate.err_text = gettext_noop("while storing call arguments into local variables");
610 estate.trig_nargs = trigdata->tg_trigger->tgnargs;
611 if (estate.trig_nargs == 0)
612 estate.trig_argv = NULL;
615 estate.trig_argv = palloc(sizeof(Datum) * estate.trig_nargs);
616 for (i = 0; i < trigdata->tg_trigger->tgnargs; i++)
617 estate.trig_argv[i] = CStringGetTextDatum(trigdata->tg_trigger->tgargs[i]);
620 estate.err_text = gettext_noop("during function entry");
623 * Set the magic variable FOUND to false
625 exec_set_found(&estate, false);
628 * Let the instrumentation plugin peek at this function
630 if (*plugin_ptr && (*plugin_ptr)->func_beg)
631 ((*plugin_ptr)->func_beg) (&estate, func);
634 * Now call the toplevel block of statements
636 estate.err_text = NULL;
637 estate.err_stmt = (PLpgSQL_stmt *) (func->action);
638 rc = exec_stmt_block(&estate, func->action);
639 if (rc != PLPGSQL_RC_RETURN)
641 estate.err_stmt = NULL;
642 estate.err_text = NULL;
645 * Provide a more helpful message if a CONTINUE has been used outside
648 if (rc == PLPGSQL_RC_CONTINUE)
650 (errcode(ERRCODE_SYNTAX_ERROR),
651 errmsg("CONTINUE cannot be used outside a loop")));
654 (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
655 errmsg("control reached end of trigger procedure without RETURN")));
658 estate.err_stmt = NULL;
659 estate.err_text = gettext_noop("during function exit");
663 (errcode(ERRCODE_DATATYPE_MISMATCH),
664 errmsg("trigger procedure cannot return a set")));
667 * Check that the returned tuple structure has the same attributes, the
668 * relation that fired the trigger has. A per-statement trigger always
669 * needs to return NULL, so we ignore any return value the function itself
670 * produces (XXX: is this a good idea?)
672 * XXX This way it is possible, that the trigger returns a tuple where
673 * attributes don't have the correct atttypmod's length. It's up to the
674 * trigger's programmer to ensure that this doesn't happen. Jan
676 if (estate.retisnull || TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
680 if (!compatible_tupdesc(estate.rettupdesc,
681 trigdata->tg_relation->rd_att))
683 (errcode(ERRCODE_DATATYPE_MISMATCH),
684 errmsg("returned tuple structure does not match table of trigger event")));
685 /* Copy tuple to upper executor memory */
686 rettup = SPI_copytuple((HeapTuple) (estate.retval));
690 * Let the instrumentation plugin peek at this function
692 if (*plugin_ptr && (*plugin_ptr)->func_end)
693 ((*plugin_ptr)->func_end) (&estate, func);
695 /* Clean up any leftover temporary memory */
696 FreeExprContext(estate.eval_econtext);
697 estate.eval_econtext = NULL;
698 exec_eval_cleanup(&estate);
701 * Pop the error context stack
703 error_context_stack = plerrcontext.previous;
706 * Return the trigger's result
713 * error context callback to let us supply a call-stack traceback
716 plpgsql_exec_error_callback(void *arg)
718 PLpgSQL_execstate *estate = (PLpgSQL_execstate *) arg;
720 /* safety check, shouldn't happen */
721 if (estate->err_func == NULL)
724 /* if we are doing RAISE, don't report its location */
725 if (estate->err_text == raise_skip_msg)
728 if (estate->err_text != NULL)
731 * We don't expend the cycles to run gettext() on err_text unless we
732 * actually need it. Therefore, places that set up err_text should
733 * use gettext_noop() to ensure the strings get recorded in the
734 * message dictionary.
736 * If both err_text and err_stmt are set, use the err_text as
737 * description, but report the err_stmt's line number. When err_stmt
738 * is not set, we're in function entry/exit, or some such place not
739 * attached to a specific line number.
741 if (estate->err_stmt != NULL)
744 * translator: last %s is a phrase such as "during statement block
745 * local variable initialization"
747 errcontext("PL/pgSQL function \"%s\" line %d %s",
748 estate->err_func->fn_name,
749 estate->err_stmt->lineno,
750 gettext(estate->err_text));
755 * translator: last %s is a phrase such as "while storing call
756 * arguments into local variables"
758 errcontext("PL/pgSQL function \"%s\" %s",
759 estate->err_func->fn_name,
760 gettext(estate->err_text));
763 else if (estate->err_stmt != NULL)
765 /* translator: last %s is a plpgsql statement type name */
766 errcontext("PL/pgSQL function \"%s\" line %d at %s",
767 estate->err_func->fn_name,
768 estate->err_stmt->lineno,
769 plpgsql_stmt_typename(estate->err_stmt));
772 errcontext("PL/pgSQL function \"%s\"",
773 estate->err_func->fn_name);
778 * Support function for initializing local execution variables
781 static PLpgSQL_datum *
782 copy_plpgsql_datum(PLpgSQL_datum *datum)
784 PLpgSQL_datum *result;
786 switch (datum->dtype)
788 case PLPGSQL_DTYPE_VAR:
790 PLpgSQL_var *new = palloc(sizeof(PLpgSQL_var));
792 memcpy(new, datum, sizeof(PLpgSQL_var));
793 /* Ensure the value is null (possibly not needed?) */
796 new->freeval = false;
798 result = (PLpgSQL_datum *) new;
802 case PLPGSQL_DTYPE_REC:
804 PLpgSQL_rec *new = palloc(sizeof(PLpgSQL_rec));
806 memcpy(new, datum, sizeof(PLpgSQL_rec));
807 /* Ensure the value is null (possibly not needed?) */
810 new->freetup = false;
811 new->freetupdesc = false;
813 result = (PLpgSQL_datum *) new;
817 case PLPGSQL_DTYPE_ROW:
818 case PLPGSQL_DTYPE_RECFIELD:
819 case PLPGSQL_DTYPE_ARRAYELEM:
820 case PLPGSQL_DTYPE_TRIGARG:
823 * These datum records are read-only at runtime, so no need to
830 elog(ERROR, "unrecognized dtype: %d", datum->dtype);
831 result = NULL; /* keep compiler quiet */
840 exception_matches_conditions(ErrorData *edata, PLpgSQL_condition *cond)
842 for (; cond != NULL; cond = cond->next)
844 int sqlerrstate = cond->sqlerrstate;
847 * OTHERS matches everything *except* query-canceled; if you're
848 * foolish enough, you can match that explicitly.
850 if (sqlerrstate == 0)
852 if (edata->sqlerrcode != ERRCODE_QUERY_CANCELED)
856 else if (edata->sqlerrcode == sqlerrstate)
858 /* Category match? */
859 else if (ERRCODE_IS_CATEGORY(sqlerrstate) &&
860 ERRCODE_TO_CATEGORY(edata->sqlerrcode) == sqlerrstate)
868 * exec_stmt_block Execute a block of statements
872 exec_stmt_block(PLpgSQL_execstate *estate, PLpgSQL_stmt_block *block)
874 volatile int rc = -1;
879 * First initialize all variables declared in this block
881 estate->err_text = gettext_noop("during statement block local variable initialization");
883 for (i = 0; i < block->n_initvars; i++)
885 n = block->initvarnos[i];
887 switch (estate->datums[n]->dtype)
889 case PLPGSQL_DTYPE_VAR:
891 PLpgSQL_var *var = (PLpgSQL_var *) (estate->datums[n]);
893 /* free any old value, in case re-entering block */
896 /* Initially it contains a NULL */
897 var->value = (Datum) 0;
900 if (var->default_val == NULL)
903 * If needed, give the datatype a chance to reject
904 * NULLs, by assigning a NULL to the variable. We
905 * claim the value is of type UNKNOWN, not the var's
906 * datatype, else coercion will be skipped. (Do this
907 * before the notnull check to be consistent with
908 * exec_assign_value.)
910 if (!var->datatype->typinput.fn_strict)
912 bool valIsNull = true;
914 exec_assign_value(estate,
915 (PLpgSQL_datum *) var,
922 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
923 errmsg("variable \"%s\" declared NOT NULL cannot default to NULL",
928 exec_assign_expr(estate, (PLpgSQL_datum *) var,
934 case PLPGSQL_DTYPE_REC:
936 PLpgSQL_rec *rec = (PLpgSQL_rec *) (estate->datums[n]);
940 heap_freetuple(rec->tup);
941 FreeTupleDesc(rec->tupdesc);
942 rec->freetup = false;
950 case PLPGSQL_DTYPE_RECFIELD:
951 case PLPGSQL_DTYPE_ARRAYELEM:
955 elog(ERROR, "unrecognized dtype: %d",
956 estate->datums[n]->dtype);
960 if (block->exceptions)
963 * Execute the statements in the block's body inside a sub-transaction
965 MemoryContext oldcontext = CurrentMemoryContext;
966 ResourceOwner oldowner = CurrentResourceOwner;
967 ExprContext *old_eval_econtext = estate->eval_econtext;
968 EState *old_eval_estate = estate->eval_estate;
969 long int old_eval_estate_simple_id = estate->eval_estate_simple_id;
971 estate->err_text = gettext_noop("during statement block entry");
973 BeginInternalSubTransaction(NULL);
974 /* Want to run statements inside function's memory context */
975 MemoryContextSwitchTo(oldcontext);
980 * We need to run the block's statements with a new eval_econtext
981 * that belongs to the current subtransaction; if we try to use
982 * the outer econtext then ExprContext shutdown callbacks will be
983 * called at the wrong times.
985 plpgsql_create_econtext(estate);
987 estate->err_text = NULL;
989 /* Run the block's statements */
990 rc = exec_stmts(estate, block->body);
992 estate->err_text = gettext_noop("during statement block exit");
995 * If the block ended with RETURN, we may need to copy the return
996 * value out of the subtransaction eval_context. This is
997 * currently only needed for scalar result types --- rowtype
998 * values will always exist in the function's own memory context.
1000 if (rc == PLPGSQL_RC_RETURN &&
1001 !estate->retisset &&
1002 !estate->retisnull &&
1003 estate->rettupdesc == NULL)
1008 get_typlenbyval(estate->rettype, &resTypLen, &resTypByVal);
1009 estate->retval = datumCopy(estate->retval,
1010 resTypByVal, resTypLen);
1013 /* Commit the inner transaction, return to outer xact context */
1014 ReleaseCurrentSubTransaction();
1015 MemoryContextSwitchTo(oldcontext);
1016 CurrentResourceOwner = oldowner;
1018 /* Revert to outer eval_econtext */
1019 estate->eval_econtext = old_eval_econtext;
1020 estate->eval_estate = old_eval_estate;
1021 estate->eval_estate_simple_id = old_eval_estate_simple_id;
1024 * AtEOSubXact_SPI() should not have popped any SPI context, but
1025 * just in case it did, make sure we remain connected.
1027 SPI_restore_connection();
1034 estate->err_text = gettext_noop("during exception cleanup");
1036 /* Save error info */
1037 MemoryContextSwitchTo(oldcontext);
1038 edata = CopyErrorData();
1041 /* Abort the inner transaction */
1042 RollbackAndReleaseCurrentSubTransaction();
1043 MemoryContextSwitchTo(oldcontext);
1044 CurrentResourceOwner = oldowner;
1046 /* Revert to outer eval_econtext */
1047 estate->eval_econtext = old_eval_econtext;
1048 estate->eval_estate = old_eval_estate;
1049 estate->eval_estate_simple_id = old_eval_estate_simple_id;
1052 * If AtEOSubXact_SPI() popped any SPI context of the subxact, it
1053 * will have left us in a disconnected state. We need this hack
1054 * to return to connected state.
1056 SPI_restore_connection();
1058 /* Look for a matching exception handler */
1059 foreach(e, block->exceptions->exc_list)
1061 PLpgSQL_exception *exception = (PLpgSQL_exception *) lfirst(e);
1063 if (exception_matches_conditions(edata, exception->conditions))
1066 * Initialize the magic SQLSTATE and SQLERRM variables for
1067 * the exception block. We needn't do this until we have
1068 * found a matching exception.
1070 PLpgSQL_var *state_var;
1071 PLpgSQL_var *errm_var;
1073 state_var = (PLpgSQL_var *)
1074 estate->datums[block->exceptions->sqlstate_varno];
1075 state_var->value = CStringGetTextDatum(unpack_sql_state(edata->sqlerrcode));
1076 state_var->freeval = true;
1077 state_var->isnull = false;
1079 errm_var = (PLpgSQL_var *)
1080 estate->datums[block->exceptions->sqlerrm_varno];
1081 errm_var->value = CStringGetTextDatum(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)
2012 MemoryContext oldcxt;
2013 HeapTuple tuple = NULL;
2014 bool free_tuple = false;
2016 if (!estate->retisset)
2018 (errcode(ERRCODE_SYNTAX_ERROR),
2019 errmsg("cannot use RETURN NEXT in a non-SETOF function")));
2021 if (estate->tuple_store == NULL)
2022 exec_init_tuple_store(estate);
2024 /* rettupdesc will be filled by exec_init_tuple_store */
2025 tupdesc = estate->rettupdesc;
2026 natts = tupdesc->natts;
2028 if (stmt->retvarno >= 0)
2030 PLpgSQL_datum *retvar = estate->datums[stmt->retvarno];
2032 switch (retvar->dtype)
2034 case PLPGSQL_DTYPE_VAR:
2036 PLpgSQL_var *var = (PLpgSQL_var *) retvar;
2037 Datum retval = var->value;
2038 bool isNull = var->isnull;
2042 (errcode(ERRCODE_DATATYPE_MISMATCH),
2043 errmsg("wrong result type supplied in RETURN NEXT")));
2045 /* coerce type if needed */
2046 retval = exec_simple_cast_value(retval,
2047 var->datatype->typoid,
2048 tupdesc->attrs[0]->atttypid,
2049 tupdesc->attrs[0]->atttypmod,
2052 oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
2053 tuplestore_putvalues(estate->tuple_store, tupdesc,
2055 MemoryContextSwitchTo(oldcxt);
2059 case PLPGSQL_DTYPE_REC:
2061 PLpgSQL_rec *rec = (PLpgSQL_rec *) retvar;
2063 if (!HeapTupleIsValid(rec->tup))
2065 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2066 errmsg("record \"%s\" is not assigned yet",
2068 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
2069 if (!compatible_tupdesc(tupdesc, rec->tupdesc))
2071 (errcode(ERRCODE_DATATYPE_MISMATCH),
2072 errmsg("wrong record type supplied in RETURN NEXT")));
2077 case PLPGSQL_DTYPE_ROW:
2079 PLpgSQL_row *row = (PLpgSQL_row *) retvar;
2081 tuple = make_tuple_from_row(estate, row, tupdesc);
2084 (errcode(ERRCODE_DATATYPE_MISMATCH),
2085 errmsg("wrong record type supplied in RETURN NEXT")));
2091 elog(ERROR, "unrecognized dtype: %d", retvar->dtype);
2095 else if (stmt->expr)
2103 (errcode(ERRCODE_DATATYPE_MISMATCH),
2104 errmsg("wrong result type supplied in RETURN NEXT")));
2106 retval = exec_eval_expr(estate,
2111 /* coerce type if needed */
2112 retval = exec_simple_cast_value(retval,
2114 tupdesc->attrs[0]->atttypid,
2115 tupdesc->attrs[0]->atttypmod,
2118 oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
2119 tuplestore_putvalues(estate->tuple_store, tupdesc,
2121 MemoryContextSwitchTo(oldcxt);
2123 exec_eval_cleanup(estate);
2128 (errcode(ERRCODE_SYNTAX_ERROR),
2129 errmsg("RETURN NEXT must have a parameter")));
2132 if (HeapTupleIsValid(tuple))
2134 oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
2135 tuplestore_puttuple(estate->tuple_store, tuple);
2136 MemoryContextSwitchTo(oldcxt);
2139 heap_freetuple(tuple);
2142 return PLPGSQL_RC_OK;
2146 * exec_stmt_return_query Evaluate a query and add it to the
2147 * list of tuples returned by the current
2152 exec_stmt_return_query(PLpgSQL_execstate *estate,
2153 PLpgSQL_stmt_return_query *stmt)
2157 if (!estate->retisset)
2159 (errcode(ERRCODE_SYNTAX_ERROR),
2160 errmsg("cannot use RETURN QUERY in a non-SETOF function")));
2162 if (estate->tuple_store == NULL)
2163 exec_init_tuple_store(estate);
2165 exec_run_select(estate, stmt->query, 0, &portal);
2167 if (!compatible_tupdesc(estate->rettupdesc, portal->tupDesc))
2169 (errcode(ERRCODE_DATATYPE_MISMATCH),
2170 errmsg("structure of query does not match function result type")));
2174 MemoryContext old_cxt;
2177 SPI_cursor_fetch(portal, true, 50);
2178 if (SPI_processed == 0)
2181 old_cxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
2182 for (i = 0; i < SPI_processed; i++)
2184 HeapTuple tuple = SPI_tuptable->vals[i];
2186 tuplestore_puttuple(estate->tuple_store, tuple);
2188 MemoryContextSwitchTo(old_cxt);
2190 SPI_freetuptable(SPI_tuptable);
2193 SPI_freetuptable(SPI_tuptable);
2194 SPI_cursor_close(portal);
2196 return PLPGSQL_RC_OK;
2200 exec_init_tuple_store(PLpgSQL_execstate *estate)
2202 ReturnSetInfo *rsi = estate->rsi;
2203 MemoryContext oldcxt;
2206 * Check caller can handle a set result in the way we want
2208 if (!rsi || !IsA(rsi, ReturnSetInfo) ||
2209 (rsi->allowedModes & SFRM_Materialize) == 0 ||
2210 rsi->expectedDesc == NULL)
2212 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2213 errmsg("set-valued function called in context that cannot accept a set")));
2215 estate->tuple_store_cxt = rsi->econtext->ecxt_per_query_memory;
2217 oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
2218 estate->tuple_store = tuplestore_begin_heap(true, false, work_mem);
2219 MemoryContextSwitchTo(oldcxt);
2221 estate->rettupdesc = rsi->expectedDesc;
2225 * exec_stmt_raise Build a message and throw it with elog()
2229 exec_stmt_raise(PLpgSQL_execstate *estate, PLpgSQL_stmt_raise *stmt)
2233 ListCell *current_param;
2235 plpgsql_dstring_init(&ds);
2236 current_param = list_head(stmt->params);
2238 for (cp = stmt->message; *cp; cp++)
2241 * Occurrences of a single % are replaced by the next parameter's
2242 * external representation. Double %'s are converted to one %.
2253 plpgsql_dstring_append_char(&ds, cp[1]);
2258 if (current_param == NULL)
2260 (errcode(ERRCODE_SYNTAX_ERROR),
2261 errmsg("too few parameters specified for RAISE")));
2263 paramvalue = exec_eval_expr(estate,
2264 (PLpgSQL_expr *) lfirst(current_param),
2271 extval = convert_value_to_string(paramvalue, paramtypeid);
2272 plpgsql_dstring_append(&ds, extval);
2273 current_param = lnext(current_param);
2274 exec_eval_cleanup(estate);
2278 plpgsql_dstring_append_char(&ds, cp[0]);
2282 * If more parameters were specified than were required to process the
2283 * format string, throw an error
2285 if (current_param != NULL)
2287 (errcode(ERRCODE_SYNTAX_ERROR),
2288 errmsg("too many parameters specified for RAISE")));
2291 * Throw the error (may or may not come back)
2293 estate->err_text = raise_skip_msg; /* suppress traceback of raise */
2295 ereport(stmt->elog_level,
2296 ((stmt->elog_level >= ERROR) ? errcode(ERRCODE_RAISE_EXCEPTION) : 0,
2297 errmsg_internal("%s", plpgsql_dstring_get(&ds))));
2299 estate->err_text = NULL; /* un-suppress... */
2301 plpgsql_dstring_free(&ds);
2303 return PLPGSQL_RC_OK;
2308 * Initialize a mostly empty execution state
2312 plpgsql_estate_setup(PLpgSQL_execstate *estate,
2313 PLpgSQL_function *func,
2316 estate->retval = (Datum) 0;
2317 estate->retisnull = true;
2318 estate->rettype = InvalidOid;
2320 estate->fn_rettype = func->fn_rettype;
2321 estate->retistuple = func->fn_retistuple;
2322 estate->retisset = func->fn_retset;
2324 estate->readonly_func = func->fn_readonly;
2326 estate->rettupdesc = NULL;
2327 estate->exitlabel = NULL;
2329 estate->tuple_store = NULL;
2330 estate->tuple_store_cxt = NULL;
2333 estate->trig_nargs = 0;
2334 estate->trig_argv = NULL;
2336 estate->found_varno = func->found_varno;
2337 estate->ndatums = func->ndatums;
2338 estate->datums = palloc(sizeof(PLpgSQL_datum *) * estate->ndatums);
2339 /* caller is expected to fill the datums array */
2341 estate->eval_tuptable = NULL;
2342 estate->eval_processed = 0;
2343 estate->eval_lastoid = InvalidOid;
2345 estate->err_func = func;
2346 estate->err_stmt = NULL;
2347 estate->err_text = NULL;
2350 * Create an EState and ExprContext for evaluation of simple expressions.
2352 plpgsql_create_econtext(estate);
2355 * Let the plugin see this function before we initialize any local
2356 * PL/pgSQL variables - note that we also give the plugin a few function
2357 * pointers so it can call back into PL/pgSQL for doing things like
2358 * variable assignments and stack traces
2362 (*plugin_ptr)->error_callback = plpgsql_exec_error_callback;
2363 (*plugin_ptr)->assign_expr = exec_assign_expr;
2365 if ((*plugin_ptr)->func_setup)
2366 ((*plugin_ptr)->func_setup) (estate, func);
2371 * Release temporary memory used by expression/subselect evaluation
2373 * NB: the result of the evaluation is no longer valid after this is done,
2374 * unless it is a pass-by-value datatype.
2378 exec_eval_cleanup(PLpgSQL_execstate *estate)
2380 /* Clear result of a full SPI_execute */
2381 if (estate->eval_tuptable != NULL)
2382 SPI_freetuptable(estate->eval_tuptable);
2383 estate->eval_tuptable = NULL;
2385 /* Clear result of exec_eval_simple_expr (but keep the econtext) */
2386 if (estate->eval_econtext != NULL)
2387 ResetExprContext(estate->eval_econtext);
2392 * Generate a prepared plan
2396 exec_prepare_plan(PLpgSQL_execstate *estate,
2397 PLpgSQL_expr *expr, int cursorOptions)
2404 * We need a temporary argtypes array to load with data. (The finished
2405 * plan structure will contain a copy of it.)
2407 argtypes = (Oid *) palloc(expr->nparams * sizeof(Oid));
2409 for (i = 0; i < expr->nparams; i++)
2414 exec_eval_datum(estate, estate->datums[expr->params[i]],
2416 &argtypes[i], ¶mval, ¶misnull);
2420 * Generate and save the plan
2422 plan = SPI_prepare_cursor(expr->query, expr->nparams, argtypes,
2426 /* Some SPI errors deserve specific error messages */
2429 case SPI_ERROR_COPY:
2431 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2432 errmsg("cannot COPY to/from client in PL/pgSQL")));
2433 case SPI_ERROR_TRANSACTION:
2435 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2436 errmsg("cannot begin/end transactions in PL/pgSQL"),
2437 errhint("Use a BEGIN block with an EXCEPTION clause instead.")));
2439 elog(ERROR, "SPI_prepare_cursor failed for \"%s\": %s",
2440 expr->query, SPI_result_code_string(SPI_result));
2443 expr->plan = SPI_saveplan(plan);
2446 expr->plan_argtypes = plan->argtypes;
2447 exec_simple_check_plan(expr);
2454 * exec_stmt_execsql Execute an SQL statement (possibly with INTO).
2458 exec_stmt_execsql(PLpgSQL_execstate *estate,
2459 PLpgSQL_stmt_execsql *stmt)
2466 PLpgSQL_expr *expr = stmt->sqlstmt;
2469 * On the first call for this statement generate the plan, and detect
2470 * whether the statement is INSERT/UPDATE/DELETE
2472 if (expr->plan == NULL)
2476 exec_prepare_plan(estate, expr, 0);
2477 stmt->mod_stmt = false;
2478 foreach(l, expr->plan->plancache_list)
2480 CachedPlanSource *plansource = (CachedPlanSource *) lfirst(l);
2483 foreach(l2, plansource->plan->stmt_list)
2485 PlannedStmt *p = (PlannedStmt *) lfirst(l2);
2487 if (IsA(p, PlannedStmt) &&
2490 if (p->commandType == CMD_INSERT ||
2491 p->commandType == CMD_UPDATE ||
2492 p->commandType == CMD_DELETE)
2493 stmt->mod_stmt = true;
2500 * Now build up the values and nulls arguments for SPI_execute_plan()
2502 values = (Datum *) palloc(expr->nparams * sizeof(Datum));
2503 nulls = (char *) palloc(expr->nparams * sizeof(char));
2505 for (i = 0; i < expr->nparams; i++)
2507 PLpgSQL_datum *datum = estate->datums[expr->params[i]];
2511 exec_eval_datum(estate, datum, expr->plan_argtypes[i],
2512 ¶mtypeid, &values[i], ¶misnull);
2520 * If we have INTO, then we only need one row back ... but if we have INTO
2521 * STRICT, ask for two rows, so that we can verify the statement returns
2522 * only one. INSERT/UPDATE/DELETE are always treated strictly. Without
2523 * INTO, just run the statement to completion (tcount = 0).
2525 * We could just ask for two rows always when using INTO, but there are
2526 * some cases where demanding the extra row costs significant time, eg by
2527 * forcing completion of a sequential scan. So don't do it unless we need
2528 * to enforce strictness.
2532 if (stmt->strict || stmt->mod_stmt)
2543 rc = SPI_execute_plan(expr->plan, values, nulls,
2544 estate->readonly_func, tcount);
2547 * Check for error, and set FOUND if appropriate (for historical reasons
2548 * we set FOUND only for certain query types). Also Assert that we
2549 * identified the statement type the same as SPI did.
2554 Assert(!stmt->mod_stmt);
2555 exec_set_found(estate, (SPI_processed != 0));
2561 case SPI_OK_INSERT_RETURNING:
2562 case SPI_OK_UPDATE_RETURNING:
2563 case SPI_OK_DELETE_RETURNING:
2564 Assert(stmt->mod_stmt);
2565 exec_set_found(estate, (SPI_processed != 0));
2568 case SPI_OK_SELINTO:
2569 case SPI_OK_UTILITY:
2570 Assert(!stmt->mod_stmt);
2574 elog(ERROR, "SPI_execute_plan failed executing query \"%s\": %s",
2575 expr->query, SPI_result_code_string(rc));
2578 /* All variants should save result info for GET DIAGNOSTICS */
2579 estate->eval_processed = SPI_processed;
2580 estate->eval_lastoid = SPI_lastoid;
2582 /* Process INTO if present */
2585 SPITupleTable *tuptab = SPI_tuptable;
2586 uint32 n = SPI_processed;
2587 PLpgSQL_rec *rec = NULL;
2588 PLpgSQL_row *row = NULL;
2590 /* If the statement did not return a tuple table, complain */
2593 (errcode(ERRCODE_SYNTAX_ERROR),
2594 errmsg("INTO used with a command that cannot return data")));
2596 /* Determine if we assign to a record or a row */
2597 if (stmt->rec != NULL)
2598 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
2599 else if (stmt->row != NULL)
2600 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
2602 elog(ERROR, "unsupported target");
2605 * If SELECT ... INTO specified STRICT, and the query didn't find
2606 * exactly one row, throw an error. If STRICT was not specified, then
2607 * allow the query to find any number of rows.
2613 (errcode(ERRCODE_NO_DATA_FOUND),
2614 errmsg("query returned no rows")));
2615 /* set the target to NULL(s) */
2616 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
2620 if (n > 1 && (stmt->strict || stmt->mod_stmt))
2622 (errcode(ERRCODE_TOO_MANY_ROWS),
2623 errmsg("query returned more than one row")));
2624 /* Put the first result row into the target */
2625 exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
2629 SPI_freetuptable(SPI_tuptable);
2633 /* If the statement returned a tuple table, complain */
2634 if (SPI_tuptable != NULL)
2636 (errcode(ERRCODE_SYNTAX_ERROR),
2637 errmsg("query has no destination for result data"),
2638 (rc == SPI_OK_SELECT) ? errhint("If you want to discard the results of a SELECT, use PERFORM instead.") : 0));
2644 return PLPGSQL_RC_OK;
2649 * exec_stmt_dynexecute Execute a dynamic SQL query
2650 * (possibly with INTO).
2654 exec_stmt_dynexecute(PLpgSQL_execstate *estate,
2655 PLpgSQL_stmt_dynexecute *stmt)
2658 bool isnull = false;
2664 * First we evaluate the string expression after the EXECUTE keyword. Its
2665 * result is the querystring we have to execute.
2667 query = exec_eval_expr(estate, stmt->query, &isnull, &restype);
2670 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2671 errmsg("cannot EXECUTE a null querystring")));
2673 /* Get the C-String representation */
2674 querystr = convert_value_to_string(query, restype);
2676 exec_eval_cleanup(estate);
2679 * Call SPI_execute() without preparing a saved plan.
2681 exec_res = SPI_execute(querystr, estate->readonly_func, 0);
2689 case SPI_OK_INSERT_RETURNING:
2690 case SPI_OK_UPDATE_RETURNING:
2691 case SPI_OK_DELETE_RETURNING:
2692 case SPI_OK_UTILITY:
2698 * Also allow a zero return, which implies the querystring
2699 * contained no commands.
2703 case SPI_OK_SELINTO:
2706 * We want to disallow SELECT INTO for now, because its behavior
2707 * is not consistent with SELECT INTO in a normal plpgsql context.
2708 * (We need to reimplement EXECUTE to parse the string as a
2709 * plpgsql command, not just feed it to SPI_execute.) However,
2710 * CREATE AS should be allowed ... and since it produces the same
2711 * parsetree as SELECT INTO, there's no way to tell the difference
2712 * except to look at the source text. Wotta kluge!
2717 for (ptr = querystr; *ptr; ptr++)
2718 if (!scanner_isspace(*ptr))
2720 if (*ptr == 'S' || *ptr == 's')
2722 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2723 errmsg("EXECUTE of SELECT ... INTO is not implemented yet")));
2727 /* Some SPI errors deserve specific error messages */
2728 case SPI_ERROR_COPY:
2730 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2731 errmsg("cannot COPY to/from client in PL/pgSQL")));
2732 case SPI_ERROR_TRANSACTION:
2734 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2735 errmsg("cannot begin/end transactions in PL/pgSQL"),
2736 errhint("Use a BEGIN block with an EXCEPTION clause instead.")));
2739 elog(ERROR, "SPI_execute failed executing query \"%s\": %s",
2740 querystr, SPI_result_code_string(exec_res));
2744 /* Save result info for GET DIAGNOSTICS */
2745 estate->eval_processed = SPI_processed;
2746 estate->eval_lastoid = SPI_lastoid;
2748 /* Process INTO if present */
2751 SPITupleTable *tuptab = SPI_tuptable;
2752 uint32 n = SPI_processed;
2753 PLpgSQL_rec *rec = NULL;
2754 PLpgSQL_row *row = NULL;
2756 /* If the statement did not return a tuple table, complain */
2759 (errcode(ERRCODE_SYNTAX_ERROR),
2760 errmsg("INTO used with a command that cannot return data")));
2762 /* Determine if we assign to a record or a row */
2763 if (stmt->rec != NULL)
2764 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
2765 else if (stmt->row != NULL)
2766 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
2768 elog(ERROR, "unsupported target");
2771 * If SELECT ... INTO specified STRICT, and the query didn't find
2772 * exactly one row, throw an error. If STRICT was not specified, then
2773 * allow the query to find any number of rows.
2779 (errcode(ERRCODE_NO_DATA_FOUND),
2780 errmsg("query returned no rows")));
2781 /* set the target to NULL(s) */
2782 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
2786 if (n > 1 && stmt->strict)
2788 (errcode(ERRCODE_TOO_MANY_ROWS),
2789 errmsg("query returned more than one row")));
2790 /* Put the first result row into the target */
2791 exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
2797 * It might be a good idea to raise an error if the query returned
2798 * tuples that are being ignored, but historically we have not done
2803 /* Release any result from SPI_execute, as well as the querystring */
2804 SPI_freetuptable(SPI_tuptable);
2807 return PLPGSQL_RC_OK;
2812 * exec_stmt_dynfors Execute a dynamic query, assign each
2813 * tuple to a record or row and
2814 * execute a group of statements
2819 exec_stmt_dynfors(PLpgSQL_execstate *estate, PLpgSQL_stmt_dynfors *stmt)
2825 PLpgSQL_rec *rec = NULL;
2826 PLpgSQL_row *row = NULL;
2827 SPITupleTable *tuptab;
2834 * Determine if we assign to a record or a row
2836 if (stmt->rec != NULL)
2837 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
2838 else if (stmt->row != NULL)
2839 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
2841 elog(ERROR, "unsupported target");
2844 * Evaluate the string expression after the EXECUTE keyword. It's result
2845 * is the querystring we have to execute.
2847 query = exec_eval_expr(estate, stmt->query, &isnull, &restype);
2850 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2851 errmsg("cannot EXECUTE a null querystring")));
2853 /* Get the C-String representation */
2854 querystr = convert_value_to_string(query, restype);
2856 exec_eval_cleanup(estate);
2859 * Prepare a plan and open an implicit cursor for the query
2861 plan = SPI_prepare(querystr, 0, NULL);
2863 elog(ERROR, "SPI_prepare failed for \"%s\": %s",
2864 querystr, SPI_result_code_string(SPI_result));
2865 portal = SPI_cursor_open(NULL, plan, NULL, NULL,
2866 estate->readonly_func);
2868 elog(ERROR, "could not open implicit cursor for query \"%s\": %s",
2869 querystr, SPI_result_code_string(SPI_result));
2874 * Fetch the initial 10 tuples
2876 SPI_cursor_fetch(portal, true, 10);
2877 tuptab = SPI_tuptable;
2881 * If the query didn't return any rows, set the target to NULL and return
2882 * with FOUND = false.
2885 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
2887 found = true; /* processed at least one tuple */
2896 for (i = 0; i < n; i++)
2901 * Assign the tuple to the target
2903 exec_move_row(estate, rec, row, tuptab->vals[i], tuptab->tupdesc);
2906 * Execute the statements
2908 rc = exec_stmts(estate, stmt->body);
2910 if (rc != PLPGSQL_RC_OK)
2912 if (rc == PLPGSQL_RC_EXIT)
2914 if (estate->exitlabel == NULL)
2915 /* unlabelled exit, finish the current loop */
2917 else if (stmt->label != NULL &&
2918 strcmp(stmt->label, estate->exitlabel) == 0)
2920 /* labelled exit, matches the current stmt's label */
2921 estate->exitlabel = NULL;
2926 * otherwise, we processed a labelled exit that does not
2927 * match the current statement's label, if any: return
2928 * RC_EXIT so that the EXIT continues to recurse upward.
2931 else if (rc == PLPGSQL_RC_CONTINUE)
2933 if (estate->exitlabel == NULL)
2934 /* unlabelled continue, continue the current loop */
2936 else if (stmt->label != NULL &&
2937 strcmp(stmt->label, estate->exitlabel) == 0)
2939 /* labelled continue, matches the current stmt's label */
2940 estate->exitlabel = NULL;
2945 * otherwise, we process a labelled continue that does not
2946 * match the current statement's label, so propagate
2947 * RC_CONTINUE upward in the stack.
2952 * We're aborting the loop, so cleanup and set FOUND. (This
2953 * code should match the code after the loop.)
2955 SPI_freetuptable(tuptab);
2956 SPI_cursor_close(portal);
2957 exec_set_found(estate, found);
2963 SPI_freetuptable(tuptab);
2966 * Fetch the next 50 tuples
2968 SPI_cursor_fetch(portal, true, 50);
2970 tuptab = SPI_tuptable;
2974 * Release last group of tuples
2976 SPI_freetuptable(tuptab);
2979 * Close the implicit cursor
2981 SPI_cursor_close(portal);
2984 * Set the FOUND variable to indicate the result of executing the loop
2985 * (namely, whether we looped one or more times). This must be set here so
2986 * that it does not interfere with the value of the FOUND variable inside
2987 * the loop processing itself.
2989 exec_set_found(estate, found);
2991 return PLPGSQL_RC_OK;
2996 * exec_stmt_open Execute an OPEN cursor statement
3000 exec_stmt_open(PLpgSQL_execstate *estate, PLpgSQL_stmt_open *stmt)
3002 PLpgSQL_var *curvar = NULL;
3003 char *curname = NULL;
3004 PLpgSQL_expr *query = NULL;
3013 * Get the cursor variable and if it has an assigned name, check
3014 * that it's not in use currently.
3017 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
3018 if (!curvar->isnull)
3020 curname = TextDatumGetCString(curvar->value);
3021 if (SPI_cursor_find(curname) != NULL)
3023 (errcode(ERRCODE_DUPLICATE_CURSOR),
3024 errmsg("cursor \"%s\" already in use", curname)));
3028 * Process the OPEN according to it's type.
3031 if (stmt->query != NULL)
3034 * This is an OPEN refcursor FOR SELECT ...
3036 * We just make sure the query is planned. The real work is
3040 query = stmt->query;
3041 if (query->plan == NULL)
3042 exec_prepare_plan(estate, query, stmt->cursor_options);
3044 else if (stmt->dynquery != NULL)
3047 * This is an OPEN refcursor FOR EXECUTE ...
3056 * We evaluate the string expression after the
3057 * EXECUTE keyword. It's result is the querystring we have
3061 queryD = exec_eval_expr(estate, stmt->dynquery, &isnull, &restype);
3064 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3065 errmsg("cannot EXECUTE a null querystring")));
3067 /* Get the C-String representation */
3068 querystr = convert_value_to_string(queryD, restype);
3070 exec_eval_cleanup(estate);
3073 * Now we prepare a query plan for it and open a cursor
3076 curplan = SPI_prepare_cursor(querystr, 0, NULL, stmt->cursor_options);
3077 if (curplan == NULL)
3078 elog(ERROR, "SPI_prepare_cursor failed for \"%s\": %s",
3079 querystr, SPI_result_code_string(SPI_result));
3080 portal = SPI_cursor_open(curname, curplan, NULL, NULL,
3081 estate->readonly_func);
3083 elog(ERROR, "could not open cursor for query \"%s\": %s",
3084 querystr, SPI_result_code_string(SPI_result));
3086 SPI_freeplan(curplan);
3089 * Store the eventually assigned cursor name in the cursor variable
3093 curvar->value = CStringGetTextDatum(portal->name);
3094 curvar->isnull = false;
3095 curvar->freeval = true;
3097 return PLPGSQL_RC_OK;
3102 * This is an OPEN cursor
3104 * Note: parser should already have checked that statement supplies
3105 * args iff cursor needs them, but we check again to be safe.
3108 if (stmt->argquery != NULL)
3111 * OPEN CURSOR with args. We fake a SELECT ... INTO ...
3112 * statement to evaluate the args and put 'em into the
3116 PLpgSQL_stmt_execsql set_args;
3118 if (curvar->cursor_explicit_argrow < 0)
3120 (errcode(ERRCODE_SYNTAX_ERROR),
3121 errmsg("arguments given for cursor without arguments")));
3123 memset(&set_args, 0, sizeof(set_args));
3124 set_args.cmd_type = PLPGSQL_STMT_EXECSQL;
3125 set_args.lineno = stmt->lineno;
3126 set_args.sqlstmt = stmt->argquery;
3127 set_args.into = true;
3128 /* XXX historically this has not been STRICT */
3129 set_args.row = (PLpgSQL_row *)
3130 (estate->datums[curvar->cursor_explicit_argrow]);
3132 if (exec_stmt_execsql(estate, &set_args) != PLPGSQL_RC_OK)
3133 elog(ERROR, "open cursor failed during argument processing");
3137 if (curvar->cursor_explicit_argrow >= 0)
3139 (errcode(ERRCODE_SYNTAX_ERROR),
3140 errmsg("arguments required for cursor")));
3143 query = curvar->cursor_explicit_expr;
3144 if (query->plan == NULL)
3145 exec_prepare_plan(estate, query, curvar->cursor_options);
3149 * Here we go if we have a saved plan where we have to put
3150 * values into, either from an explicit cursor or from a
3151 * refcursor opened with OPEN ... FOR SELECT ...;
3154 values = (Datum *) palloc(query->nparams * sizeof(Datum));
3155 nulls = (char *) palloc(query->nparams * sizeof(char));
3157 for (i = 0; i < query->nparams; i++)
3159 PLpgSQL_datum *datum = estate->datums[query->params[i]];
3163 exec_eval_datum(estate, datum, query->plan_argtypes[i],
3164 ¶mtypeid, &values[i], ¶misnull);
3175 portal = SPI_cursor_open(curname, query->plan, values, nulls,
3176 estate->readonly_func);
3178 elog(ERROR, "could not open cursor: %s",
3179 SPI_result_code_string(SPI_result));
3187 * Store the eventually assigned portal name in the cursor variable
3191 curvar->value = CStringGetTextDatum(portal->name);
3192 curvar->isnull = false;
3193 curvar->freeval = true;
3195 return PLPGSQL_RC_OK;
3200 * exec_stmt_fetch Fetch from a cursor into a target, or just
3201 * move the current position of the cursor
3205 exec_stmt_fetch(PLpgSQL_execstate *estate, PLpgSQL_stmt_fetch *stmt)
3207 PLpgSQL_var *curvar = NULL;
3208 PLpgSQL_rec *rec = NULL;
3209 PLpgSQL_row *row = NULL;
3210 long how_many = stmt->how_many;
3211 SPITupleTable *tuptab;
3217 * Get the portal of the cursor by name
3220 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
3223 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3224 errmsg("cursor variable \"%s\" is NULL", curvar->refname)));
3225 curname = TextDatumGetCString(curvar->value);
3227 portal = SPI_cursor_find(curname);
3230 (errcode(ERRCODE_UNDEFINED_CURSOR),
3231 errmsg("cursor \"%s\" does not exist", curname)));
3234 /* Calculate position for FETCH_RELATIVE or FETCH_ABSOLUTE */
3239 /* XXX should be doing this in LONG not INT width */
3240 how_many = exec_eval_integer(estate, stmt->expr, &isnull);
3244 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3245 errmsg("relative or absolute cursor position is NULL")));
3247 exec_eval_cleanup(estate);
3253 * Determine if we fetch into a record or a row
3256 if (stmt->rec != NULL)
3257 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
3258 else if (stmt->row != NULL)
3259 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
3261 elog(ERROR, "unsupported target");
3264 * Fetch 1 tuple from the cursor
3267 SPI_scroll_cursor_fetch(portal, stmt->direction, how_many);
3268 tuptab = SPI_tuptable;
3272 * Set the target and the global FOUND variable appropriately.
3277 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
3278 exec_set_found(estate, false);
3282 exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
3283 exec_set_found(estate, true);
3286 SPI_freetuptable(tuptab);
3290 /* Move the cursor */
3291 SPI_scroll_cursor_move(portal, stmt->direction, how_many);
3294 /* Set the global FOUND variable appropriately. */
3295 exec_set_found(estate, n != 0);
3298 return PLPGSQL_RC_OK;
3302 * exec_stmt_close Close a cursor
3306 exec_stmt_close(PLpgSQL_execstate *estate, PLpgSQL_stmt_close *stmt)
3308 PLpgSQL_var *curvar = NULL;
3313 * Get the portal of the cursor by name
3316 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
3319 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3320 errmsg("cursor variable \"%s\" is NULL", curvar->refname)));
3321 curname = TextDatumGetCString(curvar->value);
3323 portal = SPI_cursor_find(curname);
3326 (errcode(ERRCODE_UNDEFINED_CURSOR),
3327 errmsg("cursor \"%s\" does not exist", curname)));
3334 SPI_cursor_close(portal);
3336 return PLPGSQL_RC_OK;
3341 * exec_assign_expr Put an expression's result into
3346 exec_assign_expr(PLpgSQL_execstate *estate, PLpgSQL_datum *target,
3351 bool isnull = false;
3353 value = exec_eval_expr(estate, expr, &isnull, &valtype);
3354 exec_assign_value(estate, target, value, valtype, &isnull);
3355 exec_eval_cleanup(estate);
3360 * exec_assign_value Put a value into a target field
3364 exec_assign_value(PLpgSQL_execstate *estate,
3365 PLpgSQL_datum *target,
3366 Datum value, Oid valtype, bool *isNull)
3368 switch (target->dtype)
3370 case PLPGSQL_DTYPE_VAR:
3373 * Target is a variable
3375 PLpgSQL_var *var = (PLpgSQL_var *) target;
3378 newvalue = exec_cast_value(value, valtype, var->datatype->typoid,
3379 &(var->datatype->typinput),
3380 var->datatype->typioparam,
3381 var->datatype->atttypmod,
3384 if (*isNull && var->notnull)
3386 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3387 errmsg("NULL cannot be assigned to variable \"%s\" declared NOT NULL",
3391 * If type is by-reference, make sure we have a freshly
3392 * palloc'd copy; the originally passed value may not live as
3393 * long as the variable! But we don't need to re-copy if
3394 * exec_cast_value performed a conversion; its output must
3395 * already be palloc'd.
3397 if (!var->datatype->typbyval && !*isNull)
3399 if (newvalue == value)
3400 newvalue = datumCopy(newvalue,
3402 var->datatype->typlen);
3406 * Now free the old value. (We can't do this any earlier
3407 * because of the possibility that we are assigning the var's
3408 * old value to it, eg "foo := foo". We could optimize out
3409 * the assignment altogether in such cases, but it's too
3410 * infrequent to be worth testing for.)
3414 var->value = newvalue;
3415 var->isnull = *isNull;
3416 if (!var->datatype->typbyval && !*isNull)
3417 var->freeval = true;
3421 case PLPGSQL_DTYPE_ROW:
3424 * Target is a row variable
3426 PLpgSQL_row *row = (PLpgSQL_row *) target;
3428 /* Source must be of RECORD or composite type */
3429 if (!type_is_rowtype(valtype))
3431 (errcode(ERRCODE_DATATYPE_MISMATCH),
3432 errmsg("cannot assign non-composite value to a row variable")));
3435 /* If source is null, just assign nulls to the row */
3436 exec_move_row(estate, NULL, row, NULL, NULL);
3444 HeapTupleData tmptup;
3446 /* Else source is a tuple Datum, safe to do this: */
3447 td = DatumGetHeapTupleHeader(value);
3448 /* Extract rowtype info and find a tupdesc */
3449 tupType = HeapTupleHeaderGetTypeId(td);
3450 tupTypmod = HeapTupleHeaderGetTypMod(td);
3451 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
3452 /* Build a temporary HeapTuple control structure */
3453 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
3454 ItemPointerSetInvalid(&(tmptup.t_self));
3455 tmptup.t_tableOid = InvalidOid;
3457 exec_move_row(estate, NULL, row, &tmptup, tupdesc);
3458 ReleaseTupleDesc(tupdesc);
3463 case PLPGSQL_DTYPE_REC:
3466 * Target is a record variable
3468 PLpgSQL_rec *rec = (PLpgSQL_rec *) target;
3470 /* Source must be of RECORD or composite type */
3471 if (!type_is_rowtype(valtype))
3473 (errcode(ERRCODE_DATATYPE_MISMATCH),
3474 errmsg("cannot assign non-composite value to a record variable")));
3477 /* If source is null, just assign nulls to the record */
3478 exec_move_row(estate, rec, NULL, NULL, NULL);
3486 HeapTupleData tmptup;
3488 /* Else source is a tuple Datum, safe to do this: */
3489 td = DatumGetHeapTupleHeader(value);
3490 /* Extract rowtype info and find a tupdesc */
3491 tupType = HeapTupleHeaderGetTypeId(td);
3492 tupTypmod = HeapTupleHeaderGetTypMod(td);
3493 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
3494 /* Build a temporary HeapTuple control structure */
3495 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
3496 ItemPointerSetInvalid(&(tmptup.t_self));
3497 tmptup.t_tableOid = InvalidOid;
3499 exec_move_row(estate, rec, NULL, &tmptup, tupdesc);
3500 ReleaseTupleDesc(tupdesc);
3505 case PLPGSQL_DTYPE_RECFIELD:
3508 * Target is a field of a record
3510 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) target;
3523 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
3526 * Check that there is already a tuple in the record. We need
3527 * that because records don't have any predefined field
3530 if (!HeapTupleIsValid(rec->tup))
3532 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3533 errmsg("record \"%s\" is not assigned yet",
3535 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
3538 * Get the number of the records field to change and the
3539 * number of attributes in the tuple.
3541 fno = SPI_fnumber(rec->tupdesc, recfield->fieldname);
3542 if (fno == SPI_ERROR_NOATTRIBUTE)
3544 (errcode(ERRCODE_UNDEFINED_COLUMN),
3545 errmsg("record \"%s\" has no field \"%s\"",
3546 rec->refname, recfield->fieldname)));
3548 natts = rec->tupdesc->natts;
3551 * Set up values/datums arrays for heap_formtuple. For all
3552 * the attributes except the one we want to replace, use the
3553 * value that's in the old tuple.
3555 values = palloc(sizeof(Datum) * natts);
3556 nulls = palloc(natts);
3558 for (i = 0; i < natts; i++)
3562 values[i] = SPI_getbinval(rec->tup, rec->tupdesc,
3571 * Now insert the new value, being careful to cast it to the
3574 atttype = SPI_gettypeid(rec->tupdesc, fno + 1);
3575 atttypmod = rec->tupdesc->attrs[fno]->atttypmod;
3576 attisnull = *isNull;
3577 values[fno] = exec_simple_cast_value(value,
3588 * Avoid leaking the result of exec_simple_cast_value, if it
3589 * performed a conversion to a pass-by-ref type.
3591 if (!attisnull && values[fno] != value && !get_typbyval(atttype))
3592 mustfree = DatumGetPointer(values[fno]);
3597 * Now call heap_formtuple() to create a new tuple that
3598 * replaces the old one in the record.
3600 newtup = heap_formtuple(rec->tupdesc, values, nulls);
3603 heap_freetuple(rec->tup);
3606 rec->freetup = true;
3616 case PLPGSQL_DTYPE_ARRAYELEM:
3620 PLpgSQL_expr *subscripts[MAXDIM];
3621 int subscriptvals[MAXDIM];
3622 bool oldarrayisnull;
3629 Datum oldarraydatum,
3631 ArrayType *oldarrayval;
3632 ArrayType *newarrayval;
3635 * Target is an element of an array
3637 * To handle constructs like x[1][2] := something, we have to
3638 * be prepared to deal with a chain of arrayelem datums. Chase
3639 * back to find the base array datum, and save the subscript
3640 * expressions as we go. (We are scanning right to left here,
3641 * but want to evaluate the subscripts left-to-right to
3642 * minimize surprises.)
3647 PLpgSQL_arrayelem *arrayelem = (PLpgSQL_arrayelem *) target;
3649 if (nsubscripts >= MAXDIM)
3651 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
3652 errmsg("number of array dimensions exceeds the maximum allowed, %d",
3654 subscripts[nsubscripts++] = arrayelem->subscript;
3655 target = estate->datums[arrayelem->arrayparentno];
3656 } while (target->dtype == PLPGSQL_DTYPE_ARRAYELEM);
3658 /* Fetch current value of array datum */
3659 exec_eval_datum(estate, target, InvalidOid,
3660 &arraytypeid, &oldarraydatum, &oldarrayisnull);
3662 arrayelemtypeid = get_element_type(arraytypeid);
3663 if (!OidIsValid(arrayelemtypeid))
3665 (errcode(ERRCODE_DATATYPE_MISMATCH),
3666 errmsg("subscripted object is not an array")));
3668 get_typlenbyvalalign(arrayelemtypeid,
3672 arraytyplen = get_typlen(arraytypeid);
3675 * Evaluate the subscripts, switch into left-to-right order.
3676 * Like ExecEvalArrayRef(), complain if any subscript is null.
3678 for (i = 0; i < nsubscripts; i++)
3683 exec_eval_integer(estate,
3684 subscripts[nsubscripts - 1 - i],
3688 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3689 errmsg("array subscript in assignment must not be NULL")));
3692 /* Coerce source value to match array element type. */
3693 coerced_value = exec_simple_cast_value(value,
3700 * If the original array is null, cons up an empty array so
3701 * that the assignment can proceed; we'll end with a
3702 * one-element array containing just the assigned-to
3703 * subscript. This only works for varlena arrays, though; for
3704 * fixed-length array types we skip the assignment. We can't
3705 * support assignment of a null entry into a fixed-length
3706 * array, either, so that's a no-op too. This is all ugly but
3707 * corresponds to the current behavior of ExecEvalArrayRef().
3709 if (arraytyplen > 0 && /* fixed-length array? */
3710 (oldarrayisnull || *isNull))
3714 oldarrayval = construct_empty_array(arrayelemtypeid);
3716 oldarrayval = (ArrayType *) DatumGetPointer(oldarraydatum);
3719 * Build the modified array value.
3721 newarrayval = array_set(oldarrayval,
3732 * Avoid leaking the result of exec_simple_cast_value, if it
3733 * performed a conversion to a pass-by-ref type.
3735 if (!*isNull && coerced_value != value && !elemtypbyval)
3736 pfree(DatumGetPointer(coerced_value));
3739 * Assign the new array to the base variable. It's never NULL
3743 exec_assign_value(estate, target,
3744 PointerGetDatum(newarrayval),
3745 arraytypeid, isNull);
3748 * Avoid leaking the modified array value, too.
3755 elog(ERROR, "unrecognized dtype: %d", target->dtype);
3760 * exec_eval_datum Get current value of a PLpgSQL_datum
3762 * The type oid, value in Datum format, and null flag are returned.
3764 * If expectedtypeid isn't InvalidOid, it is checked against the actual type.
3766 * At present this doesn't handle PLpgSQL_expr or PLpgSQL_arrayelem datums.
3768 * NOTE: caller must not modify the returned value, since it points right
3769 * at the stored value in the case of pass-by-reference datatypes. In some
3770 * cases we have to palloc a return value, and in such cases we put it into
3771 * the estate's short-term memory context.
3774 exec_eval_datum(PLpgSQL_execstate *estate,
3775 PLpgSQL_datum *datum,
3781 MemoryContext oldcontext;
3783 switch (datum->dtype)
3785 case PLPGSQL_DTYPE_VAR:
3787 PLpgSQL_var *var = (PLpgSQL_var *) datum;
3789 *typeid = var->datatype->typoid;
3790 *value = var->value;
3791 *isnull = var->isnull;
3792 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3794 (errcode(ERRCODE_DATATYPE_MISMATCH),
3795 errmsg("type of \"%s\" does not match that when preparing the plan",
3800 case PLPGSQL_DTYPE_ROW:
3802 PLpgSQL_row *row = (PLpgSQL_row *) datum;
3805 if (!row->rowtupdesc) /* should not happen */
3806 elog(ERROR, "row variable has no tupdesc");
3807 /* Make sure we have a valid type/typmod setting */
3808 BlessTupleDesc(row->rowtupdesc);
3809 oldcontext = MemoryContextSwitchTo(estate->eval_econtext->ecxt_per_tuple_memory);
3810 tup = make_tuple_from_row(estate, row, row->rowtupdesc);
3811 if (tup == NULL) /* should not happen */
3812 elog(ERROR, "row not compatible with its own tupdesc");
3813 MemoryContextSwitchTo(oldcontext);
3814 *typeid = row->rowtupdesc->tdtypeid;
3815 *value = HeapTupleGetDatum(tup);
3817 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3819 (errcode(ERRCODE_DATATYPE_MISMATCH),
3820 errmsg("type of \"%s\" does not match that when preparing the plan",
3825 case PLPGSQL_DTYPE_REC:
3827 PLpgSQL_rec *rec = (PLpgSQL_rec *) datum;
3828 HeapTupleData worktup;
3830 if (!HeapTupleIsValid(rec->tup))
3832 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3833 errmsg("record \"%s\" is not assigned yet",
3835 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
3836 Assert(rec->tupdesc != NULL);
3837 /* Make sure we have a valid type/typmod setting */
3838 BlessTupleDesc(rec->tupdesc);
3841 * In a trigger, the NEW and OLD parameters are likely to be
3842 * on-disk tuples that don't have the desired Datum fields.
3843 * Copy the tuple body and insert the right values.
3845 oldcontext = MemoryContextSwitchTo(estate->eval_econtext->ecxt_per_tuple_memory);
3846 heap_copytuple_with_tuple(rec->tup, &worktup);
3847 HeapTupleHeaderSetDatumLength(worktup.t_data, worktup.t_len);
3848 HeapTupleHeaderSetTypeId(worktup.t_data, rec->tupdesc->tdtypeid);
3849 HeapTupleHeaderSetTypMod(worktup.t_data, rec->tupdesc->tdtypmod);
3850 MemoryContextSwitchTo(oldcontext);
3851 *typeid = rec->tupdesc->tdtypeid;
3852 *value = HeapTupleGetDatum(&worktup);
3854 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3856 (errcode(ERRCODE_DATATYPE_MISMATCH),
3857 errmsg("type of \"%s\" does not match that when preparing the plan",
3862 case PLPGSQL_DTYPE_RECFIELD:
3864 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) datum;
3868 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
3869 if (!HeapTupleIsValid(rec->tup))
3871 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3872 errmsg("record \"%s\" is not assigned yet",
3874 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
3875 fno = SPI_fnumber(rec->tupdesc, recfield->fieldname);
3876 if (fno == SPI_ERROR_NOATTRIBUTE)
3878 (errcode(ERRCODE_UNDEFINED_COLUMN),
3879 errmsg("record \"%s\" has no field \"%s\"",
3880 rec->refname, recfield->fieldname)));
3881 *typeid = SPI_gettypeid(rec->tupdesc, fno);
3882 *value = SPI_getbinval(rec->tup, rec->tupdesc, fno, isnull);
3883 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3885 (errcode(ERRCODE_DATATYPE_MISMATCH),
3886 errmsg("type of \"%s.%s\" does not match that when preparing the plan",
3887 rec->refname, recfield->fieldname)));
3891 case PLPGSQL_DTYPE_TRIGARG:
3893 PLpgSQL_trigarg *trigarg = (PLpgSQL_trigarg *) datum;
3897 tgargno = exec_eval_integer(estate, trigarg->argnum, isnull);
3898 if (*isnull || tgargno < 0 || tgargno >= estate->trig_nargs)
3905 *value = estate->trig_argv[tgargno];
3908 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3910 (errcode(ERRCODE_DATATYPE_MISMATCH),
3911 errmsg("type of tgargv[%d] does not match that when preparing the plan",
3917 elog(ERROR, "unrecognized dtype: %d", datum->dtype);
3922 * exec_eval_integer Evaluate an expression, coerce result to int4
3924 * Note we do not do exec_eval_cleanup here; the caller must do it at
3925 * some later point. (We do this because the caller may be holding the
3926 * results of other, pass-by-reference, expression evaluations, such as
3927 * an array value to be subscripted. Also see notes in exec_eval_simple_expr
3928 * about allocation of the parameter array.)
3932 exec_eval_integer(PLpgSQL_execstate *estate,
3939 exprdatum = exec_eval_expr(estate, expr, isNull, &exprtypeid);
3940 exprdatum = exec_simple_cast_value(exprdatum, exprtypeid,
3943 return DatumGetInt32(exprdatum);
3947 * exec_eval_boolean Evaluate an expression, coerce result to bool
3949 * Note we do not do exec_eval_cleanup here; the caller must do it at
3954 exec_eval_boolean(PLpgSQL_execstate *estate,
3961 exprdatum = exec_eval_expr(estate, expr, isNull, &exprtypeid);
3962 exprdatum = exec_simple_cast_value(exprdatum, exprtypeid,
3965 return DatumGetBool(exprdatum);
3969 * exec_eval_expr Evaluate an expression and return
3972 * NOTE: caller must do exec_eval_cleanup when done with the Datum.
3976 exec_eval_expr(PLpgSQL_execstate *estate,
3985 * If first time through, create a plan for this expression.
3987 if (expr->plan == NULL)
3988 exec_prepare_plan(estate, expr, 0);
3991 * If this is a simple expression, bypass SPI and use the executor
3994 if (exec_eval_simple_expr(estate, expr, &result, isNull, rettype))
3998 * Else do it the hard way via exec_run_select
4000 rc = exec_run_select(estate, expr, 2, NULL);
4001 if (rc != SPI_OK_SELECT)
4003 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
4004 errmsg("query \"%s\" did not return data", expr->query)));
4007 * If there are no rows selected, the result is NULL.
4009 if (estate->eval_processed == 0)
4016 * Check that the expression returned one single Datum
4018 if (estate->eval_processed > 1)
4020 (errcode(ERRCODE_CARDINALITY_VIOLATION),
4021 errmsg("query \"%s\" returned more than one row",
4023 if (estate->eval_tuptable->tupdesc->natts != 1)
4025 (errcode(ERRCODE_SYNTAX_ERROR),
4026 errmsg("query \"%s\" returned %d columns", expr->query,
4027 estate->eval_tuptable->tupdesc->natts)));
4030 * Return the result and its type
4032 *rettype = SPI_gettypeid(estate->eval_tuptable->tupdesc, 1);
4033 return SPI_getbinval(estate->eval_tuptable->vals[0],
4034 estate->eval_tuptable->tupdesc, 1, isNull);
4039 * exec_run_select Execute a select query
4043 exec_run_select(PLpgSQL_execstate *estate,
4044 PLpgSQL_expr *expr, long maxtuples, Portal *portalP)
4052 * On the first call for this expression generate the plan
4054 if (expr->plan == NULL)
4055 exec_prepare_plan(estate, expr, 0);
4058 * Now build up the values and nulls arguments for SPI_execute_plan()
4060 values = (Datum *) palloc(expr->nparams * sizeof(Datum));
4061 nulls = (char *) palloc(expr->nparams * sizeof(char));
4063 for (i = 0; i < expr->nparams; i++)
4065 PLpgSQL_datum *datum = estate->datums[expr->params[i]];
4069 exec_eval_datum(estate, datum, expr->plan_argtypes[i],
4070 ¶mtypeid, &values[i], ¶misnull);
4078 * If a portal was requested, put the query into the portal
4080 if (portalP != NULL)
4082 *portalP = SPI_cursor_open(NULL, expr->plan, values, nulls,
4083 estate->readonly_func);
4084 if (*portalP == NULL)
4085 elog(ERROR, "could not open implicit cursor for query \"%s\": %s",
4086 expr->query, SPI_result_code_string(SPI_result));
4089 return SPI_OK_CURSOR;
4095 rc = SPI_execute_plan(expr->plan, values, nulls,
4096 estate->readonly_func, maxtuples);
4097 if (rc != SPI_OK_SELECT)
4099 (errcode(ERRCODE_SYNTAX_ERROR),
4100 errmsg("query \"%s\" is not a SELECT", expr->query)));
4102 /* Save query results for eventual cleanup */
4103 Assert(estate->eval_tuptable == NULL);
4104 estate->eval_tuptable = SPI_tuptable;
4105 estate->eval_processed = SPI_processed;
4106 estate->eval_lastoid = SPI_lastoid;
4116 * exec_eval_simple_expr - Evaluate a simple expression returning
4117 * a Datum by directly calling ExecEvalExpr().
4119 * If successful, store results into *result, *isNull, *rettype and return
4120 * TRUE. If the expression is not simple (any more), return FALSE.
4122 * It is possible though unlikely for a simple expression to become non-simple
4123 * (consider for example redefining a trivial view). We must handle that for
4124 * correctness; fortunately it's normally inexpensive to do
4125 * RevalidateCachedPlan on a simple expression. We do not consider the other
4126 * direction (non-simple expression becoming simple) because we'll still give
4127 * correct results if that happens, and it's unlikely to be worth the cycles
4130 * Note: if pass-by-reference, the result is in the eval_econtext's
4131 * temporary memory context. It will be freed when exec_eval_cleanup
4136 exec_eval_simple_expr(PLpgSQL_execstate *estate,
4142 ExprContext *econtext = estate->eval_econtext;
4143 CachedPlanSource *plansource;
4145 ParamListInfo paramLI;
4147 Snapshot saveActiveSnapshot;
4150 * Forget it if expression wasn't simple before.
4152 if (expr->expr_simple_expr == NULL)
4156 * Revalidate cached plan, so that we will notice if it became stale. (We
4157 * also need to hold a refcount while using the plan.) Note that even if
4158 * replanning occurs, the length of plancache_list can't change, since it
4159 * is a property of the raw parsetree generated from the query text.
4161 Assert(list_length(expr->plan->plancache_list) == 1);
4162 plansource = (CachedPlanSource *) linitial(expr->plan->plancache_list);
4163 cplan = RevalidateCachedPlan(plansource, true);
4164 if (cplan->generation != expr->expr_simple_generation)
4166 /* It got replanned ... is it still simple? */
4167 exec_simple_check_plan(expr);
4168 if (expr->expr_simple_expr == NULL)
4170 /* Ooops, release refcount and fail */
4171 ReleaseCachedPlan(cplan, true);
4177 * Pass back previously-determined result type.
4179 *rettype = expr->expr_simple_type;
4182 * Prepare the expression for execution, if it's not been done already in
4183 * the current eval_estate. (This will be forced to happen if we called
4184 * exec_simple_check_plan above.)
4186 if (expr->expr_simple_id != estate->eval_estate_simple_id)
4188 expr->expr_simple_state = ExecPrepareExpr(expr->expr_simple_expr,
4189 estate->eval_estate);
4190 expr->expr_simple_id = estate->eval_estate_simple_id;
4194 * Param list can live in econtext's temporary memory context.
4196 * XXX think about avoiding repeated palloc's for param lists? Beware
4197 * however that this routine is re-entrant: exec_eval_datum() can call it
4198 * back for subscript evaluation, and so there can be a need to have more
4199 * than one active param list.
4201 if (expr->nparams > 0)
4203 /* sizeof(ParamListInfoData) includes the first array element */
4204 paramLI = (ParamListInfo)
4205 MemoryContextAlloc(econtext->ecxt_per_tuple_memory,
4206 sizeof(ParamListInfoData) +
4207 (expr->nparams - 1) *sizeof(ParamExternData));
4208 paramLI->numParams = expr->nparams;
4210 for (i = 0; i < expr->nparams; i++)
4212 ParamExternData *prm = ¶mLI->params[i];
4213 PLpgSQL_datum *datum = estate->datums[expr->params[i]];
4216 exec_eval_datum(estate, datum, expr->plan_argtypes[i],
4218 &prm->value, &prm->isnull);
4225 * Now we can safely make the econtext point to the param list.
4227 econtext->ecxt_param_list_info = paramLI;
4230 * We have to do some of the things SPI_execute_plan would do, in
4231 * particular advance the snapshot if we are in a non-read-only function.
4232 * Without this, stable functions within the expression would fail to see
4233 * updates made so far by our own function.
4236 saveActiveSnapshot = ActiveSnapshot;
4240 MemoryContext oldcontext;
4242 oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
4243 if (!estate->readonly_func)
4245 CommandCounterIncrement();
4246 ActiveSnapshot = CopySnapshot(GetTransactionSnapshot());
4250 * Finally we can call the executor to evaluate the expression
4252 *result = ExecEvalExpr(expr->expr_simple_state,
4256 MemoryContextSwitchTo(oldcontext);
4260 /* Restore global vars and propagate error */
4261 ActiveSnapshot = saveActiveSnapshot;
4266 ActiveSnapshot = saveActiveSnapshot;
4270 * Now we can release our refcount on the cached plan.
4272 ReleaseCachedPlan(cplan, true);
4282 * exec_move_row Move one tuple's values into a record or row
4286 exec_move_row(PLpgSQL_execstate *estate,
4289 HeapTuple tup, TupleDesc tupdesc)
4292 * Record is simple - just copy the tuple and its descriptor into the
4298 * copy input first, just in case it is pointing at variable's value
4300 if (HeapTupleIsValid(tup))
4301 tup = heap_copytuple(tup);
4303 tupdesc = CreateTupleDescCopy(tupdesc);
4307 heap_freetuple(rec->tup);
4308 rec->freetup = false;
4310 if (rec->freetupdesc)
4312 FreeTupleDesc(rec->tupdesc);
4313 rec->freetupdesc = false;
4316 if (HeapTupleIsValid(tup))
4319 rec->freetup = true;
4323 /* If we have a tupdesc but no data, form an all-nulls tuple */
4326 nulls = (char *) palloc(tupdesc->natts * sizeof(char));
4327 memset(nulls, 'n', tupdesc->natts * sizeof(char));
4329 rec->tup = heap_formtuple(tupdesc, NULL, nulls);
4330 rec->freetup = true;
4339 rec->tupdesc = tupdesc;
4340 rec->freetupdesc = true;
4343 rec->tupdesc = NULL;
4349 * Row is a bit more complicated in that we assign the individual
4350 * attributes of the tuple to the variables the row points to.
4352 * NOTE: this code used to demand row->nfields ==
4353 * HeapTupleHeaderGetNatts(tup->t_data, but that's wrong. The tuple might
4354 * have more fields than we expected if it's from an inheritance-child
4355 * table of the current table, or it might have fewer if the table has had
4356 * columns added by ALTER TABLE. Ignore extra columns and assume NULL for
4357 * missing columns, the same as heap_getattr would do. We also have to
4358 * skip over dropped columns in either the source or destination.
4360 * If we have no tuple data at all, we'll assign NULL to all columns of
4369 if (HeapTupleIsValid(tup))
4370 t_natts = HeapTupleHeaderGetNatts(tup->t_data);
4375 for (fnum = 0; fnum < row->nfields; fnum++)
4382 if (row->varnos[fnum] < 0)
4383 continue; /* skip dropped column in row struct */
4385 var = (PLpgSQL_var *) (estate->datums[row->varnos[fnum]]);
4387 while (anum < t_natts && tupdesc->attrs[anum]->attisdropped)
4388 anum++; /* skip dropped column in tuple */
4392 value = SPI_getbinval(tup, tupdesc, anum + 1, &isnull);
4393 valtype = SPI_gettypeid(tupdesc, anum + 1);
4400 valtype = InvalidOid;
4403 exec_assign_value(estate, (PLpgSQL_datum *) var,
4404 value, valtype, &isnull);
4410 elog(ERROR, "unsupported target");
4414 * make_tuple_from_row Make a tuple from the values of a row object
4416 * A NULL return indicates rowtype mismatch; caller must raise suitable error
4420 make_tuple_from_row(PLpgSQL_execstate *estate,
4424 int natts = tupdesc->natts;
4430 if (natts != row->nfields)
4433 dvalues = (Datum *) palloc0(natts * sizeof(Datum));
4434 nulls = (bool *) palloc(natts * sizeof(bool));
4436 for (i = 0; i < natts; i++)
4440 if (tupdesc->attrs[i]->attisdropped)
4442 nulls[i] = true; /* leave the column as null */
4445 if (row->varnos[i] < 0) /* should not happen */
4446 elog(ERROR, "dropped rowtype entry for non-dropped column");
4448 exec_eval_datum(estate, estate->datums[row->varnos[i]],
4449 InvalidOid, &fieldtypeid, &dvalues[i], &nulls[i]);
4450 if (fieldtypeid != tupdesc->attrs[i]->atttypid)
4454 tuple = heap_form_tuple(tupdesc, dvalues, nulls);
4463 * convert_value_to_string Convert a non-null Datum to C string
4465 * Note: callers generally assume that the result is a palloc'd string and
4466 * should be pfree'd. This is not all that safe an assumption ...
4468 * Note: not caching the conversion function lookup is bad for performance.
4472 convert_value_to_string(Datum value, Oid valtype)
4478 getTypeOutputInfo(valtype, &typoutput, &typIsVarlena);
4481 * We do SPI_push to allow the datatype output function to use SPI.
4482 * However we do not mess around with CommandCounterIncrement or advancing
4483 * the snapshot, which means that a stable output function would not see
4484 * updates made so far by our own function. The use-case for such
4485 * scenarios seems too narrow to justify the cycles that would be
4490 str = OidOutputFunctionCall(typoutput, value);
4498 * exec_cast_value Cast a value if required
4502 exec_cast_value(Datum value, Oid valtype,
4510 * If the type of the queries return value isn't that of the variable,
4513 if (valtype != reqtype || reqtypmod != -1)
4519 extval = convert_value_to_string(value, valtype);
4521 /* Allow input function to use SPI ... see notes above */
4524 value = InputFunctionCall(reqinput, extval,
4525 reqtypioparam, reqtypmod);
4535 value = InputFunctionCall(reqinput, NULL,
4536 reqtypioparam, reqtypmod);
4546 * exec_simple_cast_value Cast a value if required
4548 * As above, but need not supply details about target type. Note that this
4549 * is slower than exec_cast_value with cached type info, and so should be
4550 * avoided in heavily used code paths.
4554 exec_simple_cast_value(Datum value, Oid valtype,
4555 Oid reqtype, int32 reqtypmod,
4560 if (valtype != reqtype || reqtypmod != -1)
4564 FmgrInfo finfo_input;
4566 getTypeInputInfo(reqtype, &typinput, &typioparam);
4568 fmgr_info(typinput, &finfo_input);
4570 value = exec_cast_value(value,
4585 * exec_simple_check_node - Recursively check if an expression
4586 * is made only of simple things we can
4587 * hand out directly to ExecEvalExpr()
4588 * instead of calling SPI.
4592 exec_simple_check_node(Node *node)
4597 switch (nodeTag(node))
4607 ArrayRef *expr = (ArrayRef *) node;
4609 if (!exec_simple_check_node((Node *) expr->refupperindexpr))
4611 if (!exec_simple_check_node((Node *) expr->reflowerindexpr))
4613 if (!exec_simple_check_node((Node *) expr->refexpr))
4615 if (!exec_simple_check_node((Node *) expr->refassgnexpr))
4623 FuncExpr *expr = (FuncExpr *) node;
4625 if (expr->funcretset)
4627 if (!exec_simple_check_node((Node *) expr->args))
4635 OpExpr *expr = (OpExpr *) node;
4639 if (!exec_simple_check_node((Node *) expr->args))
4645 case T_DistinctExpr:
4647 DistinctExpr *expr = (DistinctExpr *) node;
4651 if (!exec_simple_check_node((Node *) expr->args))
4657 case T_ScalarArrayOpExpr:
4659 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
4661 if (!exec_simple_check_node((Node *) expr->args))
4669 BoolExpr *expr = (BoolExpr *) node;
4671 if (!exec_simple_check_node((Node *) expr->args))
4678 return exec_simple_check_node((Node *) ((FieldSelect *) node)->arg);
4682 FieldStore *expr = (FieldStore *) node;
4684 if (!exec_simple_check_node((Node *) expr->arg))
4686 if (!exec_simple_check_node((Node *) expr->newvals))
4693 return exec_simple_check_node((Node *) ((RelabelType *) node)->arg);
4696 return exec_simple_check_node((Node *) ((CoerceViaIO *) node)->arg);
4698 case T_ArrayCoerceExpr:
4699 return exec_simple_check_node((Node *) ((ArrayCoerceExpr *) node)->arg);
4701 case T_ConvertRowtypeExpr:
4702 return exec_simple_check_node((Node *) ((ConvertRowtypeExpr *) node)->arg);
4706 CaseExpr *expr = (CaseExpr *) node;
4708 if (!exec_simple_check_node((Node *) expr->arg))
4710 if (!exec_simple_check_node((Node *) expr->args))
4712 if (!exec_simple_check_node((Node *) expr->defresult))
4720 CaseWhen *when = (CaseWhen *) node;
4722 if (!exec_simple_check_node((Node *) when->expr))
4724 if (!exec_simple_check_node((Node *) when->result))
4730 case T_CaseTestExpr:
4735 ArrayExpr *expr = (ArrayExpr *) node;
4737 if (!exec_simple_check_node((Node *) expr->elements))
4745 RowExpr *expr = (RowExpr *) node;
4747 if (!exec_simple_check_node((Node *) expr->args))
4753 case T_RowCompareExpr:
4755 RowCompareExpr *expr = (RowCompareExpr *) node;
4757 if (!exec_simple_check_node((Node *) expr->largs))
4759 if (!exec_simple_check_node((Node *) expr->rargs))
4765 case T_CoalesceExpr:
4767 CoalesceExpr *expr = (CoalesceExpr *) node;
4769 if (!exec_simple_check_node((Node *) expr->args))
4777 MinMaxExpr *expr = (MinMaxExpr *) node;
4779 if (!exec_simple_check_node((Node *) expr->args))
4787 XmlExpr *expr = (XmlExpr *) node;
4789 if (!exec_simple_check_node((Node *) expr->named_args))
4791 if (!exec_simple_check_node((Node *) expr->args))
4799 NullIfExpr *expr = (NullIfExpr *) node;
4803 if (!exec_simple_check_node((Node *) expr->args))
4810 return exec_simple_check_node((Node *) ((NullTest *) node)->arg);
4813 return exec_simple_check_node((Node *) ((BooleanTest *) node)->arg);
4815 case T_CoerceToDomain:
4816 return exec_simple_check_node((Node *) ((CoerceToDomain *) node)->arg);
4818 case T_CoerceToDomainValue:
4823 List *expr = (List *) node;
4828 if (!exec_simple_check_node(lfirst(l)))
4842 * exec_simple_check_plan - Check if a plan is simple enough to
4843 * be evaluated by ExecEvalExpr() instead
4848 exec_simple_check_plan(PLpgSQL_expr *expr)
4850 CachedPlanSource *plansource;
4856 * Initialize to "not simple", and remember the plan generation number we
4857 * last checked. (If the query produces more or less than one parsetree
4858 * we just leave expr_simple_generation set to 0.)
4860 expr->expr_simple_expr = NULL;
4861 expr->expr_simple_generation = 0;
4864 * 1. We can only evaluate queries that resulted in one single execution
4867 if (list_length(expr->plan->plancache_list) != 1)
4869 plansource = (CachedPlanSource *) linitial(expr->plan->plancache_list);
4870 expr->expr_simple_generation = plansource->generation;
4871 if (list_length(plansource->plan->stmt_list) != 1)
4874 stmt = (PlannedStmt *) linitial(plansource->plan->stmt_list);
4877 * 2. It must be a RESULT plan --> no scan's required
4879 if (!IsA(stmt, PlannedStmt))
4881 plan = stmt->planTree;
4882 if (!IsA(plan, Result))
4886 * 3. Can't have any subplan or qual clause, either
4888 if (plan->lefttree != NULL ||
4889 plan->righttree != NULL ||
4890 plan->initPlan != NULL ||
4891 plan->qual != NULL ||
4892 ((Result *) plan)->resconstantqual != NULL)
4896 * 4. The plan must have a single attribute as result
4898 if (list_length(plan->targetlist) != 1)
4901 tle = (TargetEntry *) linitial(plan->targetlist);
4904 * 5. Check that all the nodes in the expression are non-scary.
4906 if (!exec_simple_check_node((Node *) tle->expr))
4910 * Yes - this is a simple expression. Mark it as such, and initialize
4911 * state to "not valid in current transaction".
4913 expr->expr_simple_expr = tle->expr;
4914 expr->expr_simple_state = NULL;
4915 expr->expr_simple_id = -1;
4916 /* Also stash away the expression result type */
4917 expr->expr_simple_type = exprType((Node *) tle->expr);
4921 * Check two tupledescs have matching number and types of attributes
4924 compatible_tupdesc(TupleDesc td1, TupleDesc td2)
4928 if (td1->natts != td2->natts)
4931 for (i = 0; i < td1->natts; i++)
4933 if (td1->attrs[i]->atttypid != td2->attrs[i]->atttypid)
4941 * exec_set_found Set the global found variable
4946 exec_set_found(PLpgSQL_execstate *estate, bool state)
4950 var = (PLpgSQL_var *) (estate->datums[estate->found_varno]);
4951 var->value = (Datum) state;
4952 var->isnull = false;
4956 * plpgsql_create_econtext --- create an eval_econtext for the current function
4958 * We may need to create a new eval_estate too, if there's not one already
4959 * for the current (sub) transaction. The EState will be cleaned up at
4960 * (sub) transaction end.
4963 plpgsql_create_econtext(PLpgSQL_execstate *estate)
4965 SubTransactionId my_subxid = GetCurrentSubTransactionId();
4966 SimpleEstateStackEntry *entry = simple_estate_stack;
4968 /* Create new EState if not one for current subxact */
4969 if (entry == NULL ||
4970 entry->xact_subxid != my_subxid)
4972 MemoryContext oldcontext;
4974 /* Stack entries are kept in TopTransactionContext for simplicity */
4975 entry = (SimpleEstateStackEntry *)
4976 MemoryContextAlloc(TopTransactionContext,
4977 sizeof(SimpleEstateStackEntry));
4979 /* But each EState should be a child of its CurTransactionContext */
4980 oldcontext = MemoryContextSwitchTo(CurTransactionContext);
4981 entry->xact_eval_estate = CreateExecutorState();
4982 MemoryContextSwitchTo(oldcontext);
4984 /* Assign a reasonably-unique ID to this EState */
4985 entry->xact_estate_simple_id = simple_estate_id_counter++;
4986 entry->xact_subxid = my_subxid;
4988 entry->next = simple_estate_stack;
4989 simple_estate_stack = entry;
4992 /* Link plpgsql estate to it */
4993 estate->eval_estate = entry->xact_eval_estate;
4994 estate->eval_estate_simple_id = entry->xact_estate_simple_id;
4996 /* And create a child econtext for the current function */
4997 estate->eval_econtext = CreateExprContext(estate->eval_estate);
5001 * plpgsql_xact_cb --- post-transaction-commit-or-abort cleanup
5003 * If a simple-expression EState was created in the current transaction,
5004 * it has to be cleaned up.
5007 plpgsql_xact_cb(XactEvent event, void *arg)
5010 * If we are doing a clean transaction shutdown, free the EState (so that
5011 * any remaining resources will be released correctly). In an abort, we
5012 * expect the regular abort recovery procedures to release everything of
5013 * interest. We don't need to free the individual stack entries since
5014 * TopTransactionContext is about to go away anyway.
5016 * Note: if plpgsql_subxact_cb is doing its job, there should be at most
5017 * one stack entry, but we may as well code this as a loop.
5019 if (event != XACT_EVENT_ABORT)
5021 while (simple_estate_stack != NULL)
5023 FreeExecutorState(simple_estate_stack->xact_eval_estate);
5024 simple_estate_stack = simple_estate_stack->next;
5028 simple_estate_stack = NULL;
5032 * plpgsql_subxact_cb --- post-subtransaction-commit-or-abort cleanup
5034 * If a simple-expression EState was created in the current subtransaction,
5035 * it has to be cleaned up.
5038 plpgsql_subxact_cb(SubXactEvent event, SubTransactionId mySubid,
5039 SubTransactionId parentSubid, void *arg)
5041 if (event == SUBXACT_EVENT_START_SUB)
5044 if (simple_estate_stack != NULL &&
5045 simple_estate_stack->xact_subxid == mySubid)
5047 SimpleEstateStackEntry *next;
5049 if (event == SUBXACT_EVENT_COMMIT_SUB)
5050 FreeExecutorState(simple_estate_stack->xact_eval_estate);
5051 next = simple_estate_stack->next;
5052 pfree(simple_estate_stack);
5053 simple_estate_stack = next;
5058 * free_var --- pfree any pass-by-reference value of the variable.
5060 * This should always be followed by some assignment to var->value,
5061 * as it leaves a dangling pointer.
5064 free_var(PLpgSQL_var *var)
5068 pfree(DatumGetPointer(var->value));
5069 var->freeval = false;