1 /**********************************************************************
2 * pl_exec.c - Executor for the PL/pgSQL
6 * $PostgreSQL: pgsql/src/pl/plpgsql/src/pl_exec.c,v 1.158 2005/12/28 01:30:01 tgl Exp $
8 * This software is copyrighted by Jan Wieck - Hamburg.
10 * The author hereby grants permission to use, copy, modify,
11 * distribute, and license this software and its documentation
12 * for any purpose, provided that existing copyright notices are
13 * retained in all copies and that this notice is included
14 * verbatim in any distributions. No written agreement, license,
15 * or royalty fee is required for any of the authorized uses.
16 * Modifications to this software may be copyrighted by their
17 * author and need not follow the licensing terms described
18 * here, provided that the new terms are clearly indicated on
19 * the first page of each file where they apply.
21 * IN NO EVENT SHALL THE AUTHOR OR DISTRIBUTORS BE LIABLE TO ANY
22 * PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR
23 * CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS
24 * SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN
25 * IF THE AUTHOR HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH
28 * THE AUTHOR AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY
29 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
30 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
31 * PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON
32 * AN "AS IS" BASIS, AND THE AUTHOR AND DISTRIBUTORS HAVE NO
33 * OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES,
34 * ENHANCEMENTS, OR MODIFICATIONS.
36 **********************************************************************/
43 #include "access/heapam.h"
44 #include "catalog/pg_proc.h"
45 #include "catalog/pg_type.h"
46 #include "executor/spi_priv.h"
48 #include "optimizer/clauses.h"
49 #include "parser/parse_expr.h"
50 #include "tcop/tcopprot.h"
51 #include "utils/array.h"
52 #include "utils/builtins.h"
53 #include "utils/lsyscache.h"
54 #include "utils/memutils.h"
55 #include "utils/typcache.h"
58 static const char *const raise_skip_msg = "RAISE";
62 * All plpgsql function executions within a single transaction share
63 * the same executor EState for evaluating "simple" expressions. Each
64 * function call creates its own "eval_econtext" ExprContext within this
65 * estate. We destroy the estate at transaction shutdown to ensure there
66 * is no permanent leakage of memory (especially for xact abort case).
68 * If a simple PLpgSQL_expr has been used in the current xact, it is
69 * linked into the active_simple_exprs list.
71 static EState *simple_eval_estate = NULL;
72 static PLpgSQL_expr *active_simple_exprs = NULL;
74 /************************************************************
75 * Local function forward declarations
76 ************************************************************/
77 static void plpgsql_exec_error_callback(void *arg);
78 static PLpgSQL_datum *copy_plpgsql_datum(PLpgSQL_datum *datum);
80 static int exec_stmt_block(PLpgSQL_execstate *estate,
81 PLpgSQL_stmt_block *block);
82 static int exec_stmts(PLpgSQL_execstate *estate,
84 static int exec_stmt(PLpgSQL_execstate *estate,
86 static int exec_stmt_assign(PLpgSQL_execstate *estate,
87 PLpgSQL_stmt_assign *stmt);
88 static int exec_stmt_perform(PLpgSQL_execstate *estate,
89 PLpgSQL_stmt_perform *stmt);
90 static int exec_stmt_getdiag(PLpgSQL_execstate *estate,
91 PLpgSQL_stmt_getdiag *stmt);
92 static int exec_stmt_if(PLpgSQL_execstate *estate,
93 PLpgSQL_stmt_if *stmt);
94 static int exec_stmt_loop(PLpgSQL_execstate *estate,
95 PLpgSQL_stmt_loop *stmt);
96 static int exec_stmt_while(PLpgSQL_execstate *estate,
97 PLpgSQL_stmt_while *stmt);
98 static int exec_stmt_fori(PLpgSQL_execstate *estate,
99 PLpgSQL_stmt_fori *stmt);
100 static int exec_stmt_fors(PLpgSQL_execstate *estate,
101 PLpgSQL_stmt_fors *stmt);
102 static int exec_stmt_select(PLpgSQL_execstate *estate,
103 PLpgSQL_stmt_select *stmt);
104 static int exec_stmt_open(PLpgSQL_execstate *estate,
105 PLpgSQL_stmt_open *stmt);
106 static int exec_stmt_fetch(PLpgSQL_execstate *estate,
107 PLpgSQL_stmt_fetch *stmt);
108 static int exec_stmt_close(PLpgSQL_execstate *estate,
109 PLpgSQL_stmt_close *stmt);
110 static int exec_stmt_exit(PLpgSQL_execstate *estate,
111 PLpgSQL_stmt_exit *stmt);
112 static int exec_stmt_return(PLpgSQL_execstate *estate,
113 PLpgSQL_stmt_return *stmt);
114 static int exec_stmt_return_next(PLpgSQL_execstate *estate,
115 PLpgSQL_stmt_return_next *stmt);
116 static int exec_stmt_raise(PLpgSQL_execstate *estate,
117 PLpgSQL_stmt_raise *stmt);
118 static int exec_stmt_execsql(PLpgSQL_execstate *estate,
119 PLpgSQL_stmt_execsql *stmt);
120 static int exec_stmt_dynexecute(PLpgSQL_execstate *estate,
121 PLpgSQL_stmt_dynexecute *stmt);
122 static int exec_stmt_dynfors(PLpgSQL_execstate *estate,
123 PLpgSQL_stmt_dynfors *stmt);
125 static void plpgsql_estate_setup(PLpgSQL_execstate *estate,
126 PLpgSQL_function *func,
128 static void exec_eval_cleanup(PLpgSQL_execstate *estate);
130 static void exec_prepare_plan(PLpgSQL_execstate *estate,
132 static bool exec_simple_check_node(Node *node);
133 static void exec_simple_check_plan(PLpgSQL_expr *expr);
134 static Datum exec_eval_simple_expr(PLpgSQL_execstate *estate,
139 static void exec_assign_expr(PLpgSQL_execstate *estate,
140 PLpgSQL_datum *target,
142 static void exec_assign_value(PLpgSQL_execstate *estate,
143 PLpgSQL_datum *target,
144 Datum value, Oid valtype, bool *isNull);
145 static void exec_eval_datum(PLpgSQL_execstate *estate,
146 PLpgSQL_datum *datum,
151 static int exec_eval_integer(PLpgSQL_execstate *estate,
154 static bool exec_eval_boolean(PLpgSQL_execstate *estate,
157 static Datum exec_eval_expr(PLpgSQL_execstate *estate,
161 static int exec_run_select(PLpgSQL_execstate *estate,
162 PLpgSQL_expr *expr, long maxtuples, Portal *portalP);
163 static void exec_move_row(PLpgSQL_execstate *estate,
166 HeapTuple tup, TupleDesc tupdesc);
167 static HeapTuple make_tuple_from_row(PLpgSQL_execstate *estate,
170 static char *convert_value_to_string(Datum value, Oid valtype);
171 static Datum exec_cast_value(Datum value, Oid valtype,
177 static Datum exec_simple_cast_value(Datum value, Oid valtype,
178 Oid reqtype, int32 reqtypmod,
180 static void exec_init_tuple_store(PLpgSQL_execstate *estate);
181 static bool compatible_tupdesc(TupleDesc td1, TupleDesc td2);
182 static void exec_set_found(PLpgSQL_execstate *estate, bool state);
183 static void free_var(PLpgSQL_var *var);
187 * plpgsql_exec_function Called by the call handler for
188 * function execution.
192 plpgsql_exec_function(PLpgSQL_function *func, FunctionCallInfo fcinfo)
194 PLpgSQL_execstate estate;
195 ErrorContextCallback plerrcontext;
200 * Setup the execution state
202 plpgsql_estate_setup(&estate, func, (ReturnSetInfo *) fcinfo->resultinfo);
205 * Setup error traceback support for ereport()
207 plerrcontext.callback = plpgsql_exec_error_callback;
208 plerrcontext.arg = &estate;
209 plerrcontext.previous = error_context_stack;
210 error_context_stack = &plerrcontext;
213 * Make local execution copies of all the datums
215 estate.err_text = gettext_noop("during initialization of execution state");
216 for (i = 0; i < estate.ndatums; i++)
217 estate.datums[i] = copy_plpgsql_datum(func->datums[i]);
220 * Store the actual call argument values into the appropriate variables
222 estate.err_text = gettext_noop("while storing call arguments into local variables");
223 for (i = 0; i < func->fn_nargs; i++)
225 int n = func->fn_argvarnos[i];
227 switch (estate.datums[n]->dtype)
229 case PLPGSQL_DTYPE_VAR:
231 PLpgSQL_var *var = (PLpgSQL_var *) estate.datums[n];
233 var->value = fcinfo->arg[i];
234 var->isnull = fcinfo->argnull[i];
235 var->freeval = false;
239 case PLPGSQL_DTYPE_ROW:
241 PLpgSQL_row *row = (PLpgSQL_row *) estate.datums[n];
243 if (!fcinfo->argnull[i])
249 HeapTupleData tmptup;
251 td = DatumGetHeapTupleHeader(fcinfo->arg[i]);
252 /* Extract rowtype info and find a tupdesc */
253 tupType = HeapTupleHeaderGetTypeId(td);
254 tupTypmod = HeapTupleHeaderGetTypMod(td);
255 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
256 /* Build a temporary HeapTuple control structure */
257 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
258 ItemPointerSetInvalid(&(tmptup.t_self));
259 tmptup.t_tableOid = InvalidOid;
261 exec_move_row(&estate, NULL, row, &tmptup, tupdesc);
265 /* If arg is null, treat it as an empty row */
266 exec_move_row(&estate, NULL, row, NULL, NULL);
272 elog(ERROR, "unrecognized dtype: %d", func->datums[i]->dtype);
277 * Set the magic variable FOUND to false
279 exec_set_found(&estate, false);
282 * Now call the toplevel block of statements
284 estate.err_text = NULL;
285 estate.err_stmt = (PLpgSQL_stmt *) (func->action);
286 rc = exec_stmt_block(&estate, func->action);
287 if (rc != PLPGSQL_RC_RETURN)
289 estate.err_stmt = NULL;
290 estate.err_text = NULL;
293 * Provide a more helpful message if a CONTINUE has been used outside
296 if (rc == PLPGSQL_RC_CONTINUE)
298 (errcode(ERRCODE_SYNTAX_ERROR),
299 errmsg("CONTINUE cannot be used outside a loop")));
302 (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
303 errmsg("control reached end of function without RETURN")));
307 * We got a return value - process it
309 estate.err_stmt = NULL;
310 estate.err_text = gettext_noop("while casting return value to function's return type");
312 fcinfo->isnull = estate.retisnull;
316 ReturnSetInfo *rsi = estate.rsi;
318 /* Check caller can handle a set result */
319 if (!rsi || !IsA(rsi, ReturnSetInfo) ||
320 (rsi->allowedModes & SFRM_Materialize) == 0)
322 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
323 errmsg("set-valued function called in context that cannot accept a set")));
324 rsi->returnMode = SFRM_Materialize;
326 /* If we produced any tuples, send back the result */
327 if (estate.tuple_store)
329 rsi->setResult = estate.tuple_store;
330 if (estate.rettupdesc)
332 MemoryContext oldcxt;
334 oldcxt = MemoryContextSwitchTo(estate.tuple_store_cxt);
335 rsi->setDesc = CreateTupleDescCopy(estate.rettupdesc);
336 MemoryContextSwitchTo(oldcxt);
339 estate.retval = (Datum) 0;
340 fcinfo->isnull = true;
342 else if (!estate.retisnull)
344 if (estate.retistuple)
346 /* Copy tuple to upper executor memory, as a tuple Datum */
348 PointerGetDatum(SPI_returntuple((HeapTuple) (estate.retval),
353 /* Cast value to proper type */
354 estate.retval = exec_cast_value(estate.retval, estate.rettype,
356 &(func->fn_retinput),
357 func->fn_rettypioparam,
362 * If the function's return type isn't by value, copy the value
363 * into upper executor memory context.
365 if (!fcinfo->isnull && !func->fn_retbyval)
370 len = datumGetSize(estate.retval, false, func->fn_rettyplen);
371 tmp = (void *) SPI_palloc(len);
372 memcpy(tmp, DatumGetPointer(estate.retval), len);
373 estate.retval = PointerGetDatum(tmp);
378 /* Clean up any leftover temporary memory */
379 if (estate.eval_econtext != NULL)
380 FreeExprContext(estate.eval_econtext);
381 estate.eval_econtext = NULL;
382 exec_eval_cleanup(&estate);
385 * Pop the error context stack
387 error_context_stack = plerrcontext.previous;
390 * Return the function's result
392 return estate.retval;
397 * plpgsql_exec_trigger Called by the call handler for
402 plpgsql_exec_trigger(PLpgSQL_function *func,
403 TriggerData *trigdata)
405 PLpgSQL_execstate estate;
406 ErrorContextCallback plerrcontext;
410 PLpgSQL_rec *rec_new,
415 * Setup the execution state
417 plpgsql_estate_setup(&estate, func, NULL);
420 * Setup error traceback support for ereport()
422 plerrcontext.callback = plpgsql_exec_error_callback;
423 plerrcontext.arg = &estate;
424 plerrcontext.previous = error_context_stack;
425 error_context_stack = &plerrcontext;
428 * Make local execution copies of all the datums
430 estate.err_text = gettext_noop("during initialization of execution state");
431 for (i = 0; i < estate.ndatums; i++)
432 estate.datums[i] = copy_plpgsql_datum(func->datums[i]);
435 * Put the OLD and NEW tuples into record variables
437 rec_new = (PLpgSQL_rec *) (estate.datums[func->new_varno]);
438 rec_new->freetup = false;
439 rec_new->freetupdesc = false;
440 rec_old = (PLpgSQL_rec *) (estate.datums[func->old_varno]);
441 rec_old->freetup = false;
442 rec_old->freetupdesc = false;
444 if (TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
447 * Per-statement triggers don't use OLD/NEW variables
450 rec_new->tupdesc = NULL;
452 rec_old->tupdesc = NULL;
454 else if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
456 rec_new->tup = trigdata->tg_trigtuple;
457 rec_new->tupdesc = trigdata->tg_relation->rd_att;
459 rec_old->tupdesc = NULL;
461 else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
463 rec_new->tup = trigdata->tg_newtuple;
464 rec_new->tupdesc = trigdata->tg_relation->rd_att;
465 rec_old->tup = trigdata->tg_trigtuple;
466 rec_old->tupdesc = trigdata->tg_relation->rd_att;
468 else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
471 rec_new->tupdesc = NULL;
472 rec_old->tup = trigdata->tg_trigtuple;
473 rec_old->tupdesc = trigdata->tg_relation->rd_att;
476 elog(ERROR, "unrecognized trigger action: not INSERT, DELETE, or UPDATE");
479 * Assign the special tg_ variables
482 var = (PLpgSQL_var *) (estate.datums[func->tg_op_varno]);
483 if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
484 var->value = DirectFunctionCall1(textin, CStringGetDatum("INSERT"));
485 else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
486 var->value = DirectFunctionCall1(textin, CStringGetDatum("UPDATE"));
487 else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
488 var->value = DirectFunctionCall1(textin, CStringGetDatum("DELETE"));
490 elog(ERROR, "unrecognized trigger action: not INSERT, DELETE, or UPDATE");
494 var = (PLpgSQL_var *) (estate.datums[func->tg_name_varno]);
495 var->value = DirectFunctionCall1(namein,
496 CStringGetDatum(trigdata->tg_trigger->tgname));
500 var = (PLpgSQL_var *) (estate.datums[func->tg_when_varno]);
501 if (TRIGGER_FIRED_BEFORE(trigdata->tg_event))
502 var->value = DirectFunctionCall1(textin, CStringGetDatum("BEFORE"));
503 else if (TRIGGER_FIRED_AFTER(trigdata->tg_event))
504 var->value = DirectFunctionCall1(textin, CStringGetDatum("AFTER"));
506 elog(ERROR, "unrecognized trigger execution time: not BEFORE or AFTER");
510 var = (PLpgSQL_var *) (estate.datums[func->tg_level_varno]);
511 if (TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
512 var->value = DirectFunctionCall1(textin, CStringGetDatum("ROW"));
513 else if (TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
514 var->value = DirectFunctionCall1(textin, CStringGetDatum("STATEMENT"));
516 elog(ERROR, "unrecognized trigger event type: not ROW or STATEMENT");
520 var = (PLpgSQL_var *) (estate.datums[func->tg_relid_varno]);
521 var->value = ObjectIdGetDatum(trigdata->tg_relation->rd_id);
523 var->freeval = false;
525 var = (PLpgSQL_var *) (estate.datums[func->tg_relname_varno]);
526 var->value = DirectFunctionCall1(namein,
527 CStringGetDatum(RelationGetRelationName(trigdata->tg_relation)));
531 var = (PLpgSQL_var *) (estate.datums[func->tg_nargs_varno]);
532 var->value = Int16GetDatum(trigdata->tg_trigger->tgnargs);
534 var->freeval = false;
537 * Store the trigger argument values into the special execution state
540 estate.err_text = gettext_noop("while storing call arguments into local variables");
541 estate.trig_nargs = trigdata->tg_trigger->tgnargs;
542 if (estate.trig_nargs == 0)
543 estate.trig_argv = NULL;
546 estate.trig_argv = palloc(sizeof(Datum) * estate.trig_nargs);
547 for (i = 0; i < trigdata->tg_trigger->tgnargs; i++)
548 estate.trig_argv[i] = DirectFunctionCall1(textin,
549 CStringGetDatum(trigdata->tg_trigger->tgargs[i]));
553 * Set the magic variable FOUND to false
555 exec_set_found(&estate, false);
558 * Now call the toplevel block of statements
560 estate.err_text = NULL;
561 estate.err_stmt = (PLpgSQL_stmt *) (func->action);
562 rc = exec_stmt_block(&estate, func->action);
563 if (rc != PLPGSQL_RC_RETURN)
565 estate.err_stmt = NULL;
566 estate.err_text = NULL;
569 * Provide a more helpful message if a CONTINUE has been used outside
572 if (rc == PLPGSQL_RC_CONTINUE)
574 (errcode(ERRCODE_SYNTAX_ERROR),
575 errmsg("CONTINUE cannot be used outside a loop")));
578 (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
579 errmsg("control reached end of trigger procedure without RETURN")));
584 (errcode(ERRCODE_DATATYPE_MISMATCH),
585 errmsg("trigger procedure cannot return a set")));
588 * Check that the returned tuple structure has the same attributes, the
589 * relation that fired the trigger has. A per-statement trigger always
590 * needs to return NULL, so we ignore any return value the function itself
591 * produces (XXX: is this a good idea?)
593 * XXX This way it is possible, that the trigger returns a tuple where
594 * attributes don't have the correct atttypmod's length. It's up to the
595 * trigger's programmer to ensure that this doesn't happen. Jan
597 if (estate.retisnull || TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
601 if (!compatible_tupdesc(estate.rettupdesc,
602 trigdata->tg_relation->rd_att))
604 (errcode(ERRCODE_DATATYPE_MISMATCH),
605 errmsg("returned tuple structure does not match table of trigger event")));
606 /* Copy tuple to upper executor memory */
607 rettup = SPI_copytuple((HeapTuple) (estate.retval));
610 /* Clean up any leftover temporary memory */
611 if (estate.eval_econtext != NULL)
612 FreeExprContext(estate.eval_econtext);
613 estate.eval_econtext = NULL;
614 exec_eval_cleanup(&estate);
617 * Pop the error context stack
619 error_context_stack = plerrcontext.previous;
622 * Return the trigger's result
629 * error context callback to let us supply a call-stack traceback
632 plpgsql_exec_error_callback(void *arg)
634 PLpgSQL_execstate *estate = (PLpgSQL_execstate *) arg;
636 /* safety check, shouldn't happen */
637 if (estate->err_func == NULL)
640 /* if we are doing RAISE, don't report its location */
641 if (estate->err_text == raise_skip_msg)
644 if (estate->err_stmt != NULL)
646 /* translator: last %s is a plpgsql statement type name */
647 errcontext("PL/pgSQL function \"%s\" line %d at %s",
648 estate->err_func->fn_name,
649 estate->err_stmt->lineno,
650 plpgsql_stmt_typename(estate->err_stmt));
652 else if (estate->err_text != NULL)
655 * We don't expend the cycles to run gettext() on err_text unless we
656 * actually need it. Therefore, places that set up err_text should
657 * use gettext_noop() to ensure the strings get recorded in the
658 * message dictionary.
662 * translator: last %s is a phrase such as "while storing call
663 * arguments into local variables"
665 errcontext("PL/pgSQL function \"%s\" %s",
666 estate->err_func->fn_name,
667 gettext(estate->err_text));
670 errcontext("PL/pgSQL function \"%s\"",
671 estate->err_func->fn_name);
676 * Support function for initializing local execution variables
679 static PLpgSQL_datum *
680 copy_plpgsql_datum(PLpgSQL_datum *datum)
682 PLpgSQL_datum *result;
684 switch (datum->dtype)
686 case PLPGSQL_DTYPE_VAR:
688 PLpgSQL_var *new = palloc(sizeof(PLpgSQL_var));
690 memcpy(new, datum, sizeof(PLpgSQL_var));
691 /* Ensure the value is null (possibly not needed?) */
694 new->freeval = false;
696 result = (PLpgSQL_datum *) new;
700 case PLPGSQL_DTYPE_REC:
702 PLpgSQL_rec *new = palloc(sizeof(PLpgSQL_rec));
704 memcpy(new, datum, sizeof(PLpgSQL_rec));
705 /* Ensure the value is null (possibly not needed?) */
708 new->freetup = false;
709 new->freetupdesc = false;
711 result = (PLpgSQL_datum *) new;
715 case PLPGSQL_DTYPE_ROW:
716 case PLPGSQL_DTYPE_RECFIELD:
717 case PLPGSQL_DTYPE_ARRAYELEM:
718 case PLPGSQL_DTYPE_TRIGARG:
721 * These datum records are read-only at runtime, so no need to
728 elog(ERROR, "unrecognized dtype: %d", datum->dtype);
729 result = NULL; /* keep compiler quiet */
738 exception_matches_conditions(ErrorData *edata, PLpgSQL_condition *cond)
740 for (; cond != NULL; cond = cond->next)
742 int sqlerrstate = cond->sqlerrstate;
745 * OTHERS matches everything *except* query-canceled; if you're
746 * foolish enough, you can match that explicitly.
748 if (sqlerrstate == 0)
750 if (edata->sqlerrcode != ERRCODE_QUERY_CANCELED)
754 else if (edata->sqlerrcode == sqlerrstate)
756 /* Category match? */
757 else if (ERRCODE_IS_CATEGORY(sqlerrstate) &&
758 ERRCODE_TO_CATEGORY(edata->sqlerrcode) == sqlerrstate)
766 * exec_stmt_block Execute a block of statements
770 exec_stmt_block(PLpgSQL_execstate *estate, PLpgSQL_stmt_block *block)
772 volatile int rc = -1;
777 * First initialize all variables declared in this block
779 for (i = 0; i < block->n_initvars; i++)
781 n = block->initvarnos[i];
783 switch (estate->datums[n]->dtype)
785 case PLPGSQL_DTYPE_VAR:
787 PLpgSQL_var *var = (PLpgSQL_var *) (estate->datums[n]);
790 if (!var->isconst || var->isnull)
792 if (var->default_val == NULL)
794 var->value = (Datum) 0;
798 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
799 errmsg("variable \"%s\" declared NOT NULL cannot default to NULL",
804 exec_assign_expr(estate, (PLpgSQL_datum *) var,
811 case PLPGSQL_DTYPE_REC:
813 PLpgSQL_rec *rec = (PLpgSQL_rec *) (estate->datums[n]);
817 heap_freetuple(rec->tup);
818 FreeTupleDesc(rec->tupdesc);
819 rec->freetup = false;
827 case PLPGSQL_DTYPE_RECFIELD:
828 case PLPGSQL_DTYPE_ARRAYELEM:
832 elog(ERROR, "unrecognized dtype: %d",
833 estate->datums[n]->dtype);
837 if (block->exceptions)
840 * Execute the statements in the block's body inside a sub-transaction
842 MemoryContext oldcontext = CurrentMemoryContext;
843 ResourceOwner oldowner = CurrentResourceOwner;
845 BeginInternalSubTransaction(NULL);
846 /* Want to run statements inside function's memory context */
847 MemoryContextSwitchTo(oldcontext);
851 rc = exec_stmts(estate, block->body);
853 /* Commit the inner transaction, return to outer xact context */
854 ReleaseCurrentSubTransaction();
855 MemoryContextSwitchTo(oldcontext);
856 CurrentResourceOwner = oldowner;
859 * AtEOSubXact_SPI() should not have popped any SPI context, but
860 * just in case it did, make sure we remain connected.
862 SPI_restore_connection();
869 /* Save error info */
870 MemoryContextSwitchTo(oldcontext);
871 edata = CopyErrorData();
874 /* Abort the inner transaction */
875 RollbackAndReleaseCurrentSubTransaction();
876 MemoryContextSwitchTo(oldcontext);
877 CurrentResourceOwner = oldowner;
880 * If AtEOSubXact_SPI() popped any SPI context of the subxact, it
881 * will have left us in a disconnected state. We need this hack
882 * to return to connected state.
884 SPI_restore_connection();
886 /* Look for a matching exception handler */
887 foreach(e, block->exceptions->exc_list)
889 PLpgSQL_exception *exception = (PLpgSQL_exception *) lfirst(e);
891 if (exception_matches_conditions(edata, exception->conditions))
894 * Initialize the magic SQLSTATE and SQLERRM variables for
895 * the exception block. We needn't do this until we have
896 * found a matching exception.
898 PLpgSQL_var *state_var;
899 PLpgSQL_var *errm_var;
901 state_var = (PLpgSQL_var *)
902 estate->datums[block->exceptions->sqlstate_varno];
903 state_var->value = DirectFunctionCall1(textin,
904 CStringGetDatum(unpack_sql_state(edata->sqlerrcode)));
905 state_var->freeval = true;
906 state_var->isnull = false;
908 errm_var = (PLpgSQL_var *)
909 estate->datums[block->exceptions->sqlerrm_varno];
910 errm_var->value = DirectFunctionCall1(textin,
911 CStringGetDatum(edata->message));
912 errm_var->freeval = true;
913 errm_var->isnull = false;
915 rc = exec_stmts(estate, exception->action);
923 /* If no match found, re-throw the error */
927 FreeErrorData(edata);
934 * Just execute the statements in the block's body
936 rc = exec_stmts(estate, block->body);
940 * Handle the return code.
945 case PLPGSQL_RC_CONTINUE:
946 case PLPGSQL_RC_RETURN:
949 case PLPGSQL_RC_EXIT:
950 if (estate->exitlabel == NULL)
951 return PLPGSQL_RC_OK;
952 if (block->label == NULL)
953 return PLPGSQL_RC_EXIT;
954 if (strcmp(block->label, estate->exitlabel))
955 return PLPGSQL_RC_EXIT;
956 estate->exitlabel = NULL;
957 return PLPGSQL_RC_OK;
960 elog(ERROR, "unrecognized rc: %d", rc);
963 return PLPGSQL_RC_OK;
968 * exec_stmts Iterate over a list of statements
969 * as long as their return code is OK
973 exec_stmts(PLpgSQL_execstate *estate, List *stmts)
980 * Ensure we do a CHECK_FOR_INTERRUPTS() even though there is no
981 * statement. This prevents hangup in a tight loop if, for instance,
982 * there is a LOOP construct with an empty body.
984 CHECK_FOR_INTERRUPTS();
985 return PLPGSQL_RC_OK;
990 PLpgSQL_stmt *stmt = (PLpgSQL_stmt *) lfirst(s);
991 int rc = exec_stmt(estate, stmt);
993 if (rc != PLPGSQL_RC_OK)
997 return PLPGSQL_RC_OK;
1002 * exec_stmt Distribute one statement to the statements
1003 * type specific execution function.
1007 exec_stmt(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
1009 PLpgSQL_stmt *save_estmt;
1012 save_estmt = estate->err_stmt;
1013 estate->err_stmt = stmt;
1015 CHECK_FOR_INTERRUPTS();
1017 switch (stmt->cmd_type)
1019 case PLPGSQL_STMT_BLOCK:
1020 rc = exec_stmt_block(estate, (PLpgSQL_stmt_block *) stmt);
1023 case PLPGSQL_STMT_ASSIGN:
1024 rc = exec_stmt_assign(estate, (PLpgSQL_stmt_assign *) stmt);
1027 case PLPGSQL_STMT_PERFORM:
1028 rc = exec_stmt_perform(estate, (PLpgSQL_stmt_perform *) stmt);
1031 case PLPGSQL_STMT_GETDIAG:
1032 rc = exec_stmt_getdiag(estate, (PLpgSQL_stmt_getdiag *) stmt);
1035 case PLPGSQL_STMT_IF:
1036 rc = exec_stmt_if(estate, (PLpgSQL_stmt_if *) stmt);
1039 case PLPGSQL_STMT_LOOP:
1040 rc = exec_stmt_loop(estate, (PLpgSQL_stmt_loop *) stmt);
1043 case PLPGSQL_STMT_WHILE:
1044 rc = exec_stmt_while(estate, (PLpgSQL_stmt_while *) stmt);
1047 case PLPGSQL_STMT_FORI:
1048 rc = exec_stmt_fori(estate, (PLpgSQL_stmt_fori *) stmt);
1051 case PLPGSQL_STMT_FORS:
1052 rc = exec_stmt_fors(estate, (PLpgSQL_stmt_fors *) stmt);
1055 case PLPGSQL_STMT_SELECT:
1056 rc = exec_stmt_select(estate, (PLpgSQL_stmt_select *) stmt);
1059 case PLPGSQL_STMT_EXIT:
1060 rc = exec_stmt_exit(estate, (PLpgSQL_stmt_exit *) stmt);
1063 case PLPGSQL_STMT_RETURN:
1064 rc = exec_stmt_return(estate, (PLpgSQL_stmt_return *) stmt);
1067 case PLPGSQL_STMT_RETURN_NEXT:
1068 rc = exec_stmt_return_next(estate, (PLpgSQL_stmt_return_next *) stmt);
1071 case PLPGSQL_STMT_RAISE:
1072 rc = exec_stmt_raise(estate, (PLpgSQL_stmt_raise *) stmt);
1075 case PLPGSQL_STMT_EXECSQL:
1076 rc = exec_stmt_execsql(estate, (PLpgSQL_stmt_execsql *) stmt);
1079 case PLPGSQL_STMT_DYNEXECUTE:
1080 rc = exec_stmt_dynexecute(estate, (PLpgSQL_stmt_dynexecute *) stmt);
1083 case PLPGSQL_STMT_DYNFORS:
1084 rc = exec_stmt_dynfors(estate, (PLpgSQL_stmt_dynfors *) stmt);
1087 case PLPGSQL_STMT_OPEN:
1088 rc = exec_stmt_open(estate, (PLpgSQL_stmt_open *) stmt);
1091 case PLPGSQL_STMT_FETCH:
1092 rc = exec_stmt_fetch(estate, (PLpgSQL_stmt_fetch *) stmt);
1095 case PLPGSQL_STMT_CLOSE:
1096 rc = exec_stmt_close(estate, (PLpgSQL_stmt_close *) stmt);
1100 estate->err_stmt = save_estmt;
1101 elog(ERROR, "unrecognized cmdtype: %d", stmt->cmd_type);
1104 estate->err_stmt = save_estmt;
1111 * exec_stmt_assign Evaluate an expression and
1112 * put the result into a variable.
1116 exec_stmt_assign(PLpgSQL_execstate *estate, PLpgSQL_stmt_assign *stmt)
1118 Assert(stmt->varno >= 0);
1120 exec_assign_expr(estate, estate->datums[stmt->varno], stmt->expr);
1122 return PLPGSQL_RC_OK;
1126 * exec_stmt_perform Evaluate query and discard result (but set
1127 * FOUND depending on whether at least one row
1132 exec_stmt_perform(PLpgSQL_execstate *estate, PLpgSQL_stmt_perform *stmt)
1134 PLpgSQL_expr *expr = stmt->expr;
1136 (void) exec_run_select(estate, expr, 0, NULL);
1137 exec_set_found(estate, (estate->eval_processed != 0));
1138 exec_eval_cleanup(estate);
1140 return PLPGSQL_RC_OK;
1144 * exec_stmt_getdiag Put internal PG information into
1145 * specified variables.
1149 exec_stmt_getdiag(PLpgSQL_execstate *estate, PLpgSQL_stmt_getdiag *stmt)
1153 foreach(lc, stmt->diag_items)
1155 PLpgSQL_diag_item *diag_item = (PLpgSQL_diag_item *) lfirst(lc);
1157 bool isnull = false;
1159 if (diag_item->target <= 0)
1162 var = estate->datums[diag_item->target];
1167 switch (diag_item->kind)
1169 case PLPGSQL_GETDIAG_ROW_COUNT:
1171 exec_assign_value(estate, var,
1172 UInt32GetDatum(estate->eval_processed),
1176 case PLPGSQL_GETDIAG_RESULT_OID:
1178 exec_assign_value(estate, var,
1179 ObjectIdGetDatum(estate->eval_lastoid),
1184 elog(ERROR, "unrecognized attribute request: %d",
1189 return PLPGSQL_RC_OK;
1193 * exec_stmt_if Evaluate a bool expression and
1194 * execute the true or false body
1199 exec_stmt_if(PLpgSQL_execstate *estate, PLpgSQL_stmt_if *stmt)
1204 value = exec_eval_boolean(estate, stmt->cond, &isnull);
1205 exec_eval_cleanup(estate);
1207 if (!isnull && value)
1209 if (stmt->true_body != NIL)
1210 return exec_stmts(estate, stmt->true_body);
1214 if (stmt->false_body != NIL)
1215 return exec_stmts(estate, stmt->false_body);
1218 return PLPGSQL_RC_OK;
1223 * exec_stmt_loop Loop over statements until
1228 exec_stmt_loop(PLpgSQL_execstate *estate, PLpgSQL_stmt_loop *stmt)
1232 int rc = exec_stmts(estate, stmt->body);
1239 case PLPGSQL_RC_EXIT:
1240 if (estate->exitlabel == NULL)
1241 return PLPGSQL_RC_OK;
1242 if (stmt->label == NULL)
1243 return PLPGSQL_RC_EXIT;
1244 if (strcmp(stmt->label, estate->exitlabel) != 0)
1245 return PLPGSQL_RC_EXIT;
1246 estate->exitlabel = NULL;
1247 return PLPGSQL_RC_OK;
1249 case PLPGSQL_RC_CONTINUE:
1250 if (estate->exitlabel == NULL)
1251 /* anonymous continue, so re-run the loop */
1253 else if (stmt->label != NULL &&
1254 strcmp(stmt->label, estate->exitlabel) == 0)
1255 /* label matches named continue, so re-run loop */
1256 estate->exitlabel = NULL;
1258 /* label doesn't match named continue, so propagate upward */
1259 return PLPGSQL_RC_CONTINUE;
1262 case PLPGSQL_RC_RETURN:
1263 return PLPGSQL_RC_RETURN;
1266 elog(ERROR, "unrecognized rc: %d", rc);
1270 return PLPGSQL_RC_OK;
1275 * exec_stmt_while Loop over statements as long
1276 * as an expression evaluates to
1277 * true or an exit occurs.
1281 exec_stmt_while(PLpgSQL_execstate *estate, PLpgSQL_stmt_while *stmt)
1289 value = exec_eval_boolean(estate, stmt->cond, &isnull);
1290 exec_eval_cleanup(estate);
1292 if (isnull || !value)
1295 rc = exec_stmts(estate, stmt->body);
1302 case PLPGSQL_RC_EXIT:
1303 if (estate->exitlabel == NULL)
1304 return PLPGSQL_RC_OK;
1305 if (stmt->label == NULL)
1306 return PLPGSQL_RC_EXIT;
1307 if (strcmp(stmt->label, estate->exitlabel))
1308 return PLPGSQL_RC_EXIT;
1309 estate->exitlabel = NULL;
1310 return PLPGSQL_RC_OK;
1312 case PLPGSQL_RC_CONTINUE:
1313 if (estate->exitlabel == NULL)
1314 /* anonymous continue, so re-run loop */
1316 else if (stmt->label != NULL &&
1317 strcmp(stmt->label, estate->exitlabel) == 0)
1318 /* label matches named continue, so re-run loop */
1319 estate->exitlabel = NULL;
1321 /* label doesn't match named continue, propagate upward */
1322 return PLPGSQL_RC_CONTINUE;
1325 case PLPGSQL_RC_RETURN:
1326 return PLPGSQL_RC_RETURN;
1329 elog(ERROR, "unrecognized rc: %d", rc);
1333 return PLPGSQL_RC_OK;
1338 * exec_stmt_fori Iterate an integer variable
1339 * from a lower to an upper value.
1340 * Loop can be left with exit.
1344 exec_stmt_fori(PLpgSQL_execstate *estate, PLpgSQL_stmt_fori *stmt)
1351 int rc = PLPGSQL_RC_OK;
1353 var = (PLpgSQL_var *) (estate->datums[stmt->var->varno]);
1356 * Get the value of the lower bound into the loop var
1358 value = exec_eval_expr(estate, stmt->lower, &isnull, &valtype);
1359 value = exec_cast_value(value, valtype, var->datatype->typoid,
1360 &(var->datatype->typinput),
1361 var->datatype->typioparam,
1362 var->datatype->atttypmod, isnull);
1365 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1366 errmsg("lower bound of FOR loop cannot be NULL")));
1368 var->isnull = false;
1369 exec_eval_cleanup(estate);
1372 * Get the value of the upper bound
1374 value = exec_eval_expr(estate, stmt->upper, &isnull, &valtype);
1375 value = exec_cast_value(value, valtype, var->datatype->typoid,
1376 &(var->datatype->typinput),
1377 var->datatype->typioparam,
1378 var->datatype->atttypmod, isnull);
1381 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1382 errmsg("upper bound of FOR loop cannot be NULL")));
1383 exec_eval_cleanup(estate);
1395 if ((int4) (var->value) < (int4) value)
1400 if ((int4) (var->value) > (int4) value)
1404 found = true; /* looped at least once */
1407 * Execute the statements
1409 rc = exec_stmts(estate, stmt->body);
1411 if (rc == PLPGSQL_RC_RETURN)
1412 break; /* return from function */
1413 else if (rc == PLPGSQL_RC_EXIT)
1415 if (estate->exitlabel == NULL)
1416 /* unlabelled exit, finish the current loop */
1418 else if (stmt->label != NULL &&
1419 strcmp(stmt->label, estate->exitlabel) == 0)
1421 /* labelled exit, matches the current stmt's label */
1422 estate->exitlabel = NULL;
1427 * otherwise, this is a labelled exit that does not match the
1428 * current statement's label, if any: return RC_EXIT so that the
1429 * EXIT continues to propagate up the stack.
1434 else if (rc == PLPGSQL_RC_CONTINUE)
1436 if (estate->exitlabel == NULL)
1437 /* anonymous continue, so re-run the current loop */
1439 else if (stmt->label != NULL &&
1440 strcmp(stmt->label, estate->exitlabel) == 0)
1442 /* label matches named continue, so re-run loop */
1443 estate->exitlabel = NULL;
1449 * otherwise, this is a named continue that does not match the
1450 * current statement's label, if any: return RC_CONTINUE so
1451 * that the CONTINUE will propagate up the stack.
1458 * Increase/decrease loop var
1467 * Set the FOUND variable to indicate the result of executing the loop
1468 * (namely, whether we looped one or more times). This must be set here so
1469 * that it does not interfere with the value of the FOUND variable inside
1470 * the loop processing itself.
1472 exec_set_found(estate, found);
1479 * exec_stmt_fors Execute a query, assign each
1480 * tuple to a record or row and
1481 * execute a group of statements
1486 exec_stmt_fors(PLpgSQL_execstate *estate, PLpgSQL_stmt_fors *stmt)
1488 PLpgSQL_rec *rec = NULL;
1489 PLpgSQL_row *row = NULL;
1490 SPITupleTable *tuptab;
1493 int rc = PLPGSQL_RC_OK;
1498 * Determine if we assign to a record or a row
1500 if (stmt->rec != NULL)
1501 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
1502 else if (stmt->row != NULL)
1503 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
1505 elog(ERROR, "unsupported target");
1508 * Open the implicit cursor for the statement and fetch the initial 10
1511 exec_run_select(estate, stmt->query, 0, &portal);
1513 SPI_cursor_fetch(portal, true, 10);
1514 tuptab = SPI_tuptable;
1518 * If the query didn't return any rows, set the target to NULL and return
1519 * with FOUND = false.
1522 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
1524 found = true; /* processed at least one tuple */
1531 for (i = 0; i < n; i++)
1534 * Assign the tuple to the target
1536 exec_move_row(estate, rec, row, tuptab->vals[i], tuptab->tupdesc);
1539 * Execute the statements
1541 rc = exec_stmts(estate, stmt->body);
1542 if (rc != PLPGSQL_RC_OK)
1544 if (rc == PLPGSQL_RC_EXIT)
1546 if (estate->exitlabel == NULL)
1547 /* unlabelled exit, finish the current loop */
1549 else if (stmt->label != NULL &&
1550 strcmp(stmt->label, estate->exitlabel) == 0)
1552 /* labelled exit, matches the current stmt's label */
1553 estate->exitlabel = NULL;
1558 * otherwise, we processed a labelled exit that does not
1559 * match the current statement's label, if any: return
1560 * RC_EXIT so that the EXIT continues to recurse upward.
1563 else if (rc == PLPGSQL_RC_CONTINUE)
1565 if (estate->exitlabel == NULL)
1567 /* anonymous continue, so re-run the current loop */
1571 else if (stmt->label != NULL &&
1572 strcmp(stmt->label, estate->exitlabel) == 0)
1574 /* label matches named continue, so re-run loop */
1576 estate->exitlabel = NULL;
1581 * otherwise, we processed a named continue that does not
1582 * match the current statement's label, if any: return
1583 * RC_CONTINUE so that the CONTINUE will propagate up the
1589 * We're aborting the loop, so cleanup and set FOUND. (This
1590 * code should match the code after the loop.)
1592 SPI_freetuptable(tuptab);
1593 SPI_cursor_close(portal);
1594 exec_set_found(estate, found);
1600 SPI_freetuptable(tuptab);
1603 * Fetch the next 50 tuples
1605 SPI_cursor_fetch(portal, true, 50);
1607 tuptab = SPI_tuptable;
1611 * Release last group of tuples
1613 SPI_freetuptable(tuptab);
1616 * Close the implicit cursor
1618 SPI_cursor_close(portal);
1621 * Set the FOUND variable to indicate the result of executing the loop
1622 * (namely, whether we looped one or more times). This must be set here so
1623 * that it does not interfere with the value of the FOUND variable inside
1624 * the loop processing itself.
1626 exec_set_found(estate, found);
1633 * exec_stmt_select Run a query and assign the first
1634 * row to a record or rowtype.
1638 exec_stmt_select(PLpgSQL_execstate *estate, PLpgSQL_stmt_select *stmt)
1640 PLpgSQL_rec *rec = NULL;
1641 PLpgSQL_row *row = NULL;
1642 SPITupleTable *tuptab;
1646 * Initialize the global found variable to false
1648 exec_set_found(estate, false);
1651 * Determine if we assign to a record or a row
1653 if (stmt->rec != NULL)
1654 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
1655 else if (stmt->row != NULL)
1656 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
1658 elog(ERROR, "unsupported target");
1663 exec_run_select(estate, stmt->query, 1, NULL);
1664 tuptab = estate->eval_tuptable;
1665 n = estate->eval_processed;
1668 * If the query didn't return any rows, set the target to NULL and return.
1672 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
1673 exec_eval_cleanup(estate);
1674 return PLPGSQL_RC_OK;
1678 * Put the result into the target and set found to true
1680 exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
1681 exec_set_found(estate, true);
1683 exec_eval_cleanup(estate);
1685 return PLPGSQL_RC_OK;
1690 * exec_stmt_exit Implements EXIT and CONTINUE
1692 * This begins the process of exiting / restarting a loop.
1696 exec_stmt_exit(PLpgSQL_execstate *estate, PLpgSQL_stmt_exit *stmt)
1699 * If the exit / continue has a condition, evaluate it
1701 if (stmt->cond != NULL)
1706 value = exec_eval_boolean(estate, stmt->cond, &isnull);
1707 exec_eval_cleanup(estate);
1708 if (isnull || value == false)
1709 return PLPGSQL_RC_OK;
1712 estate->exitlabel = stmt->label;
1714 return PLPGSQL_RC_EXIT;
1716 return PLPGSQL_RC_CONTINUE;
1721 * exec_stmt_return Evaluate an expression and start
1722 * returning from the function.
1726 exec_stmt_return(PLpgSQL_execstate *estate, PLpgSQL_stmt_return *stmt)
1729 * If processing a set-returning PL/PgSQL function, the final RETURN
1730 * indicates that the function is finished producing tuples. The rest of
1731 * the work will be done at the top level.
1733 if (estate->retisset)
1734 return PLPGSQL_RC_RETURN;
1736 /* initialize for null result (possibly a tuple) */
1737 estate->retval = (Datum) 0;
1738 estate->rettupdesc = NULL;
1739 estate->retisnull = true;
1741 if (stmt->retvarno >= 0)
1743 PLpgSQL_datum *retvar = estate->datums[stmt->retvarno];
1745 switch (retvar->dtype)
1747 case PLPGSQL_DTYPE_VAR:
1749 PLpgSQL_var *var = (PLpgSQL_var *) retvar;
1751 estate->retval = var->value;
1752 estate->retisnull = var->isnull;
1753 estate->rettype = var->datatype->typoid;
1757 case PLPGSQL_DTYPE_REC:
1759 PLpgSQL_rec *rec = (PLpgSQL_rec *) retvar;
1761 if (HeapTupleIsValid(rec->tup))
1763 estate->retval = (Datum) rec->tup;
1764 estate->rettupdesc = rec->tupdesc;
1765 estate->retisnull = false;
1770 case PLPGSQL_DTYPE_ROW:
1772 PLpgSQL_row *row = (PLpgSQL_row *) retvar;
1774 Assert(row->rowtupdesc);
1775 estate->retval = (Datum) make_tuple_from_row(estate, row,
1777 if (estate->retval == (Datum) NULL) /* should not happen */
1778 elog(ERROR, "row not compatible with its own tupdesc");
1779 estate->rettupdesc = row->rowtupdesc;
1780 estate->retisnull = false;
1785 elog(ERROR, "unrecognized dtype: %d", retvar->dtype);
1788 return PLPGSQL_RC_RETURN;
1791 if (stmt->expr != NULL)
1793 if (estate->retistuple)
1795 exec_run_select(estate, stmt->expr, 1, NULL);
1796 if (estate->eval_processed > 0)
1798 estate->retval = (Datum) estate->eval_tuptable->vals[0];
1799 estate->rettupdesc = estate->eval_tuptable->tupdesc;
1800 estate->retisnull = false;
1805 /* Normal case for scalar results */
1806 estate->retval = exec_eval_expr(estate, stmt->expr,
1807 &(estate->retisnull),
1808 &(estate->rettype));
1811 return PLPGSQL_RC_RETURN;
1815 * Special hack for function returning VOID: instead of NULL, return a
1816 * non-null VOID value. This is of dubious importance but is kept for
1817 * backwards compatibility. Note that the only other way to get here is
1818 * to have written "RETURN NULL" in a function returning tuple.
1820 if (estate->fn_rettype == VOIDOID)
1822 estate->retval = (Datum) 0;
1823 estate->retisnull = false;
1824 estate->rettype = VOIDOID;
1827 return PLPGSQL_RC_RETURN;
1831 * exec_stmt_return_next Evaluate an expression and add it to the
1832 * list of tuples returned by the current
1837 exec_stmt_return_next(PLpgSQL_execstate *estate,
1838 PLpgSQL_stmt_return_next *stmt)
1843 bool free_tuple = false;
1845 if (!estate->retisset)
1847 (errcode(ERRCODE_SYNTAX_ERROR),
1848 errmsg("cannot use RETURN NEXT in a non-SETOF function")));
1850 if (estate->tuple_store == NULL)
1851 exec_init_tuple_store(estate);
1853 /* rettupdesc will be filled by exec_init_tuple_store */
1854 tupdesc = estate->rettupdesc;
1855 natts = tupdesc->natts;
1857 if (stmt->retvarno >= 0)
1859 PLpgSQL_datum *retvar = estate->datums[stmt->retvarno];
1861 switch (retvar->dtype)
1863 case PLPGSQL_DTYPE_VAR:
1865 PLpgSQL_var *var = (PLpgSQL_var *) retvar;
1866 Datum retval = var->value;
1867 bool isNull = var->isnull;
1871 (errcode(ERRCODE_DATATYPE_MISMATCH),
1872 errmsg("wrong result type supplied in RETURN NEXT")));
1874 /* coerce type if needed */
1875 retval = exec_simple_cast_value(retval,
1876 var->datatype->typoid,
1877 tupdesc->attrs[0]->atttypid,
1878 tupdesc->attrs[0]->atttypmod,
1881 tuple = heap_form_tuple(tupdesc, &retval, &isNull);
1887 case PLPGSQL_DTYPE_REC:
1889 PLpgSQL_rec *rec = (PLpgSQL_rec *) retvar;
1891 if (!HeapTupleIsValid(rec->tup))
1893 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1894 errmsg("record \"%s\" is not assigned yet",
1896 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
1897 if (!compatible_tupdesc(tupdesc, rec->tupdesc))
1899 (errcode(ERRCODE_DATATYPE_MISMATCH),
1900 errmsg("wrong record type supplied in RETURN NEXT")));
1905 case PLPGSQL_DTYPE_ROW:
1907 PLpgSQL_row *row = (PLpgSQL_row *) retvar;
1909 tuple = make_tuple_from_row(estate, row, tupdesc);
1912 (errcode(ERRCODE_DATATYPE_MISMATCH),
1913 errmsg("wrong record type supplied in RETURN NEXT")));
1919 elog(ERROR, "unrecognized dtype: %d", retvar->dtype);
1920 tuple = NULL; /* keep compiler quiet */
1924 else if (stmt->expr)
1932 (errcode(ERRCODE_DATATYPE_MISMATCH),
1933 errmsg("wrong result type supplied in RETURN NEXT")));
1935 retval = exec_eval_expr(estate,
1940 /* coerce type if needed */
1941 retval = exec_simple_cast_value(retval,
1943 tupdesc->attrs[0]->atttypid,
1944 tupdesc->attrs[0]->atttypmod,
1947 tuple = heap_form_tuple(tupdesc, &retval, &isNull);
1951 exec_eval_cleanup(estate);
1956 (errcode(ERRCODE_SYNTAX_ERROR),
1957 errmsg("RETURN NEXT must have a parameter")));
1958 tuple = NULL; /* keep compiler quiet */
1961 if (HeapTupleIsValid(tuple))
1963 MemoryContext oldcxt;
1965 oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
1966 tuplestore_puttuple(estate->tuple_store, tuple);
1967 MemoryContextSwitchTo(oldcxt);
1970 heap_freetuple(tuple);
1973 return PLPGSQL_RC_OK;
1977 exec_init_tuple_store(PLpgSQL_execstate *estate)
1979 ReturnSetInfo *rsi = estate->rsi;
1980 MemoryContext oldcxt;
1983 * Check caller can handle a set result in the way we want
1985 if (!rsi || !IsA(rsi, ReturnSetInfo) ||
1986 (rsi->allowedModes & SFRM_Materialize) == 0 ||
1987 rsi->expectedDesc == NULL)
1989 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1990 errmsg("set-valued function called in context that cannot accept a set")));
1992 estate->tuple_store_cxt = rsi->econtext->ecxt_per_query_memory;
1994 oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
1995 estate->tuple_store = tuplestore_begin_heap(true, false, work_mem);
1996 MemoryContextSwitchTo(oldcxt);
1998 estate->rettupdesc = rsi->expectedDesc;
2002 * exec_stmt_raise Build a message and throw it with elog()
2006 exec_stmt_raise(PLpgSQL_execstate *estate, PLpgSQL_stmt_raise *stmt)
2010 ListCell *current_param;
2012 plpgsql_dstring_init(&ds);
2013 current_param = list_head(stmt->params);
2015 for (cp = stmt->message; *cp; cp++)
2018 * Occurrences of a single % are replaced by the next parameter's
2019 * external representation. Double %'s are converted to one %.
2030 plpgsql_dstring_append_char(&ds, cp[1]);
2035 if (current_param == NULL)
2037 (errcode(ERRCODE_SYNTAX_ERROR),
2038 errmsg("too few parameters specified for RAISE")));
2040 paramvalue = exec_eval_expr(estate,
2041 (PLpgSQL_expr *) lfirst(current_param),
2048 extval = convert_value_to_string(paramvalue, paramtypeid);
2049 plpgsql_dstring_append(&ds, extval);
2050 current_param = lnext(current_param);
2051 exec_eval_cleanup(estate);
2055 plpgsql_dstring_append_char(&ds, cp[0]);
2059 * If more parameters were specified than were required to process the
2060 * format string, throw an error
2062 if (current_param != NULL)
2064 (errcode(ERRCODE_SYNTAX_ERROR),
2065 errmsg("too many parameters specified for RAISE")));
2068 * Throw the error (may or may not come back)
2070 estate->err_text = raise_skip_msg; /* suppress traceback of raise */
2072 ereport(stmt->elog_level,
2073 ((stmt->elog_level >= ERROR) ? errcode(ERRCODE_RAISE_EXCEPTION) : 0,
2074 errmsg_internal("%s", plpgsql_dstring_get(&ds))));
2076 estate->err_text = NULL; /* un-suppress... */
2078 plpgsql_dstring_free(&ds);
2080 return PLPGSQL_RC_OK;
2085 * Initialize a mostly empty execution state
2089 plpgsql_estate_setup(PLpgSQL_execstate *estate,
2090 PLpgSQL_function *func,
2093 estate->retval = (Datum) 0;
2094 estate->retisnull = true;
2095 estate->rettype = InvalidOid;
2097 estate->fn_rettype = func->fn_rettype;
2098 estate->retistuple = func->fn_retistuple;
2099 estate->retisset = func->fn_retset;
2101 estate->readonly_func = func->fn_readonly;
2103 estate->rettupdesc = NULL;
2104 estate->exitlabel = NULL;
2106 estate->tuple_store = NULL;
2107 estate->tuple_store_cxt = NULL;
2110 estate->trig_nargs = 0;
2111 estate->trig_argv = NULL;
2113 estate->found_varno = func->found_varno;
2114 estate->ndatums = func->ndatums;
2115 estate->datums = palloc(sizeof(PLpgSQL_datum *) * estate->ndatums);
2116 /* caller is expected to fill the datums array */
2118 estate->eval_tuptable = NULL;
2119 estate->eval_processed = 0;
2120 estate->eval_lastoid = InvalidOid;
2122 estate->err_func = func;
2123 estate->err_stmt = NULL;
2124 estate->err_text = NULL;
2127 * Create an EState for evaluation of simple expressions, if there's not
2128 * one already in the current transaction. The EState is made a child of
2129 * TopTransactionContext so it will have the right lifespan.
2131 if (simple_eval_estate == NULL)
2133 MemoryContext oldcontext;
2135 oldcontext = MemoryContextSwitchTo(TopTransactionContext);
2136 simple_eval_estate = CreateExecutorState();
2137 MemoryContextSwitchTo(oldcontext);
2141 * Create an expression context for simple expressions. This must be a
2142 * child of simple_eval_estate.
2144 estate->eval_econtext = CreateExprContext(simple_eval_estate);
2148 * Release temporary memory used by expression/subselect evaluation
2150 * NB: the result of the evaluation is no longer valid after this is done,
2151 * unless it is a pass-by-value datatype.
2155 exec_eval_cleanup(PLpgSQL_execstate *estate)
2157 /* Clear result of a full SPI_execute */
2158 if (estate->eval_tuptable != NULL)
2159 SPI_freetuptable(estate->eval_tuptable);
2160 estate->eval_tuptable = NULL;
2162 /* Clear result of exec_eval_simple_expr (but keep the econtext) */
2163 if (estate->eval_econtext != NULL)
2164 ResetExprContext(estate->eval_econtext);
2169 * Generate a prepared plan
2173 exec_prepare_plan(PLpgSQL_execstate *estate,
2177 _SPI_plan *spi_plan;
2182 * We need a temporary argtypes array to load with data. (The finished
2183 * plan structure will contain a copy of it.)
2185 argtypes = (Oid *) palloc(expr->nparams * sizeof(Oid));
2187 for (i = 0; i < expr->nparams; i++)
2192 exec_eval_datum(estate, estate->datums[expr->params[i]],
2194 &argtypes[i], ¶mval, ¶misnull);
2198 * Generate and save the plan
2200 plan = SPI_prepare(expr->query, expr->nparams, argtypes);
2203 /* Some SPI errors deserve specific error messages */
2206 case SPI_ERROR_COPY:
2208 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2209 errmsg("cannot COPY to/from client in PL/pgSQL")));
2210 case SPI_ERROR_CURSOR:
2212 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2213 errmsg("cannot manipulate cursors directly in PL/pgSQL"),
2214 errhint("Use PL/pgSQL's cursor features instead.")));
2215 case SPI_ERROR_TRANSACTION:
2217 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2218 errmsg("cannot begin/end transactions in PL/pgSQL"),
2219 errhint("Use a BEGIN block with an EXCEPTION clause instead.")));
2221 elog(ERROR, "SPI_prepare failed for \"%s\": %s",
2222 expr->query, SPI_result_code_string(SPI_result));
2225 expr->plan = SPI_saveplan(plan);
2226 spi_plan = (_SPI_plan *) expr->plan;
2227 expr->plan_argtypes = spi_plan->argtypes;
2228 expr->expr_simple_expr = NULL;
2229 exec_simple_check_plan(expr);
2237 * exec_stmt_execsql Execute an SQL statement not
2238 * returning any data.
2242 exec_stmt_execsql(PLpgSQL_execstate *estate,
2243 PLpgSQL_stmt_execsql *stmt)
2249 PLpgSQL_expr *expr = stmt->sqlstmt;
2252 * On the first call for this expression generate the plan
2254 if (expr->plan == NULL)
2255 exec_prepare_plan(estate, expr);
2258 * Now build up the values and nulls arguments for SPI_execute_plan()
2260 values = (Datum *) palloc(expr->nparams * sizeof(Datum));
2261 nulls = (char *) palloc(expr->nparams * sizeof(char));
2263 for (i = 0; i < expr->nparams; i++)
2265 PLpgSQL_datum *datum = estate->datums[expr->params[i]];
2269 exec_eval_datum(estate, datum, expr->plan_argtypes[i],
2270 ¶mtypeid, &values[i], ¶misnull);
2280 rc = SPI_execute_plan(expr->plan, values, nulls,
2281 estate->readonly_func, 0);
2284 case SPI_OK_UTILITY:
2285 case SPI_OK_SELINTO:
2293 * If the INSERT, DELETE, or UPDATE query affected at least one
2294 * tuple, set the magic 'FOUND' variable to true. This conforms
2295 * with the behavior of PL/SQL.
2297 exec_set_found(estate, (SPI_processed != 0));
2302 (errcode(ERRCODE_SYNTAX_ERROR),
2303 errmsg("SELECT query has no destination for result data"),
2304 errhint("If you want to discard the results, use PERFORM instead.")));
2307 elog(ERROR, "SPI_execute_plan failed executing query \"%s\": %s",
2308 expr->query, SPI_result_code_string(rc));
2312 * Release any result tuples from SPI_execute_plan (probably shouldn't be
2315 SPI_freetuptable(SPI_tuptable);
2317 /* Save result info for GET DIAGNOSTICS */
2318 estate->eval_processed = SPI_processed;
2319 estate->eval_lastoid = SPI_lastoid;
2324 return PLPGSQL_RC_OK;
2329 * exec_stmt_dynexecute Execute a dynamic SQL query not
2330 * returning any data.
2334 exec_stmt_dynexecute(PLpgSQL_execstate *estate,
2335 PLpgSQL_stmt_dynexecute *stmt)
2338 bool isnull = false;
2342 PLpgSQL_rec *rec = NULL;
2343 PLpgSQL_row *row = NULL;
2345 if (stmt->rec != NULL)
2346 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
2347 else if (stmt->row != NULL)
2348 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
2351 * First we evaluate the string expression after the EXECUTE keyword. It's
2352 * result is the querystring we have to execute.
2354 query = exec_eval_expr(estate, stmt->query, &isnull, &restype);
2357 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2358 errmsg("cannot EXECUTE a null querystring")));
2360 /* Get the C-String representation */
2361 querystr = convert_value_to_string(query, restype);
2363 exec_eval_cleanup(estate);
2366 * Call SPI_execute() without preparing a saved plan. The returncode can
2367 * be any standard OK. Note that while a SELECT is allowed, its results
2368 * will be discarded unless an INTO clause is specified.
2370 exec_res = SPI_execute(querystr, estate->readonly_func, 0);
2372 /* Assign to INTO variable */
2375 if (exec_res != SPI_OK_SELECT)
2377 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2378 errmsg("EXECUTE ... INTO is only for SELECT")));
2381 if (SPI_processed == 0)
2382 exec_move_row(estate, rec, row, NULL, SPI_tuptable->tupdesc);
2384 exec_move_row(estate, rec, row,
2385 SPI_tuptable->vals[0], SPI_tuptable->tupdesc);
2395 case SPI_OK_UTILITY:
2401 * Also allow a zero return, which implies the querystring
2402 * contained no commands.
2406 case SPI_OK_SELINTO:
2409 * We want to disallow SELECT INTO for now, because its behavior
2410 * is not consistent with SELECT INTO in a normal plpgsql context.
2411 * (We need to reimplement EXECUTE to parse the string as a
2412 * plpgsql command, not just feed it to SPI_execute.) However,
2413 * CREATE AS should be allowed ... and since it produces the same
2414 * parsetree as SELECT INTO, there's no way to tell the difference
2415 * except to look at the source text. Wotta kluge!
2420 for (ptr = querystr; *ptr; ptr++)
2421 if (!isspace((unsigned char) *ptr))
2423 if (*ptr == 'S' || *ptr == 's')
2425 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2426 errmsg("EXECUTE of SELECT ... INTO is not implemented yet")));
2430 /* Some SPI errors deserve specific error messages */
2431 case SPI_ERROR_COPY:
2433 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2434 errmsg("cannot COPY to/from client in PL/pgSQL")));
2435 case SPI_ERROR_CURSOR:
2437 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2438 errmsg("cannot manipulate cursors directly in PL/pgSQL"),
2439 errhint("Use PL/pgSQL's cursor features instead.")));
2440 case SPI_ERROR_TRANSACTION:
2442 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2443 errmsg("cannot begin/end transactions in PL/pgSQL"),
2444 errhint("Use a BEGIN block with an EXCEPTION clause instead.")));
2447 elog(ERROR, "SPI_execute failed executing query \"%s\": %s",
2448 querystr, SPI_result_code_string(exec_res));
2452 /* Release any result from SPI_execute, as well as the querystring */
2453 SPI_freetuptable(SPI_tuptable);
2456 /* Save result info for GET DIAGNOSTICS */
2457 estate->eval_processed = SPI_processed;
2458 estate->eval_lastoid = SPI_lastoid;
2460 return PLPGSQL_RC_OK;
2465 * exec_stmt_dynfors Execute a dynamic query, assign each
2466 * tuple to a record or row and
2467 * execute a group of statements
2472 exec_stmt_dynfors(PLpgSQL_execstate *estate, PLpgSQL_stmt_dynfors *stmt)
2478 PLpgSQL_rec *rec = NULL;
2479 PLpgSQL_row *row = NULL;
2480 SPITupleTable *tuptab;
2487 * Determine if we assign to a record or a row
2489 if (stmt->rec != NULL)
2490 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
2491 else if (stmt->row != NULL)
2492 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
2494 elog(ERROR, "unsupported target");
2497 * Evaluate the string expression after the EXECUTE keyword. It's result
2498 * is the querystring we have to execute.
2500 query = exec_eval_expr(estate, stmt->query, &isnull, &restype);
2503 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2504 errmsg("cannot EXECUTE a null querystring")));
2506 /* Get the C-String representation */
2507 querystr = convert_value_to_string(query, restype);
2509 exec_eval_cleanup(estate);
2512 * Prepare a plan and open an implicit cursor for the query
2514 plan = SPI_prepare(querystr, 0, NULL);
2516 elog(ERROR, "SPI_prepare failed for \"%s\": %s",
2517 querystr, SPI_result_code_string(SPI_result));
2518 portal = SPI_cursor_open(NULL, plan, NULL, NULL,
2519 estate->readonly_func);
2521 elog(ERROR, "could not open implicit cursor for query \"%s\": %s",
2522 querystr, SPI_result_code_string(SPI_result));
2527 * Fetch the initial 10 tuples
2529 SPI_cursor_fetch(portal, true, 10);
2530 tuptab = SPI_tuptable;
2534 * If the query didn't return any rows, set the target to NULL and return
2535 * with FOUND = false.
2538 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
2540 found = true; /* processed at least one tuple */
2549 for (i = 0; i < n; i++)
2554 * Assign the tuple to the target
2556 exec_move_row(estate, rec, row, tuptab->vals[i], tuptab->tupdesc);
2559 * Execute the statements
2561 rc = exec_stmts(estate, stmt->body);
2563 if (rc != PLPGSQL_RC_OK)
2565 if (rc == PLPGSQL_RC_EXIT)
2567 if (estate->exitlabel == NULL)
2568 /* unlabelled exit, finish the current loop */
2570 else if (stmt->label != NULL &&
2571 strcmp(stmt->label, estate->exitlabel) == 0)
2573 /* labelled exit, matches the current stmt's label */
2574 estate->exitlabel = NULL;
2579 * otherwise, we processed a labelled exit that does not
2580 * match the current statement's label, if any: return
2581 * RC_EXIT so that the EXIT continues to recurse upward.
2584 else if (rc == PLPGSQL_RC_CONTINUE)
2586 if (estate->exitlabel == NULL)
2587 /* unlabelled continue, continue the current loop */
2589 else if (stmt->label != NULL &&
2590 strcmp(stmt->label, estate->exitlabel) == 0)
2592 /* labelled continue, matches the current stmt's label */
2593 estate->exitlabel = NULL;
2598 * otherwise, we process a labelled continue that does not
2599 * match the current statement's label, so propagate
2600 * RC_CONTINUE upward in the stack.
2605 * We're aborting the loop, so cleanup and set FOUND. (This
2606 * code should match the code after the loop.)
2608 SPI_freetuptable(tuptab);
2609 SPI_cursor_close(portal);
2610 exec_set_found(estate, found);
2616 SPI_freetuptable(tuptab);
2619 * Fetch the next 50 tuples
2621 SPI_cursor_fetch(portal, true, 50);
2623 tuptab = SPI_tuptable;
2627 * Release last group of tuples
2629 SPI_freetuptable(tuptab);
2632 * Close the implicit cursor
2634 SPI_cursor_close(portal);
2637 * Set the FOUND variable to indicate the result of executing the loop
2638 * (namely, whether we looped one or more times). This must be set here so
2639 * that it does not interfere with the value of the FOUND variable inside
2640 * the loop processing itself.
2642 exec_set_found(estate, found);
2644 return PLPGSQL_RC_OK;
2649 * exec_stmt_open Execute an OPEN cursor statement
2653 exec_stmt_open(PLpgSQL_execstate *estate, PLpgSQL_stmt_open *stmt)
2655 PLpgSQL_var *curvar = NULL;
2656 char *curname = NULL;
2657 PLpgSQL_expr *query = NULL;
2666 * Get the cursor variable and if it has an assigned name, check
2667 * that it's not in use currently.
2670 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
2671 if (!curvar->isnull)
2673 curname = DatumGetCString(DirectFunctionCall1(textout, curvar->value));
2674 if (SPI_cursor_find(curname) != NULL)
2676 (errcode(ERRCODE_DUPLICATE_CURSOR),
2677 errmsg("cursor \"%s\" already in use", curname)));
2681 * Process the OPEN according to it's type.
2684 if (stmt->query != NULL)
2687 * This is an OPEN refcursor FOR SELECT ...
2689 * We just make sure the query is planned. The real work is
2693 query = stmt->query;
2694 if (query->plan == NULL)
2695 exec_prepare_plan(estate, query);
2697 else if (stmt->dynquery != NULL)
2700 * This is an OPEN refcursor FOR EXECUTE ...
2709 * We evaluate the string expression after the
2710 * EXECUTE keyword. It's result is the querystring we have
2714 queryD = exec_eval_expr(estate, stmt->dynquery, &isnull, &restype);
2717 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2718 errmsg("cannot EXECUTE a null querystring")));
2720 /* Get the C-String representation */
2721 querystr = convert_value_to_string(queryD, restype);
2723 exec_eval_cleanup(estate);
2726 * Now we prepare a query plan for it and open a cursor
2729 curplan = SPI_prepare(querystr, 0, NULL);
2730 if (curplan == NULL)
2731 elog(ERROR, "SPI_prepare failed for \"%s\": %s",
2732 querystr, SPI_result_code_string(SPI_result));
2733 portal = SPI_cursor_open(curname, curplan, NULL, NULL,
2734 estate->readonly_func);
2736 elog(ERROR, "could not open cursor for query \"%s\": %s",
2737 querystr, SPI_result_code_string(SPI_result));
2739 SPI_freeplan(curplan);
2742 * Store the eventually assigned cursor name in the cursor variable
2746 curvar->value = DirectFunctionCall1(textin, CStringGetDatum(portal->name));
2747 curvar->isnull = false;
2748 curvar->freeval = true;
2750 return PLPGSQL_RC_OK;
2755 * This is an OPEN cursor
2757 * Note: parser should already have checked that statement supplies
2758 * args iff cursor needs them, but we check again to be safe.
2761 if (stmt->argquery != NULL)
2764 * Er - OPEN CURSOR (args). We fake a SELECT ... INTO ...
2765 * statement to evaluate the args and put 'em into the
2769 PLpgSQL_stmt_select set_args;
2771 if (curvar->cursor_explicit_argrow < 0)
2773 (errcode(ERRCODE_SYNTAX_ERROR),
2774 errmsg("arguments given for cursor without arguments")));
2776 memset(&set_args, 0, sizeof(set_args));
2777 set_args.cmd_type = PLPGSQL_STMT_SELECT;
2778 set_args.lineno = stmt->lineno;
2779 set_args.row = (PLpgSQL_row *)
2780 (estate->datums[curvar->cursor_explicit_argrow]);
2781 set_args.query = stmt->argquery;
2783 if (exec_stmt_select(estate, &set_args) != PLPGSQL_RC_OK)
2784 elog(ERROR, "open cursor failed during argument processing");
2788 if (curvar->cursor_explicit_argrow >= 0)
2790 (errcode(ERRCODE_SYNTAX_ERROR),
2791 errmsg("arguments required for cursor")));
2794 query = curvar->cursor_explicit_expr;
2795 if (query->plan == NULL)
2796 exec_prepare_plan(estate, query);
2800 * Here we go if we have a saved plan where we have to put
2801 * values into, either from an explicit cursor or from a
2802 * refcursor opened with OPEN ... FOR SELECT ...;
2805 values = (Datum *) palloc(query->nparams * sizeof(Datum));
2806 nulls = (char *) palloc(query->nparams * sizeof(char));
2808 for (i = 0; i < query->nparams; i++)
2810 PLpgSQL_datum *datum = estate->datums[query->params[i]];
2814 exec_eval_datum(estate, datum, query->plan_argtypes[i],
2815 ¶mtypeid, &values[i], ¶misnull);
2826 portal = SPI_cursor_open(curname, query->plan, values, nulls,
2827 estate->readonly_func);
2829 elog(ERROR, "could not open cursor: %s",
2830 SPI_result_code_string(SPI_result));
2838 * Store the eventually assigned portal name in the cursor variable
2842 curvar->value = DirectFunctionCall1(textin, CStringGetDatum(portal->name));
2843 curvar->isnull = false;
2844 curvar->freeval = true;
2846 return PLPGSQL_RC_OK;
2851 * exec_stmt_fetch Fetch from a cursor into a target
2855 exec_stmt_fetch(PLpgSQL_execstate *estate, PLpgSQL_stmt_fetch *stmt)
2857 PLpgSQL_var *curvar = NULL;
2858 PLpgSQL_rec *rec = NULL;
2859 PLpgSQL_row *row = NULL;
2860 SPITupleTable *tuptab;
2866 * Get the portal of the cursor by name
2869 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
2872 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2873 errmsg("cursor variable \"%s\" is NULL", curvar->refname)));
2874 curname = DatumGetCString(DirectFunctionCall1(textout, curvar->value));
2876 portal = SPI_cursor_find(curname);
2879 (errcode(ERRCODE_UNDEFINED_CURSOR),
2880 errmsg("cursor \"%s\" does not exist", curname)));
2884 * Determine if we fetch into a record or a row
2887 if (stmt->rec != NULL)
2888 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
2889 else if (stmt->row != NULL)
2890 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
2892 elog(ERROR, "unsupported target");
2895 * Fetch 1 tuple from the cursor
2898 SPI_cursor_fetch(portal, true, 1);
2899 tuptab = SPI_tuptable;
2903 * Set the target and the global FOUND variable appropriately.
2908 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
2909 exec_set_found(estate, false);
2913 exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
2914 exec_set_found(estate, true);
2917 SPI_freetuptable(tuptab);
2919 return PLPGSQL_RC_OK;
2924 * exec_stmt_close Close a cursor
2928 exec_stmt_close(PLpgSQL_execstate *estate, PLpgSQL_stmt_close *stmt)
2930 PLpgSQL_var *curvar = NULL;
2935 * Get the portal of the cursor by name
2938 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
2941 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2942 errmsg("cursor variable \"%s\" is NULL", curvar->refname)));
2943 curname = DatumGetCString(DirectFunctionCall1(textout, curvar->value));
2945 portal = SPI_cursor_find(curname);
2948 (errcode(ERRCODE_UNDEFINED_CURSOR),
2949 errmsg("cursor \"%s\" does not exist", curname)));
2956 SPI_cursor_close(portal);
2958 return PLPGSQL_RC_OK;
2963 * exec_assign_expr Put an expression's result into
2968 exec_assign_expr(PLpgSQL_execstate *estate, PLpgSQL_datum *target,
2973 bool isnull = false;
2975 value = exec_eval_expr(estate, expr, &isnull, &valtype);
2976 exec_assign_value(estate, target, value, valtype, &isnull);
2977 exec_eval_cleanup(estate);
2982 * exec_assign_value Put a value into a target field
2986 exec_assign_value(PLpgSQL_execstate *estate,
2987 PLpgSQL_datum *target,
2988 Datum value, Oid valtype, bool *isNull)
2990 switch (target->dtype)
2992 case PLPGSQL_DTYPE_VAR:
2995 * Target is a variable
2997 PLpgSQL_var *var = (PLpgSQL_var *) target;
3000 newvalue = exec_cast_value(value, valtype, var->datatype->typoid,
3001 &(var->datatype->typinput),
3002 var->datatype->typioparam,
3003 var->datatype->atttypmod,
3006 if (*isNull && var->notnull)
3008 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3009 errmsg("NULL cannot be assigned to variable \"%s\" declared NOT NULL",
3013 * If type is by-reference, make sure we have a freshly
3014 * palloc'd copy; the originally passed value may not live as
3015 * long as the variable! But we don't need to re-copy if
3016 * exec_cast_value performed a conversion; its output must
3017 * already be palloc'd.
3019 if (!var->datatype->typbyval && !*isNull)
3021 if (newvalue == value)
3022 newvalue = datumCopy(newvalue,
3024 var->datatype->typlen);
3028 * Now free the old value. (We can't do this any earlier
3029 * because of the possibility that we are assigning the var's
3030 * old value to it, eg "foo := foo". We could optimize out
3031 * the assignment altogether in such cases, but it's too
3032 * infrequent to be worth testing for.)
3036 var->value = newvalue;
3037 var->isnull = *isNull;
3038 if (!var->datatype->typbyval && !*isNull)
3039 var->freeval = true;
3043 case PLPGSQL_DTYPE_ROW:
3046 * Target is a row variable
3048 PLpgSQL_row *row = (PLpgSQL_row *) target;
3050 /* Source must be of RECORD or composite type */
3051 if (!(valtype == RECORDOID ||
3052 get_typtype(valtype) == 'c'))
3054 (errcode(ERRCODE_DATATYPE_MISMATCH),
3055 errmsg("cannot assign non-composite value to a row variable")));
3058 /* If source is null, just assign nulls to the row */
3059 exec_move_row(estate, NULL, row, NULL, NULL);
3067 HeapTupleData tmptup;
3069 /* Else source is a tuple Datum, safe to do this: */
3070 td = DatumGetHeapTupleHeader(value);
3071 /* Extract rowtype info and find a tupdesc */
3072 tupType = HeapTupleHeaderGetTypeId(td);
3073 tupTypmod = HeapTupleHeaderGetTypMod(td);
3074 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
3075 /* Build a temporary HeapTuple control structure */
3076 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
3077 ItemPointerSetInvalid(&(tmptup.t_self));
3078 tmptup.t_tableOid = InvalidOid;
3080 exec_move_row(estate, NULL, row, &tmptup, tupdesc);
3085 case PLPGSQL_DTYPE_REC:
3088 * Target is a record variable
3090 PLpgSQL_rec *rec = (PLpgSQL_rec *) target;
3092 /* Source must be of RECORD or composite type */
3093 if (!(valtype == RECORDOID ||
3094 get_typtype(valtype) == 'c'))
3096 (errcode(ERRCODE_DATATYPE_MISMATCH),
3097 errmsg("cannot assign non-composite value to a record variable")));
3100 /* If source is null, just assign nulls to the record */
3101 exec_move_row(estate, rec, NULL, NULL, NULL);
3109 HeapTupleData tmptup;
3111 /* Else source is a tuple Datum, safe to do this: */
3112 td = DatumGetHeapTupleHeader(value);
3113 /* Extract rowtype info and find a tupdesc */
3114 tupType = HeapTupleHeaderGetTypeId(td);
3115 tupTypmod = HeapTupleHeaderGetTypMod(td);
3116 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
3117 /* Build a temporary HeapTuple control structure */
3118 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
3119 ItemPointerSetInvalid(&(tmptup.t_self));
3120 tmptup.t_tableOid = InvalidOid;
3122 exec_move_row(estate, rec, NULL, &tmptup, tupdesc);
3127 case PLPGSQL_DTYPE_RECFIELD:
3130 * Target is a field of a record
3132 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) target;
3145 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
3148 * Check that there is already a tuple in the record. We need
3149 * that because records don't have any predefined field
3152 if (!HeapTupleIsValid(rec->tup))
3154 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3155 errmsg("record \"%s\" is not assigned yet",
3157 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
3160 * Get the number of the records field to change and the
3161 * number of attributes in the tuple.
3163 fno = SPI_fnumber(rec->tupdesc, recfield->fieldname);
3164 if (fno == SPI_ERROR_NOATTRIBUTE)
3166 (errcode(ERRCODE_UNDEFINED_COLUMN),
3167 errmsg("record \"%s\" has no field \"%s\"",
3168 rec->refname, recfield->fieldname)));
3170 natts = rec->tupdesc->natts;
3173 * Set up values/datums arrays for heap_formtuple. For all
3174 * the attributes except the one we want to replace, use the
3175 * value that's in the old tuple.
3177 values = palloc(sizeof(Datum) * natts);
3178 nulls = palloc(natts);
3180 for (i = 0; i < natts; i++)
3184 values[i] = SPI_getbinval(rec->tup, rec->tupdesc,
3193 * Now insert the new value, being careful to cast it to the
3196 atttype = SPI_gettypeid(rec->tupdesc, fno + 1);
3197 atttypmod = rec->tupdesc->attrs[fno]->atttypmod;
3198 attisnull = *isNull;
3199 values[fno] = exec_simple_cast_value(value,
3210 * Avoid leaking the result of exec_simple_cast_value, if it
3211 * performed a conversion to a pass-by-ref type.
3213 if (!attisnull && values[fno] != value && !get_typbyval(atttype))
3214 mustfree = DatumGetPointer(values[fno]);
3219 * Now call heap_formtuple() to create a new tuple that
3220 * replaces the old one in the record.
3222 newtup = heap_formtuple(rec->tupdesc, values, nulls);
3225 heap_freetuple(rec->tup);
3228 rec->freetup = true;
3238 case PLPGSQL_DTYPE_ARRAYELEM:
3242 PLpgSQL_expr *subscripts[MAXDIM];
3243 int subscriptvals[MAXDIM];
3244 bool oldarrayisnull;
3251 Datum oldarraydatum,
3253 ArrayType *oldarrayval;
3254 ArrayType *newarrayval;
3257 * Target is an element of an array
3259 * To handle constructs like x[1][2] := something, we have to
3260 * be prepared to deal with a chain of arrayelem datums. Chase
3261 * back to find the base array datum, and save the subscript
3262 * expressions as we go. (We are scanning right to left here,
3263 * but want to evaluate the subscripts left-to-right to
3264 * minimize surprises.)
3269 PLpgSQL_arrayelem *arrayelem = (PLpgSQL_arrayelem *) target;
3271 if (nsubscripts >= MAXDIM)
3273 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
3274 errmsg("number of array dimensions exceeds the maximum allowed, %d",
3276 subscripts[nsubscripts++] = arrayelem->subscript;
3277 target = estate->datums[arrayelem->arrayparentno];
3278 } while (target->dtype == PLPGSQL_DTYPE_ARRAYELEM);
3280 /* Fetch current value of array datum */
3281 exec_eval_datum(estate, target, InvalidOid,
3282 &arraytypeid, &oldarraydatum, &oldarrayisnull);
3284 arrayelemtypeid = get_element_type(arraytypeid);
3285 if (!OidIsValid(arrayelemtypeid))
3287 (errcode(ERRCODE_DATATYPE_MISMATCH),
3288 errmsg("subscripted object is not an array")));
3290 get_typlenbyvalalign(arrayelemtypeid,
3294 arraytyplen = get_typlen(arraytypeid);
3297 * Evaluate the subscripts, switch into left-to-right order.
3298 * Like ExecEvalArrayRef(), complain if any subscript is null.
3300 for (i = 0; i < nsubscripts; i++)
3305 exec_eval_integer(estate,
3306 subscripts[nsubscripts - 1 - i],
3310 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3311 errmsg("array subscript in assignment must not be NULL")));
3314 /* Coerce source value to match array element type. */
3315 coerced_value = exec_simple_cast_value(value,
3322 * If the original array is null, cons up an empty array so
3323 * that the assignment can proceed; we'll end with a
3324 * one-element array containing just the assigned-to
3325 * subscript. This only works for varlena arrays, though; for
3326 * fixed-length array types we skip the assignment. We can't
3327 * support assignment of a null entry into a fixed-length
3328 * array, either, so that's a no-op too. This is all ugly but
3329 * corresponds to the current behavior of ExecEvalArrayRef().
3331 if (arraytyplen > 0 && /* fixed-length array? */
3332 (oldarrayisnull || *isNull))
3336 oldarrayval = construct_empty_array(arrayelemtypeid);
3338 oldarrayval = (ArrayType *) DatumGetPointer(oldarraydatum);
3341 * Build the modified array value.
3343 newarrayval = array_set(oldarrayval,
3354 * Avoid leaking the result of exec_simple_cast_value, if it
3355 * performed a conversion to a pass-by-ref type.
3357 if (!*isNull && coerced_value != value && !elemtypbyval)
3358 pfree(DatumGetPointer(coerced_value));
3361 * Assign the new array to the base variable. It's never NULL
3365 exec_assign_value(estate, target,
3366 PointerGetDatum(newarrayval),
3367 arraytypeid, isNull);
3370 * Avoid leaking the modified array value, too.
3377 elog(ERROR, "unrecognized dtype: %d", target->dtype);
3382 * exec_eval_datum Get current value of a PLpgSQL_datum
3384 * The type oid, value in Datum format, and null flag are returned.
3386 * If expectedtypeid isn't InvalidOid, it is checked against the actual type.
3388 * At present this doesn't handle PLpgSQL_expr or PLpgSQL_arrayelem datums.
3390 * NOTE: caller must not modify the returned value, since it points right
3391 * at the stored value in the case of pass-by-reference datatypes. In some
3392 * cases we have to palloc a return value, and in such cases we put it into
3393 * the estate's short-term memory context.
3396 exec_eval_datum(PLpgSQL_execstate *estate,
3397 PLpgSQL_datum *datum,
3403 MemoryContext oldcontext;
3405 switch (datum->dtype)
3407 case PLPGSQL_DTYPE_VAR:
3409 PLpgSQL_var *var = (PLpgSQL_var *) datum;
3411 *typeid = var->datatype->typoid;
3412 *value = var->value;
3413 *isnull = var->isnull;
3414 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3416 (errcode(ERRCODE_DATATYPE_MISMATCH),
3417 errmsg("type of \"%s\" does not match that when preparing the plan",
3422 case PLPGSQL_DTYPE_ROW:
3424 PLpgSQL_row *row = (PLpgSQL_row *) datum;
3427 if (!row->rowtupdesc) /* should not happen */
3428 elog(ERROR, "row variable has no tupdesc");
3429 /* Make sure we have a valid type/typmod setting */
3430 BlessTupleDesc(row->rowtupdesc);
3431 oldcontext = MemoryContextSwitchTo(estate->eval_econtext->ecxt_per_tuple_memory);
3432 tup = make_tuple_from_row(estate, row, row->rowtupdesc);
3433 if (tup == NULL) /* should not happen */
3434 elog(ERROR, "row not compatible with its own tupdesc");
3435 MemoryContextSwitchTo(oldcontext);
3436 *typeid = row->rowtupdesc->tdtypeid;
3437 *value = HeapTupleGetDatum(tup);
3439 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3441 (errcode(ERRCODE_DATATYPE_MISMATCH),
3442 errmsg("type of \"%s\" does not match that when preparing the plan",
3447 case PLPGSQL_DTYPE_REC:
3449 PLpgSQL_rec *rec = (PLpgSQL_rec *) datum;
3450 HeapTupleData worktup;
3452 if (!HeapTupleIsValid(rec->tup))
3454 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3455 errmsg("record \"%s\" is not assigned yet",
3457 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
3458 Assert(rec->tupdesc != NULL);
3459 /* Make sure we have a valid type/typmod setting */
3460 BlessTupleDesc(rec->tupdesc);
3463 * In a trigger, the NEW and OLD parameters are likely to be
3464 * on-disk tuples that don't have the desired Datum fields.
3465 * Copy the tuple body and insert the right values.
3467 oldcontext = MemoryContextSwitchTo(estate->eval_econtext->ecxt_per_tuple_memory);
3468 heap_copytuple_with_tuple(rec->tup, &worktup);
3469 HeapTupleHeaderSetDatumLength(worktup.t_data, worktup.t_len);
3470 HeapTupleHeaderSetTypeId(worktup.t_data, rec->tupdesc->tdtypeid);
3471 HeapTupleHeaderSetTypMod(worktup.t_data, rec->tupdesc->tdtypmod);
3472 MemoryContextSwitchTo(oldcontext);
3473 *typeid = rec->tupdesc->tdtypeid;
3474 *value = HeapTupleGetDatum(&worktup);
3476 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3478 (errcode(ERRCODE_DATATYPE_MISMATCH),
3479 errmsg("type of \"%s\" does not match that when preparing the plan",
3484 case PLPGSQL_DTYPE_RECFIELD:
3486 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) datum;
3490 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
3491 if (!HeapTupleIsValid(rec->tup))
3493 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3494 errmsg("record \"%s\" is not assigned yet",
3496 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
3497 fno = SPI_fnumber(rec->tupdesc, recfield->fieldname);
3498 if (fno == SPI_ERROR_NOATTRIBUTE)
3500 (errcode(ERRCODE_UNDEFINED_COLUMN),
3501 errmsg("record \"%s\" has no field \"%s\"",
3502 rec->refname, recfield->fieldname)));
3503 *typeid = SPI_gettypeid(rec->tupdesc, fno);
3504 *value = SPI_getbinval(rec->tup, rec->tupdesc, fno, isnull);
3505 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3507 (errcode(ERRCODE_DATATYPE_MISMATCH),
3508 errmsg("type of \"%s.%s\" does not match that when preparing the plan",
3509 rec->refname, recfield->fieldname)));
3513 case PLPGSQL_DTYPE_TRIGARG:
3515 PLpgSQL_trigarg *trigarg = (PLpgSQL_trigarg *) datum;
3519 tgargno = exec_eval_integer(estate, trigarg->argnum, isnull);
3520 if (*isnull || tgargno < 0 || tgargno >= estate->trig_nargs)
3527 *value = estate->trig_argv[tgargno];
3530 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3532 (errcode(ERRCODE_DATATYPE_MISMATCH),
3533 errmsg("type of tgargv[%d] does not match that when preparing the plan",
3539 elog(ERROR, "unrecognized dtype: %d", datum->dtype);
3544 * exec_eval_integer Evaluate an expression, coerce result to int4
3546 * Note we do not do exec_eval_cleanup here; the caller must do it at
3547 * some later point. (We do this because the caller may be holding the
3548 * results of other, pass-by-reference, expression evaluations, such as
3549 * an array value to be subscripted. Also see notes in exec_eval_simple_expr
3550 * about allocation of the parameter array.)
3554 exec_eval_integer(PLpgSQL_execstate *estate,
3561 exprdatum = exec_eval_expr(estate, expr, isNull, &exprtypeid);
3562 exprdatum = exec_simple_cast_value(exprdatum, exprtypeid,
3565 return DatumGetInt32(exprdatum);
3569 * exec_eval_boolean Evaluate an expression, coerce result to bool
3571 * Note we do not do exec_eval_cleanup here; the caller must do it at
3576 exec_eval_boolean(PLpgSQL_execstate *estate,
3583 exprdatum = exec_eval_expr(estate, expr, isNull, &exprtypeid);
3584 exprdatum = exec_simple_cast_value(exprdatum, exprtypeid,
3587 return DatumGetBool(exprdatum);
3591 * exec_eval_expr Evaluate an expression and return
3594 * NOTE: caller must do exec_eval_cleanup when done with the Datum.
3598 exec_eval_expr(PLpgSQL_execstate *estate,
3606 * If not already done create a plan for this expression
3608 if (expr->plan == NULL)
3609 exec_prepare_plan(estate, expr);
3612 * If this is a simple expression, bypass SPI and use the executor
3615 if (expr->expr_simple_expr != NULL)
3616 return exec_eval_simple_expr(estate, expr, isNull, rettype);
3618 rc = exec_run_select(estate, expr, 2, NULL);
3619 if (rc != SPI_OK_SELECT)
3621 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3622 errmsg("query \"%s\" did not return data", expr->query)));
3625 * If there are no rows selected, the result is NULL.
3627 if (estate->eval_processed == 0)
3634 * Check that the expression returned one single Datum
3636 if (estate->eval_processed > 1)
3638 (errcode(ERRCODE_CARDINALITY_VIOLATION),
3639 errmsg("query \"%s\" returned more than one row",
3641 if (estate->eval_tuptable->tupdesc->natts != 1)
3643 (errcode(ERRCODE_SYNTAX_ERROR),
3644 errmsg("query \"%s\" returned %d columns", expr->query,
3645 estate->eval_tuptable->tupdesc->natts)));
3648 * Return the result and its type
3650 *rettype = SPI_gettypeid(estate->eval_tuptable->tupdesc, 1);
3651 return SPI_getbinval(estate->eval_tuptable->vals[0],
3652 estate->eval_tuptable->tupdesc, 1, isNull);
3657 * exec_run_select Execute a select query
3661 exec_run_select(PLpgSQL_execstate *estate,
3662 PLpgSQL_expr *expr, long maxtuples, Portal *portalP)
3670 * On the first call for this expression generate the plan
3672 if (expr->plan == NULL)
3673 exec_prepare_plan(estate, expr);
3676 * Now build up the values and nulls arguments for SPI_execute_plan()
3678 values = (Datum *) palloc(expr->nparams * sizeof(Datum));
3679 nulls = (char *) palloc(expr->nparams * sizeof(char));
3681 for (i = 0; i < expr->nparams; i++)
3683 PLpgSQL_datum *datum = estate->datums[expr->params[i]];
3687 exec_eval_datum(estate, datum, expr->plan_argtypes[i],
3688 ¶mtypeid, &values[i], ¶misnull);
3696 * If a portal was requested, put the query into the portal
3698 if (portalP != NULL)
3700 *portalP = SPI_cursor_open(NULL, expr->plan, values, nulls,
3701 estate->readonly_func);
3702 if (*portalP == NULL)
3703 elog(ERROR, "could not open implicit cursor for query \"%s\": %s",
3704 expr->query, SPI_result_code_string(SPI_result));
3707 return SPI_OK_CURSOR;
3713 rc = SPI_execute_plan(expr->plan, values, nulls,
3714 estate->readonly_func, maxtuples);
3715 if (rc != SPI_OK_SELECT)
3717 (errcode(ERRCODE_SYNTAX_ERROR),
3718 errmsg("query \"%s\" is not a SELECT", expr->query)));
3720 /* Save query results for eventual cleanup */
3721 Assert(estate->eval_tuptable == NULL);
3722 estate->eval_tuptable = SPI_tuptable;
3723 estate->eval_processed = SPI_processed;
3724 estate->eval_lastoid = SPI_lastoid;
3734 * exec_eval_simple_expr - Evaluate a simple expression returning
3735 * a Datum by directly calling ExecEvalExpr().
3737 * Note: if pass-by-reference, the result is in the eval_econtext's
3738 * temporary memory context. It will be freed when exec_eval_cleanup
3743 exec_eval_simple_expr(PLpgSQL_execstate *estate,
3749 ExprContext *econtext = estate->eval_econtext;
3750 ParamListInfo paramLI;
3752 Snapshot saveActiveSnapshot;
3755 * Pass back previously-determined result type.
3757 *rettype = expr->expr_simple_type;
3760 * Prepare the expression for execution, if it's not been done already in
3761 * the current transaction.
3763 if (expr->expr_simple_state == NULL)
3765 expr->expr_simple_state = ExecPrepareExpr(expr->expr_simple_expr,
3766 simple_eval_estate);
3767 /* Add it to list for cleanup */
3768 expr->expr_simple_next = active_simple_exprs;
3769 active_simple_exprs = expr;
3773 * Param list can live in econtext's temporary memory context.
3775 * XXX think about avoiding repeated palloc's for param lists? Beware
3776 * however that this routine is re-entrant: exec_eval_datum() can call it
3777 * back for subscript evaluation, and so there can be a need to have more
3778 * than one active param list.
3780 paramLI = (ParamListInfo)
3781 MemoryContextAlloc(econtext->ecxt_per_tuple_memory,
3782 (expr->nparams + 1) * sizeof(ParamListInfoData));
3785 * Put the parameter values into the parameter list entries.
3787 for (i = 0; i < expr->nparams; i++)
3789 PLpgSQL_datum *datum = estate->datums[expr->params[i]];
3791 paramLI[i].kind = PARAM_NUM;
3792 paramLI[i].id = i + 1;
3793 exec_eval_datum(estate, datum, expr->plan_argtypes[i],
3795 ¶mLI[i].value, ¶mLI[i].isnull);
3797 paramLI[i].kind = PARAM_INVALID;
3800 * Now we can safely make the econtext point to the param list.
3802 econtext->ecxt_param_list_info = paramLI;
3805 * We have to do some of the things SPI_execute_plan would do, in
3806 * particular advance the snapshot if we are in a non-read-only function.
3807 * Without this, stable functions within the expression would fail to see
3808 * updates made so far by our own function.
3811 saveActiveSnapshot = ActiveSnapshot;
3815 MemoryContext oldcontext;
3817 oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
3818 if (!estate->readonly_func)
3820 CommandCounterIncrement();
3821 ActiveSnapshot = CopySnapshot(GetTransactionSnapshot());
3825 * Finally we can call the executor to evaluate the expression
3827 retval = ExecEvalExpr(expr->expr_simple_state,
3831 MemoryContextSwitchTo(oldcontext);
3835 /* Restore global vars and propagate error */
3836 ActiveSnapshot = saveActiveSnapshot;
3841 ActiveSnapshot = saveActiveSnapshot;
3852 * exec_move_row Move one tuple's values into a record or row
3856 exec_move_row(PLpgSQL_execstate *estate,
3859 HeapTuple tup, TupleDesc tupdesc)
3862 * Record is simple - just copy the tuple and its descriptor into the
3868 * copy input first, just in case it is pointing at variable's value
3870 if (HeapTupleIsValid(tup))
3871 tup = heap_copytuple(tup);
3873 tupdesc = CreateTupleDescCopy(tupdesc);
3877 heap_freetuple(rec->tup);
3878 rec->freetup = false;
3880 if (rec->freetupdesc)
3882 FreeTupleDesc(rec->tupdesc);
3883 rec->freetupdesc = false;
3886 if (HeapTupleIsValid(tup))
3889 rec->freetup = true;
3893 /* If we have a tupdesc but no data, form an all-nulls tuple */
3896 nulls = (char *) palloc(tupdesc->natts * sizeof(char));
3897 memset(nulls, 'n', tupdesc->natts * sizeof(char));
3899 rec->tup = heap_formtuple(tupdesc, NULL, nulls);
3900 rec->freetup = true;
3909 rec->tupdesc = tupdesc;
3910 rec->freetupdesc = true;
3913 rec->tupdesc = NULL;
3919 * Row is a bit more complicated in that we assign the individual
3920 * attributes of the tuple to the variables the row points to.
3922 * NOTE: this code used to demand row->nfields == tup->t_data->t_natts,
3923 * but that's wrong. The tuple might have more fields than we expected if
3924 * it's from an inheritance-child table of the current table, or it might
3925 * have fewer if the table has had columns added by ALTER TABLE. Ignore
3926 * extra columns and assume NULL for missing columns, the same as
3927 * heap_getattr would do. We also have to skip over dropped columns in
3928 * either the source or destination.
3930 * If we have no tuple data at all, we'll assign NULL to all columns of
3939 if (HeapTupleIsValid(tup))
3940 t_natts = tup->t_data->t_natts;
3945 for (fnum = 0; fnum < row->nfields; fnum++)
3952 if (row->varnos[fnum] < 0)
3953 continue; /* skip dropped column in row struct */
3955 var = (PLpgSQL_var *) (estate->datums[row->varnos[fnum]]);
3957 while (anum < t_natts && tupdesc->attrs[anum]->attisdropped)
3958 anum++; /* skip dropped column in tuple */
3962 value = SPI_getbinval(tup, tupdesc, anum + 1, &isnull);
3963 valtype = SPI_gettypeid(tupdesc, anum + 1);
3970 valtype = InvalidOid;
3973 exec_assign_value(estate, (PLpgSQL_datum *) var,
3974 value, valtype, &isnull);
3980 elog(ERROR, "unsupported target");
3984 * make_tuple_from_row Make a tuple from the values of a row object
3986 * A NULL return indicates rowtype mismatch; caller must raise suitable error
3990 make_tuple_from_row(PLpgSQL_execstate *estate,
3994 int natts = tupdesc->natts;
4000 if (natts != row->nfields)
4003 dvalues = (Datum *) palloc0(natts * sizeof(Datum));
4004 nulls = (bool *) palloc(natts * sizeof(bool));
4006 for (i = 0; i < natts; i++)
4010 if (tupdesc->attrs[i]->attisdropped)
4012 nulls[i] = true; /* leave the column as null */
4015 if (row->varnos[i] < 0) /* should not happen */
4016 elog(ERROR, "dropped rowtype entry for non-dropped column");
4018 exec_eval_datum(estate, estate->datums[row->varnos[i]],
4019 InvalidOid, &fieldtypeid, &dvalues[i], &nulls[i]);
4020 if (fieldtypeid != tupdesc->attrs[i]->atttypid)
4024 tuple = heap_form_tuple(tupdesc, dvalues, nulls);
4033 * convert_value_to_string Convert a non-null Datum to C string
4035 * Note: callers generally assume that the result is a palloc'd string and
4036 * should be pfree'd. This is not all that safe an assumption ...
4040 convert_value_to_string(Datum value, Oid valtype)
4045 getTypeOutputInfo(valtype, &typoutput, &typIsVarlena);
4047 return DatumGetCString(OidFunctionCall1(typoutput, value));
4051 * exec_cast_value Cast a value if required
4055 exec_cast_value(Datum value, Oid valtype,
4065 * If the type of the queries return value isn't that of the variable,
4068 if (valtype != reqtype || reqtypmod != -1)
4072 extval = convert_value_to_string(value, valtype);
4073 value = FunctionCall3(reqinput,
4074 CStringGetDatum(extval),
4075 ObjectIdGetDatum(reqtypioparam),
4076 Int32GetDatum(reqtypmod));
4085 * exec_simple_cast_value Cast a value if required
4087 * As above, but need not supply details about target type. Note that this
4088 * is slower than exec_cast_value with cached type info, and so should be
4089 * avoided in heavily used code paths.
4093 exec_simple_cast_value(Datum value, Oid valtype,
4094 Oid reqtype, int32 reqtypmod,
4099 if (valtype != reqtype || reqtypmod != -1)
4103 FmgrInfo finfo_input;
4105 getTypeInputInfo(reqtype, &typinput, &typioparam);
4107 fmgr_info(typinput, &finfo_input);
4109 value = exec_cast_value(value,
4124 * exec_simple_check_node - Recursively check if an expression
4125 * is made only of simple things we can
4126 * hand out directly to ExecEvalExpr()
4127 * instead of calling SPI.
4131 exec_simple_check_node(Node *node)
4136 switch (nodeTag(node))
4146 ArrayRef *expr = (ArrayRef *) node;
4148 if (!exec_simple_check_node((Node *) expr->refupperindexpr))
4150 if (!exec_simple_check_node((Node *) expr->reflowerindexpr))
4152 if (!exec_simple_check_node((Node *) expr->refexpr))
4154 if (!exec_simple_check_node((Node *) expr->refassgnexpr))
4162 FuncExpr *expr = (FuncExpr *) node;
4164 if (expr->funcretset)
4166 if (!exec_simple_check_node((Node *) expr->args))
4174 OpExpr *expr = (OpExpr *) node;
4178 if (!exec_simple_check_node((Node *) expr->args))
4184 case T_DistinctExpr:
4186 DistinctExpr *expr = (DistinctExpr *) node;
4190 if (!exec_simple_check_node((Node *) expr->args))
4196 case T_ScalarArrayOpExpr:
4198 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
4200 if (!exec_simple_check_node((Node *) expr->args))
4208 BoolExpr *expr = (BoolExpr *) node;
4210 if (!exec_simple_check_node((Node *) expr->args))
4217 return exec_simple_check_node((Node *) ((FieldSelect *) node)->arg);
4221 FieldStore *expr = (FieldStore *) node;
4223 if (!exec_simple_check_node((Node *) expr->arg))
4225 if (!exec_simple_check_node((Node *) expr->newvals))
4232 return exec_simple_check_node((Node *) ((RelabelType *) node)->arg);
4234 case T_ConvertRowtypeExpr:
4235 return exec_simple_check_node((Node *) ((ConvertRowtypeExpr *) node)->arg);
4239 CaseExpr *expr = (CaseExpr *) node;
4241 if (!exec_simple_check_node((Node *) expr->arg))
4243 if (!exec_simple_check_node((Node *) expr->args))
4245 if (!exec_simple_check_node((Node *) expr->defresult))
4253 CaseWhen *when = (CaseWhen *) node;
4255 if (!exec_simple_check_node((Node *) when->expr))
4257 if (!exec_simple_check_node((Node *) when->result))
4263 case T_CaseTestExpr:
4268 ArrayExpr *expr = (ArrayExpr *) node;
4270 if (!exec_simple_check_node((Node *) expr->elements))
4278 RowExpr *expr = (RowExpr *) node;
4280 if (!exec_simple_check_node((Node *) expr->args))
4286 case T_RowCompareExpr:
4288 RowCompareExpr *expr = (RowCompareExpr *) node;
4290 if (!exec_simple_check_node((Node *) expr->largs))
4292 if (!exec_simple_check_node((Node *) expr->rargs))
4298 case T_CoalesceExpr:
4300 CoalesceExpr *expr = (CoalesceExpr *) node;
4302 if (!exec_simple_check_node((Node *) expr->args))
4310 MinMaxExpr *expr = (MinMaxExpr *) node;
4312 if (!exec_simple_check_node((Node *) expr->args))
4320 NullIfExpr *expr = (NullIfExpr *) node;
4324 if (!exec_simple_check_node((Node *) expr->args))
4331 return exec_simple_check_node((Node *) ((NullTest *) node)->arg);
4334 return exec_simple_check_node((Node *) ((BooleanTest *) node)->arg);
4336 case T_CoerceToDomain:
4337 return exec_simple_check_node((Node *) ((CoerceToDomain *) node)->arg);
4339 case T_CoerceToDomainValue:
4344 List *expr = (List *) node;
4349 if (!exec_simple_check_node(lfirst(l)))
4363 * exec_simple_check_plan - Check if a plan is simple enough to
4364 * be evaluated by ExecEvalExpr() instead
4369 exec_simple_check_plan(PLpgSQL_expr *expr)
4371 _SPI_plan *spi_plan = (_SPI_plan *) expr->plan;
4375 expr->expr_simple_expr = NULL;
4378 * 1. We can only evaluate queries that resulted in one single execution
4381 if (list_length(spi_plan->ptlist) != 1)
4384 plan = (Plan *) linitial(spi_plan->ptlist);
4387 * 2. It must be a RESULT plan --> no scan's required
4389 if (plan == NULL) /* utility statement produces this */
4392 if (!IsA(plan, Result))
4396 * 3. Can't have any subplan or qual clause, either
4398 if (plan->lefttree != NULL ||
4399 plan->righttree != NULL ||
4400 plan->initPlan != NULL ||
4401 plan->qual != NULL ||
4402 ((Result *) plan)->resconstantqual != NULL)
4406 * 4. The plan must have a single attribute as result
4408 if (list_length(plan->targetlist) != 1)
4411 tle = (TargetEntry *) linitial(plan->targetlist);
4414 * 5. Check that all the nodes in the expression are non-scary.
4416 if (!exec_simple_check_node((Node *) tle->expr))
4420 * Yes - this is a simple expression. Mark it as such, and initialize
4421 * state to "not executing".
4423 expr->expr_simple_expr = tle->expr;
4424 expr->expr_simple_state = NULL;
4425 expr->expr_simple_next = NULL;
4426 /* Also stash away the expression result type */
4427 expr->expr_simple_type = exprType((Node *) tle->expr);
4431 * Check two tupledescs have matching number and types of attributes
4434 compatible_tupdesc(TupleDesc td1, TupleDesc td2)
4438 if (td1->natts != td2->natts)
4441 for (i = 0; i < td1->natts; i++)
4443 if (td1->attrs[i]->atttypid != td2->attrs[i]->atttypid)
4451 * exec_set_found Set the global found variable
4456 exec_set_found(PLpgSQL_execstate *estate, bool state)
4460 var = (PLpgSQL_var *) (estate->datums[estate->found_varno]);
4461 var->value = (Datum) state;
4462 var->isnull = false;
4466 * plpgsql_xact_cb --- post-transaction-commit-or-abort cleanup
4468 * If a simple_eval_estate was created in the current transaction,
4469 * it has to be cleaned up, and we have to mark all active PLpgSQL_expr
4470 * structs that are using it as no longer active.
4472 * XXX Do we need to do anything at subtransaction events?
4473 * Maybe subtransactions need to have their own simple_eval_estate?
4474 * It would get a lot messier, so for now let's assume we don't need that.
4477 plpgsql_xact_cb(XactEvent event, void *arg)
4480 PLpgSQL_expr *enext;
4482 /* Mark all active exprs as inactive */
4483 for (expr = active_simple_exprs; expr; expr = enext)
4485 enext = expr->expr_simple_next;
4486 expr->expr_simple_state = NULL;
4487 expr->expr_simple_next = NULL;
4489 active_simple_exprs = NULL;
4492 * If we are doing a clean transaction shutdown, free the EState (so that
4493 * any remaining resources will be released correctly). In an abort, we
4494 * expect the regular abort recovery procedures to release everything of
4497 if (event == XACT_EVENT_COMMIT && simple_eval_estate)
4498 FreeExecutorState(simple_eval_estate);
4499 simple_eval_estate = NULL;
4503 free_var(PLpgSQL_var *var)
4507 pfree(DatumGetPointer(var->value));
4508 var->freeval = false;