1 /**********************************************************************
2 * pl_exec.c - Executor for the PL/pgSQL
6 * $PostgreSQL: pgsql/src/pl/plpgsql/src/pl_exec.c,v 1.152 2005/09/13 16:16:17 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
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
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
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,
589 * the relation that fired the trigger has. A per-statement trigger
590 * always needs to return NULL, so we ignore any return value the
591 * function itself 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
595 * the 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
656 * we actually need it. Therefore, places that set up err_text
657 * should use gettext_noop() to ensure the strings get recorded in
658 * the 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:
720 * These datum records are read-only at runtime, so no need
727 elog(ERROR, "unrecognized dtype: %d", datum->dtype);
728 result = NULL; /* keep compiler quiet */
737 exception_matches_conditions(ErrorData *edata, PLpgSQL_condition *cond)
739 for (; cond != NULL; cond = cond->next)
741 int sqlerrstate = cond->sqlerrstate;
744 * OTHERS matches everything *except* query-canceled; if you're
745 * foolish enough, you can match that explicitly.
747 if (sqlerrstate == 0)
749 if (edata->sqlerrcode != ERRCODE_QUERY_CANCELED)
753 else if (edata->sqlerrcode == sqlerrstate)
755 /* Category match? */
756 else if (ERRCODE_IS_CATEGORY(sqlerrstate) &&
757 ERRCODE_TO_CATEGORY(edata->sqlerrcode) == sqlerrstate)
765 * exec_stmt_block Execute a block of statements
769 exec_stmt_block(PLpgSQL_execstate *estate, PLpgSQL_stmt_block *block)
771 volatile int rc = -1;
776 * First initialize all variables declared in this block
778 for (i = 0; i < block->n_initvars; i++)
780 n = block->initvarnos[i];
782 switch (estate->datums[n]->dtype)
784 case PLPGSQL_DTYPE_VAR:
786 PLpgSQL_var *var = (PLpgSQL_var *) (estate->datums[n]);
789 if (!var->isconst || var->isnull)
791 if (var->default_val == NULL)
793 var->value = (Datum) 0;
797 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
798 errmsg("variable \"%s\" declared NOT NULL cannot default to NULL",
803 exec_assign_expr(estate, (PLpgSQL_datum *) var,
810 case PLPGSQL_DTYPE_REC:
812 PLpgSQL_rec *rec = (PLpgSQL_rec *) (estate->datums[n]);
816 heap_freetuple(rec->tup);
817 FreeTupleDesc(rec->tupdesc);
818 rec->freetup = false;
826 case PLPGSQL_DTYPE_RECFIELD:
827 case PLPGSQL_DTYPE_ARRAYELEM:
831 elog(ERROR, "unrecognized dtype: %d",
832 estate->datums[n]->dtype);
836 if (block->exceptions)
839 * Execute the statements in the block's body inside a
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,
860 * but 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,
881 * it will have left us in a disconnected state. We need this
882 * hack 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
895 * variables for the exception block. We needn't
896 * do this until we have found a matching
899 PLpgSQL_var *state_var;
900 PLpgSQL_var *errm_var;
902 state_var = (PLpgSQL_var *)
903 estate->datums[block->exceptions->sqlstate_varno];
904 state_var->value = DirectFunctionCall1(textin,
905 CStringGetDatum(unpack_sql_state(edata->sqlerrcode)));
906 state_var->freeval = true;
907 state_var->isnull = false;
909 errm_var = (PLpgSQL_var *)
910 estate->datums[block->exceptions->sqlerrm_varno];
911 errm_var->value = DirectFunctionCall1(textin,
912 CStringGetDatum(edata->message));
913 errm_var->freeval = true;
914 errm_var->isnull = false;
916 rc = exec_stmts(estate, exception->action);
924 /* If no match found, re-throw the error */
928 FreeErrorData(edata);
935 * Just execute the statements in the block's body
937 rc = exec_stmts(estate, block->body);
941 * Handle the return code.
946 case PLPGSQL_RC_CONTINUE:
947 case PLPGSQL_RC_RETURN:
950 case PLPGSQL_RC_EXIT:
951 if (estate->exitlabel == NULL)
952 return PLPGSQL_RC_OK;
953 if (block->label == NULL)
954 return PLPGSQL_RC_EXIT;
955 if (strcmp(block->label, estate->exitlabel))
956 return PLPGSQL_RC_EXIT;
957 estate->exitlabel = NULL;
958 return PLPGSQL_RC_OK;
961 elog(ERROR, "unrecognized rc: %d", rc);
964 return PLPGSQL_RC_OK;
969 * exec_stmts Iterate over a list of statements
970 * as long as their return code is OK
974 exec_stmts(PLpgSQL_execstate *estate, List *stmts)
980 PLpgSQL_stmt *stmt = (PLpgSQL_stmt *) lfirst(s);
981 int rc = exec_stmt(estate, stmt);
982 if (rc != PLPGSQL_RC_OK)
986 return PLPGSQL_RC_OK;
991 * exec_stmt Distribute one statement to the statements
992 * type specific execution function.
996 exec_stmt(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
998 PLpgSQL_stmt *save_estmt;
1001 save_estmt = estate->err_stmt;
1002 estate->err_stmt = stmt;
1004 CHECK_FOR_INTERRUPTS();
1006 switch (stmt->cmd_type)
1008 case PLPGSQL_STMT_BLOCK:
1009 rc = exec_stmt_block(estate, (PLpgSQL_stmt_block *) stmt);
1012 case PLPGSQL_STMT_ASSIGN:
1013 rc = exec_stmt_assign(estate, (PLpgSQL_stmt_assign *) stmt);
1016 case PLPGSQL_STMT_PERFORM:
1017 rc = exec_stmt_perform(estate, (PLpgSQL_stmt_perform *) stmt);
1020 case PLPGSQL_STMT_GETDIAG:
1021 rc = exec_stmt_getdiag(estate, (PLpgSQL_stmt_getdiag *) stmt);
1024 case PLPGSQL_STMT_IF:
1025 rc = exec_stmt_if(estate, (PLpgSQL_stmt_if *) stmt);
1028 case PLPGSQL_STMT_LOOP:
1029 rc = exec_stmt_loop(estate, (PLpgSQL_stmt_loop *) stmt);
1032 case PLPGSQL_STMT_WHILE:
1033 rc = exec_stmt_while(estate, (PLpgSQL_stmt_while *) stmt);
1036 case PLPGSQL_STMT_FORI:
1037 rc = exec_stmt_fori(estate, (PLpgSQL_stmt_fori *) stmt);
1040 case PLPGSQL_STMT_FORS:
1041 rc = exec_stmt_fors(estate, (PLpgSQL_stmt_fors *) stmt);
1044 case PLPGSQL_STMT_SELECT:
1045 rc = exec_stmt_select(estate, (PLpgSQL_stmt_select *) stmt);
1048 case PLPGSQL_STMT_EXIT:
1049 rc = exec_stmt_exit(estate, (PLpgSQL_stmt_exit *) stmt);
1052 case PLPGSQL_STMT_RETURN:
1053 rc = exec_stmt_return(estate, (PLpgSQL_stmt_return *) stmt);
1056 case PLPGSQL_STMT_RETURN_NEXT:
1057 rc = exec_stmt_return_next(estate, (PLpgSQL_stmt_return_next *) stmt);
1060 case PLPGSQL_STMT_RAISE:
1061 rc = exec_stmt_raise(estate, (PLpgSQL_stmt_raise *) stmt);
1064 case PLPGSQL_STMT_EXECSQL:
1065 rc = exec_stmt_execsql(estate, (PLpgSQL_stmt_execsql *) stmt);
1068 case PLPGSQL_STMT_DYNEXECUTE:
1069 rc = exec_stmt_dynexecute(estate, (PLpgSQL_stmt_dynexecute *) stmt);
1072 case PLPGSQL_STMT_DYNFORS:
1073 rc = exec_stmt_dynfors(estate, (PLpgSQL_stmt_dynfors *) stmt);
1076 case PLPGSQL_STMT_OPEN:
1077 rc = exec_stmt_open(estate, (PLpgSQL_stmt_open *) stmt);
1080 case PLPGSQL_STMT_FETCH:
1081 rc = exec_stmt_fetch(estate, (PLpgSQL_stmt_fetch *) stmt);
1084 case PLPGSQL_STMT_CLOSE:
1085 rc = exec_stmt_close(estate, (PLpgSQL_stmt_close *) stmt);
1089 estate->err_stmt = save_estmt;
1090 elog(ERROR, "unrecognized cmdtype: %d", stmt->cmd_type);
1093 estate->err_stmt = save_estmt;
1100 * exec_stmt_assign Evaluate an expression and
1101 * put the result into a variable.
1105 exec_stmt_assign(PLpgSQL_execstate *estate, PLpgSQL_stmt_assign *stmt)
1107 Assert(stmt->varno >= 0);
1109 exec_assign_expr(estate, estate->datums[stmt->varno], stmt->expr);
1111 return PLPGSQL_RC_OK;
1115 * exec_stmt_perform Evaluate query and discard result (but set
1116 * FOUND depending on whether at least one row
1121 exec_stmt_perform(PLpgSQL_execstate *estate, PLpgSQL_stmt_perform *stmt)
1123 PLpgSQL_expr *expr = stmt->expr;
1125 (void) exec_run_select(estate, expr, 0, NULL);
1126 exec_set_found(estate, (estate->eval_processed != 0));
1127 exec_eval_cleanup(estate);
1129 return PLPGSQL_RC_OK;
1133 * exec_stmt_getdiag Put internal PG information into
1134 * specified variables.
1138 exec_stmt_getdiag(PLpgSQL_execstate *estate, PLpgSQL_stmt_getdiag *stmt)
1142 foreach (lc, stmt->diag_items)
1144 PLpgSQL_diag_item *diag_item = (PLpgSQL_diag_item *) lfirst(lc);
1146 bool isnull = false;
1148 if (diag_item->target <= 0)
1151 var = estate->datums[diag_item->target];
1156 switch (diag_item->kind)
1158 case PLPGSQL_GETDIAG_ROW_COUNT:
1160 exec_assign_value(estate, var,
1161 UInt32GetDatum(estate->eval_processed),
1165 case PLPGSQL_GETDIAG_RESULT_OID:
1167 exec_assign_value(estate, var,
1168 ObjectIdGetDatum(estate->eval_lastoid),
1173 elog(ERROR, "unrecognized attribute request: %d",
1178 return PLPGSQL_RC_OK;
1182 * exec_stmt_if Evaluate a bool expression and
1183 * execute the true or false body
1188 exec_stmt_if(PLpgSQL_execstate *estate, PLpgSQL_stmt_if *stmt)
1193 value = exec_eval_boolean(estate, stmt->cond, &isnull);
1194 exec_eval_cleanup(estate);
1196 if (!isnull && value)
1198 if (stmt->true_body != NIL)
1199 return exec_stmts(estate, stmt->true_body);
1203 if (stmt->false_body != NIL)
1204 return exec_stmts(estate, stmt->false_body);
1207 return PLPGSQL_RC_OK;
1212 * exec_stmt_loop Loop over statements until
1217 exec_stmt_loop(PLpgSQL_execstate *estate, PLpgSQL_stmt_loop *stmt)
1221 int rc = exec_stmts(estate, stmt->body);
1228 case PLPGSQL_RC_EXIT:
1229 if (estate->exitlabel == NULL)
1230 return PLPGSQL_RC_OK;
1231 if (stmt->label == NULL)
1232 return PLPGSQL_RC_EXIT;
1233 if (strcmp(stmt->label, estate->exitlabel) != 0)
1234 return PLPGSQL_RC_EXIT;
1235 estate->exitlabel = NULL;
1236 return PLPGSQL_RC_OK;
1238 case PLPGSQL_RC_CONTINUE:
1239 if (estate->exitlabel == NULL)
1240 /* anonymous continue, so re-run the loop */
1242 else if (stmt->label != NULL &&
1243 strcmp(stmt->label, estate->exitlabel) == 0)
1244 /* label matches named continue, so re-run loop */
1245 estate->exitlabel = NULL;
1247 /* label doesn't match named continue, so propagate upward */
1248 return PLPGSQL_RC_CONTINUE;
1251 case PLPGSQL_RC_RETURN:
1252 return PLPGSQL_RC_RETURN;
1255 elog(ERROR, "unrecognized rc: %d", rc);
1259 return PLPGSQL_RC_OK;
1264 * exec_stmt_while Loop over statements as long
1265 * as an expression evaluates to
1266 * true or an exit occurs.
1270 exec_stmt_while(PLpgSQL_execstate *estate, PLpgSQL_stmt_while *stmt)
1278 value = exec_eval_boolean(estate, stmt->cond, &isnull);
1279 exec_eval_cleanup(estate);
1281 if (isnull || !value)
1284 rc = exec_stmts(estate, stmt->body);
1291 case PLPGSQL_RC_EXIT:
1292 if (estate->exitlabel == NULL)
1293 return PLPGSQL_RC_OK;
1294 if (stmt->label == NULL)
1295 return PLPGSQL_RC_EXIT;
1296 if (strcmp(stmt->label, estate->exitlabel))
1297 return PLPGSQL_RC_EXIT;
1298 estate->exitlabel = NULL;
1299 return PLPGSQL_RC_OK;
1301 case PLPGSQL_RC_CONTINUE:
1302 if (estate->exitlabel == NULL)
1303 /* anonymous continue, so re-run loop */
1305 else if (stmt->label != NULL &&
1306 strcmp(stmt->label, estate->exitlabel) == 0)
1307 /* label matches named continue, so re-run loop */
1308 estate->exitlabel = NULL;
1310 /* label doesn't match named continue, propagate upward */
1311 return PLPGSQL_RC_CONTINUE;
1314 case PLPGSQL_RC_RETURN:
1315 return PLPGSQL_RC_RETURN;
1318 elog(ERROR, "unrecognized rc: %d", rc);
1322 return PLPGSQL_RC_OK;
1327 * exec_stmt_fori Iterate an integer variable
1328 * from a lower to an upper value.
1329 * Loop can be left with exit.
1333 exec_stmt_fori(PLpgSQL_execstate *estate, PLpgSQL_stmt_fori *stmt)
1340 int rc = PLPGSQL_RC_OK;
1342 var = (PLpgSQL_var *) (estate->datums[stmt->var->varno]);
1345 * Get the value of the lower bound into the loop var
1347 value = exec_eval_expr(estate, stmt->lower, &isnull, &valtype);
1348 value = exec_cast_value(value, valtype, var->datatype->typoid,
1349 &(var->datatype->typinput),
1350 var->datatype->typioparam,
1351 var->datatype->atttypmod, isnull);
1354 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1355 errmsg("lower bound of FOR loop cannot be NULL")));
1357 var->isnull = false;
1358 exec_eval_cleanup(estate);
1361 * Get the value of the upper bound
1363 value = exec_eval_expr(estate, stmt->upper, &isnull, &valtype);
1364 value = exec_cast_value(value, valtype, var->datatype->typoid,
1365 &(var->datatype->typinput),
1366 var->datatype->typioparam,
1367 var->datatype->atttypmod, isnull);
1370 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1371 errmsg("upper bound of FOR loop cannot be NULL")));
1372 exec_eval_cleanup(estate);
1384 if ((int4) (var->value) < (int4) value)
1389 if ((int4) (var->value) > (int4) value)
1393 found = true; /* looped at least once */
1396 * Execute the statements
1398 rc = exec_stmts(estate, stmt->body);
1400 if (rc == PLPGSQL_RC_RETURN)
1401 break; /* return from function */
1402 else if (rc == PLPGSQL_RC_EXIT)
1404 if (estate->exitlabel == NULL)
1405 /* unlabelled exit, finish the current loop */
1407 else if (stmt->label != NULL &&
1408 strcmp(stmt->label, estate->exitlabel) == 0)
1410 /* labelled exit, matches the current stmt's label */
1411 estate->exitlabel = NULL;
1416 * otherwise, this is a labelled exit that does not match
1417 * the current statement's label, if any: return RC_EXIT
1418 * so that the EXIT continues to propagate up the stack.
1423 else if (rc == PLPGSQL_RC_CONTINUE)
1425 if (estate->exitlabel == NULL)
1426 /* anonymous continue, so re-run the current loop */
1428 else if (stmt->label != NULL &&
1429 strcmp(stmt->label, estate->exitlabel) == 0)
1431 /* label matches named continue, so re-run loop */
1432 estate->exitlabel = NULL;
1438 * otherwise, this is a named continue that does not
1439 * match the current statement's label, if any: return
1440 * RC_CONTINUE so that the CONTINUE will propagate up
1448 * Increase/decrease loop var
1457 * Set the FOUND variable to indicate the result of executing the loop
1458 * (namely, whether we looped one or more times). This must be set
1459 * here so that it does not interfere with the value of the FOUND
1460 * variable inside the loop processing itself.
1462 exec_set_found(estate, found);
1469 * exec_stmt_fors Execute a query, assign each
1470 * tuple to a record or row and
1471 * execute a group of statements
1476 exec_stmt_fors(PLpgSQL_execstate *estate, PLpgSQL_stmt_fors *stmt)
1478 PLpgSQL_rec *rec = NULL;
1479 PLpgSQL_row *row = NULL;
1480 SPITupleTable *tuptab;
1483 int rc = PLPGSQL_RC_OK;
1488 * Determine if we assign to a record or a row
1490 if (stmt->rec != NULL)
1491 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
1492 else if (stmt->row != NULL)
1493 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
1495 elog(ERROR, "unsupported target");
1498 * Open the implicit cursor for the statement and fetch the initial 10
1501 exec_run_select(estate, stmt->query, 0, &portal);
1503 SPI_cursor_fetch(portal, true, 10);
1504 tuptab = SPI_tuptable;
1508 * If the query didn't return any rows, set the target to NULL and
1509 * return with FOUND = false.
1512 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
1514 found = true; /* processed at least one tuple */
1521 for (i = 0; i < n; i++)
1524 * Assign the tuple to the target
1526 exec_move_row(estate, rec, row, tuptab->vals[i], tuptab->tupdesc);
1529 * Execute the statements
1531 rc = exec_stmts(estate, stmt->body);
1532 if (rc != PLPGSQL_RC_OK)
1534 if (rc == PLPGSQL_RC_EXIT)
1536 if (estate->exitlabel == NULL)
1537 /* unlabelled exit, finish the current loop */
1539 else if (stmt->label != NULL &&
1540 strcmp(stmt->label, estate->exitlabel) == 0)
1542 /* labelled exit, matches the current stmt's label */
1543 estate->exitlabel = NULL;
1548 * otherwise, we processed a labelled exit that does
1549 * not match the current statement's label, if any:
1550 * return RC_EXIT so that the EXIT continues to
1554 else if (rc == PLPGSQL_RC_CONTINUE)
1556 if (estate->exitlabel == NULL)
1558 /* anonymous continue, so re-run the current loop */
1562 else if (stmt->label != NULL &&
1563 strcmp(stmt->label, estate->exitlabel) == 0)
1565 /* label matches named continue, so re-run loop */
1567 estate->exitlabel = NULL;
1572 * otherwise, we processed a named continue
1573 * that does not match the current statement's
1574 * label, if any: return RC_CONTINUE so that the
1575 * CONTINUE will propagate up the stack.
1580 * We're aborting the loop, so cleanup and set FOUND.
1581 * (This code should match the code after the loop.)
1583 SPI_freetuptable(tuptab);
1584 SPI_cursor_close(portal);
1585 exec_set_found(estate, found);
1591 SPI_freetuptable(tuptab);
1594 * Fetch the next 50 tuples
1596 SPI_cursor_fetch(portal, true, 50);
1598 tuptab = SPI_tuptable;
1602 * Release last group of tuples
1604 SPI_freetuptable(tuptab);
1607 * Close the implicit cursor
1609 SPI_cursor_close(portal);
1612 * Set the FOUND variable to indicate the result of executing the loop
1613 * (namely, whether we looped one or more times). This must be set
1614 * here so that it does not interfere with the value of the FOUND
1615 * variable inside the loop processing itself.
1617 exec_set_found(estate, found);
1624 * exec_stmt_select Run a query and assign the first
1625 * row to a record or rowtype.
1629 exec_stmt_select(PLpgSQL_execstate *estate, PLpgSQL_stmt_select *stmt)
1631 PLpgSQL_rec *rec = NULL;
1632 PLpgSQL_row *row = NULL;
1633 SPITupleTable *tuptab;
1637 * Initialize the global found variable to false
1639 exec_set_found(estate, false);
1642 * Determine if we assign to a record or a row
1644 if (stmt->rec != NULL)
1645 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
1646 else if (stmt->row != NULL)
1647 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
1649 elog(ERROR, "unsupported target");
1654 exec_run_select(estate, stmt->query, 1, NULL);
1655 tuptab = estate->eval_tuptable;
1656 n = estate->eval_processed;
1659 * If the query didn't return any rows, set the target to NULL and
1664 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
1665 exec_eval_cleanup(estate);
1666 return PLPGSQL_RC_OK;
1670 * Put the result into the target and set found to true
1672 exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
1673 exec_set_found(estate, true);
1675 exec_eval_cleanup(estate);
1677 return PLPGSQL_RC_OK;
1682 * exec_stmt_exit Implements EXIT and CONTINUE
1684 * This begins the process of exiting / restarting a loop.
1688 exec_stmt_exit(PLpgSQL_execstate *estate, PLpgSQL_stmt_exit *stmt)
1691 * If the exit / continue has a condition, evaluate it
1693 if (stmt->cond != NULL)
1698 value = exec_eval_boolean(estate, stmt->cond, &isnull);
1699 exec_eval_cleanup(estate);
1700 if (isnull || value == false)
1701 return PLPGSQL_RC_OK;
1704 estate->exitlabel = stmt->label;
1706 return PLPGSQL_RC_EXIT;
1708 return PLPGSQL_RC_CONTINUE;
1713 * exec_stmt_return Evaluate an expression and start
1714 * returning from the function.
1718 exec_stmt_return(PLpgSQL_execstate *estate, PLpgSQL_stmt_return *stmt)
1721 * If processing a set-returning PL/PgSQL function, the final RETURN
1722 * indicates that the function is finished producing tuples. The rest
1723 * of the work will be done at the top level.
1725 if (estate->retisset)
1726 return PLPGSQL_RC_RETURN;
1728 /* initialize for null result (possibly a tuple) */
1729 estate->retval = (Datum) 0;
1730 estate->rettupdesc = NULL;
1731 estate->retisnull = true;
1733 if (stmt->retvarno >= 0)
1735 PLpgSQL_datum *retvar = estate->datums[stmt->retvarno];
1737 switch (retvar->dtype)
1739 case PLPGSQL_DTYPE_VAR:
1741 PLpgSQL_var *var = (PLpgSQL_var *) retvar;
1743 estate->retval = var->value;
1744 estate->retisnull = var->isnull;
1745 estate->rettype = var->datatype->typoid;
1749 case PLPGSQL_DTYPE_REC:
1751 PLpgSQL_rec *rec = (PLpgSQL_rec *) retvar;
1753 if (HeapTupleIsValid(rec->tup))
1755 estate->retval = (Datum) rec->tup;
1756 estate->rettupdesc = rec->tupdesc;
1757 estate->retisnull = false;
1762 case PLPGSQL_DTYPE_ROW:
1764 PLpgSQL_row *row = (PLpgSQL_row *) retvar;
1766 Assert(row->rowtupdesc);
1767 estate->retval = (Datum) make_tuple_from_row(estate, row,
1769 if (estate->retval == (Datum) NULL) /* should not happen */
1770 elog(ERROR, "row not compatible with its own tupdesc");
1771 estate->rettupdesc = row->rowtupdesc;
1772 estate->retisnull = false;
1777 elog(ERROR, "unrecognized dtype: %d", retvar->dtype);
1780 return PLPGSQL_RC_RETURN;
1783 if (stmt->expr != NULL)
1785 if (estate->retistuple)
1787 exec_run_select(estate, stmt->expr, 1, NULL);
1788 if (estate->eval_processed > 0)
1790 estate->retval = (Datum) estate->eval_tuptable->vals[0];
1791 estate->rettupdesc = estate->eval_tuptable->tupdesc;
1792 estate->retisnull = false;
1797 /* Normal case for scalar results */
1798 estate->retval = exec_eval_expr(estate, stmt->expr,
1799 &(estate->retisnull),
1800 &(estate->rettype));
1803 return PLPGSQL_RC_RETURN;
1807 * Special hack for function returning VOID: instead of NULL, return a
1808 * non-null VOID value. This is of dubious importance but is kept for
1809 * backwards compatibility. Note that the only other way to get here
1810 * is to have written "RETURN NULL" in a function returning tuple.
1812 if (estate->fn_rettype == VOIDOID)
1814 estate->retval = (Datum) 0;
1815 estate->retisnull = false;
1816 estate->rettype = VOIDOID;
1819 return PLPGSQL_RC_RETURN;
1823 * exec_stmt_return_next Evaluate an expression and add it to the
1824 * list of tuples returned by the current
1829 exec_stmt_return_next(PLpgSQL_execstate *estate,
1830 PLpgSQL_stmt_return_next *stmt)
1835 bool free_tuple = false;
1837 if (!estate->retisset)
1839 (errcode(ERRCODE_SYNTAX_ERROR),
1840 errmsg("cannot use RETURN NEXT in a non-SETOF function")));
1842 if (estate->tuple_store == NULL)
1843 exec_init_tuple_store(estate);
1845 /* rettupdesc will be filled by exec_init_tuple_store */
1846 tupdesc = estate->rettupdesc;
1847 natts = tupdesc->natts;
1849 if (stmt->retvarno >= 0)
1851 PLpgSQL_datum *retvar = estate->datums[stmt->retvarno];
1853 switch (retvar->dtype)
1855 case PLPGSQL_DTYPE_VAR:
1857 PLpgSQL_var *var = (PLpgSQL_var *) retvar;
1858 Datum retval = var->value;
1859 bool isNull = var->isnull;
1863 (errcode(ERRCODE_DATATYPE_MISMATCH),
1864 errmsg("wrong result type supplied in RETURN NEXT")));
1866 /* coerce type if needed */
1867 retval = exec_simple_cast_value(retval,
1868 var->datatype->typoid,
1869 tupdesc->attrs[0]->atttypid,
1870 tupdesc->attrs[0]->atttypmod,
1873 tuple = heap_form_tuple(tupdesc, &retval, &isNull);
1879 case PLPGSQL_DTYPE_REC:
1881 PLpgSQL_rec *rec = (PLpgSQL_rec *) retvar;
1883 if (!HeapTupleIsValid(rec->tup))
1885 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1886 errmsg("record \"%s\" is not assigned yet",
1888 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
1889 if (!compatible_tupdesc(tupdesc, rec->tupdesc))
1891 (errcode(ERRCODE_DATATYPE_MISMATCH),
1892 errmsg("wrong record type supplied in RETURN NEXT")));
1897 case PLPGSQL_DTYPE_ROW:
1899 PLpgSQL_row *row = (PLpgSQL_row *) retvar;
1901 tuple = make_tuple_from_row(estate, row, tupdesc);
1904 (errcode(ERRCODE_DATATYPE_MISMATCH),
1905 errmsg("wrong record type supplied in RETURN NEXT")));
1911 elog(ERROR, "unrecognized dtype: %d", retvar->dtype);
1912 tuple = NULL; /* keep compiler quiet */
1916 else if (stmt->expr)
1924 (errcode(ERRCODE_DATATYPE_MISMATCH),
1925 errmsg("wrong result type supplied in RETURN NEXT")));
1927 retval = exec_eval_expr(estate,
1932 /* coerce type if needed */
1933 retval = exec_simple_cast_value(retval,
1935 tupdesc->attrs[0]->atttypid,
1936 tupdesc->attrs[0]->atttypmod,
1939 tuple = heap_form_tuple(tupdesc, &retval, &isNull);
1943 exec_eval_cleanup(estate);
1948 (errcode(ERRCODE_SYNTAX_ERROR),
1949 errmsg("RETURN NEXT must have a parameter")));
1950 tuple = NULL; /* keep compiler quiet */
1953 if (HeapTupleIsValid(tuple))
1955 MemoryContext oldcxt;
1957 oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
1958 tuplestore_puttuple(estate->tuple_store, tuple);
1959 MemoryContextSwitchTo(oldcxt);
1962 heap_freetuple(tuple);
1965 return PLPGSQL_RC_OK;
1969 exec_init_tuple_store(PLpgSQL_execstate *estate)
1971 ReturnSetInfo *rsi = estate->rsi;
1972 MemoryContext oldcxt;
1975 * Check caller can handle a set result in the way we want
1977 if (!rsi || !IsA(rsi, ReturnSetInfo) ||
1978 (rsi->allowedModes & SFRM_Materialize) == 0 ||
1979 rsi->expectedDesc == NULL)
1981 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1982 errmsg("set-valued function called in context that cannot accept a set")));
1984 estate->tuple_store_cxt = rsi->econtext->ecxt_per_query_memory;
1986 oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
1987 estate->tuple_store = tuplestore_begin_heap(true, false, work_mem);
1988 MemoryContextSwitchTo(oldcxt);
1990 estate->rettupdesc = rsi->expectedDesc;
1994 * exec_stmt_raise Build a message and throw it with elog()
1998 exec_stmt_raise(PLpgSQL_execstate *estate, PLpgSQL_stmt_raise *stmt)
2002 ListCell *current_param;
2004 plpgsql_dstring_init(&ds);
2005 current_param = list_head(stmt->params);
2007 for (cp = stmt->message; *cp; cp++)
2010 * Occurrences of a single % are replaced by the next parameter's
2011 * external representation. Double %'s are converted to one %.
2022 plpgsql_dstring_append_char(&ds, cp[1]);
2027 if (current_param == NULL)
2029 (errcode(ERRCODE_SYNTAX_ERROR),
2030 errmsg("too few parameters specified for RAISE")));
2032 paramvalue = exec_eval_expr(estate,
2033 (PLpgSQL_expr *) lfirst(current_param),
2040 extval = convert_value_to_string(paramvalue, paramtypeid);
2041 plpgsql_dstring_append(&ds, extval);
2042 current_param = lnext(current_param);
2043 exec_eval_cleanup(estate);
2047 plpgsql_dstring_append_char(&ds, cp[0]);
2051 * If more parameters were specified than were required to process
2052 * the format string, throw an error
2054 if (current_param != NULL)
2056 (errcode(ERRCODE_SYNTAX_ERROR),
2057 errmsg("too many parameters specified for RAISE")));
2060 * Throw the error (may or may not come back)
2062 estate->err_text = raise_skip_msg; /* suppress traceback of raise */
2064 ereport(stmt->elog_level,
2065 ((stmt->elog_level >= ERROR) ? errcode(ERRCODE_RAISE_EXCEPTION) : 0,
2066 errmsg_internal("%s", plpgsql_dstring_get(&ds))));
2068 estate->err_text = NULL; /* un-suppress... */
2070 plpgsql_dstring_free(&ds);
2072 return PLPGSQL_RC_OK;
2077 * Initialize a mostly empty execution state
2081 plpgsql_estate_setup(PLpgSQL_execstate *estate,
2082 PLpgSQL_function *func,
2085 estate->retval = (Datum) 0;
2086 estate->retisnull = true;
2087 estate->rettype = InvalidOid;
2089 estate->fn_rettype = func->fn_rettype;
2090 estate->retistuple = func->fn_retistuple;
2091 estate->retisset = func->fn_retset;
2093 estate->readonly_func = func->fn_readonly;
2095 estate->rettupdesc = NULL;
2096 estate->exitlabel = NULL;
2098 estate->tuple_store = NULL;
2099 estate->tuple_store_cxt = NULL;
2102 estate->trig_nargs = 0;
2103 estate->trig_argv = NULL;
2105 estate->found_varno = func->found_varno;
2106 estate->ndatums = func->ndatums;
2107 estate->datums = palloc(sizeof(PLpgSQL_datum *) * estate->ndatums);
2108 /* caller is expected to fill the datums array */
2110 estate->eval_tuptable = NULL;
2111 estate->eval_processed = 0;
2112 estate->eval_lastoid = InvalidOid;
2114 estate->err_func = func;
2115 estate->err_stmt = NULL;
2116 estate->err_text = NULL;
2119 * Create an EState for evaluation of simple expressions, if there's
2120 * not one already in the current transaction. The EState is made a
2121 * child of TopTransactionContext so it will have the right lifespan.
2123 if (simple_eval_estate == NULL)
2125 MemoryContext oldcontext;
2127 oldcontext = MemoryContextSwitchTo(TopTransactionContext);
2128 simple_eval_estate = CreateExecutorState();
2129 MemoryContextSwitchTo(oldcontext);
2133 * Create an expression context for simple expressions.
2134 * This must be a child of simple_eval_estate.
2136 estate->eval_econtext = CreateExprContext(simple_eval_estate);
2140 * Release temporary memory used by expression/subselect evaluation
2142 * NB: the result of the evaluation is no longer valid after this is done,
2143 * unless it is a pass-by-value datatype.
2147 exec_eval_cleanup(PLpgSQL_execstate *estate)
2149 /* Clear result of a full SPI_execute */
2150 if (estate->eval_tuptable != NULL)
2151 SPI_freetuptable(estate->eval_tuptable);
2152 estate->eval_tuptable = NULL;
2154 /* Clear result of exec_eval_simple_expr (but keep the econtext) */
2155 if (estate->eval_econtext != NULL)
2156 ResetExprContext(estate->eval_econtext);
2161 * Generate a prepared plan
2165 exec_prepare_plan(PLpgSQL_execstate *estate,
2169 _SPI_plan *spi_plan;
2174 * We need a temporary argtypes array to load with data. (The finished
2175 * plan structure will contain a copy of it.)
2177 argtypes = (Oid *) palloc(expr->nparams * sizeof(Oid));
2179 for (i = 0; i < expr->nparams; i++)
2184 exec_eval_datum(estate, estate->datums[expr->params[i]],
2186 &argtypes[i], ¶mval, ¶misnull);
2190 * Generate and save the plan
2192 plan = SPI_prepare(expr->query, expr->nparams, argtypes);
2195 /* Some SPI errors deserve specific error messages */
2198 case SPI_ERROR_COPY:
2200 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2201 errmsg("cannot COPY to/from client in PL/pgSQL")));
2202 case SPI_ERROR_CURSOR:
2204 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2205 errmsg("cannot manipulate cursors directly in PL/pgSQL"),
2206 errhint("Use PL/pgSQL's cursor features instead.")));
2207 case SPI_ERROR_TRANSACTION:
2209 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2210 errmsg("cannot begin/end transactions in PL/pgSQL"),
2211 errhint("Use a BEGIN block with an EXCEPTION clause instead.")));
2213 elog(ERROR, "SPI_prepare failed for \"%s\": %s",
2214 expr->query, SPI_result_code_string(SPI_result));
2217 expr->plan = SPI_saveplan(plan);
2218 spi_plan = (_SPI_plan *) expr->plan;
2219 expr->plan_argtypes = spi_plan->argtypes;
2220 expr->expr_simple_expr = NULL;
2221 exec_simple_check_plan(expr);
2229 * exec_stmt_execsql Execute an SQL statement not
2230 * returning any data.
2234 exec_stmt_execsql(PLpgSQL_execstate *estate,
2235 PLpgSQL_stmt_execsql *stmt)
2241 PLpgSQL_expr *expr = stmt->sqlstmt;
2244 * On the first call for this expression generate the plan
2246 if (expr->plan == NULL)
2247 exec_prepare_plan(estate, expr);
2250 * Now build up the values and nulls arguments for SPI_execute_plan()
2252 values = (Datum *) palloc(expr->nparams * sizeof(Datum));
2253 nulls = (char *) palloc(expr->nparams * sizeof(char));
2255 for (i = 0; i < expr->nparams; i++)
2257 PLpgSQL_datum *datum = estate->datums[expr->params[i]];
2261 exec_eval_datum(estate, datum, expr->plan_argtypes[i],
2262 ¶mtypeid, &values[i], ¶misnull);
2272 rc = SPI_execute_plan(expr->plan, values, nulls,
2273 estate->readonly_func, 0);
2276 case SPI_OK_UTILITY:
2277 case SPI_OK_SELINTO:
2285 * If the INSERT, DELETE, or UPDATE query affected at least
2286 * one tuple, set the magic 'FOUND' variable to true. This
2287 * conforms with the behavior of PL/SQL.
2289 exec_set_found(estate, (SPI_processed != 0));
2294 (errcode(ERRCODE_SYNTAX_ERROR),
2295 errmsg("SELECT query has no destination for result data"),
2296 errhint("If you want to discard the results, use PERFORM instead.")));
2299 elog(ERROR, "SPI_execute_plan failed executing query \"%s\": %s",
2300 expr->query, SPI_result_code_string(rc));
2304 * Release any result tuples from SPI_execute_plan (probably shouldn't be
2307 SPI_freetuptable(SPI_tuptable);
2309 /* Save result info for GET DIAGNOSTICS */
2310 estate->eval_processed = SPI_processed;
2311 estate->eval_lastoid = SPI_lastoid;
2316 return PLPGSQL_RC_OK;
2321 * exec_stmt_dynexecute Execute a dynamic SQL query not
2322 * returning any data.
2326 exec_stmt_dynexecute(PLpgSQL_execstate *estate,
2327 PLpgSQL_stmt_dynexecute *stmt)
2330 bool isnull = false;
2334 PLpgSQL_rec *rec = NULL;
2335 PLpgSQL_row *row = NULL;
2337 if (stmt->rec != NULL)
2338 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
2339 else if (stmt->row != NULL)
2340 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
2343 * First we evaluate the string expression after the EXECUTE keyword.
2344 * It's result is the querystring we have to execute.
2346 query = exec_eval_expr(estate, stmt->query, &isnull, &restype);
2349 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2350 errmsg("cannot EXECUTE a null querystring")));
2352 /* Get the C-String representation */
2353 querystr = convert_value_to_string(query, restype);
2355 exec_eval_cleanup(estate);
2358 * Call SPI_execute() without preparing a saved plan. The returncode can
2359 * be any standard OK. Note that while a SELECT is allowed, its
2360 * results will be discarded unless an INTO clause is specified.
2362 exec_res = SPI_execute(querystr, estate->readonly_func, 0);
2364 /* Assign to INTO variable */
2367 if (exec_res != SPI_OK_SELECT)
2369 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2370 errmsg("EXECUTE ... INTO is only for SELECT")));
2373 if (SPI_processed == 0)
2374 exec_move_row(estate, rec, row, NULL, SPI_tuptable->tupdesc);
2376 exec_move_row(estate, rec, row,
2377 SPI_tuptable->vals[0], SPI_tuptable->tupdesc);
2387 case SPI_OK_UTILITY:
2393 * Also allow a zero return, which implies the querystring
2394 * contained no commands.
2398 case SPI_OK_SELINTO:
2401 * We want to disallow SELECT INTO for now, because its
2402 * behavior is not consistent with SELECT INTO in a normal
2403 * plpgsql context. (We need to reimplement EXECUTE to parse
2404 * the string as a plpgsql command, not just feed it to
2405 * SPI_execute.) However, CREATE AS should be allowed ... and
2406 * since it produces the same parsetree as SELECT INTO,
2407 * there's no way to tell the difference except to look at the
2408 * source text. Wotta kluge!
2413 for (ptr = querystr; *ptr; ptr++)
2414 if (!isspace((unsigned char) *ptr))
2416 if (*ptr == 'S' || *ptr == 's')
2418 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2419 errmsg("EXECUTE of SELECT ... INTO is not implemented yet")));
2423 /* Some SPI errors deserve specific error messages */
2424 case SPI_ERROR_COPY:
2426 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2427 errmsg("cannot COPY to/from client in PL/pgSQL")));
2428 case SPI_ERROR_CURSOR:
2430 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2431 errmsg("cannot manipulate cursors directly in PL/pgSQL"),
2432 errhint("Use PL/pgSQL's cursor features instead.")));
2433 case SPI_ERROR_TRANSACTION:
2435 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2436 errmsg("cannot begin/end transactions in PL/pgSQL"),
2437 errhint("Use a BEGIN block with an EXCEPTION clause instead.")));
2440 elog(ERROR, "SPI_execute failed executing query \"%s\": %s",
2441 querystr, SPI_result_code_string(exec_res));
2445 /* Release any result from SPI_execute, as well as the querystring */
2446 SPI_freetuptable(SPI_tuptable);
2449 /* Save result info for GET DIAGNOSTICS */
2450 estate->eval_processed = SPI_processed;
2451 estate->eval_lastoid = SPI_lastoid;
2453 return PLPGSQL_RC_OK;
2458 * exec_stmt_dynfors Execute a dynamic query, assign each
2459 * tuple to a record or row and
2460 * execute a group of statements
2465 exec_stmt_dynfors(PLpgSQL_execstate *estate, PLpgSQL_stmt_dynfors *stmt)
2471 PLpgSQL_rec *rec = NULL;
2472 PLpgSQL_row *row = NULL;
2473 SPITupleTable *tuptab;
2480 * Determine if we assign to a record or a row
2482 if (stmt->rec != NULL)
2483 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
2484 else if (stmt->row != NULL)
2485 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
2487 elog(ERROR, "unsupported target");
2490 * Evaluate the string expression after the EXECUTE keyword. It's
2491 * result is the querystring we have to execute.
2493 query = exec_eval_expr(estate, stmt->query, &isnull, &restype);
2496 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2497 errmsg("cannot EXECUTE a null querystring")));
2499 /* Get the C-String representation */
2500 querystr = convert_value_to_string(query, restype);
2502 exec_eval_cleanup(estate);
2505 * Prepare a plan and open an implicit cursor for the query
2507 plan = SPI_prepare(querystr, 0, NULL);
2509 elog(ERROR, "SPI_prepare failed for \"%s\": %s",
2510 querystr, SPI_result_code_string(SPI_result));
2511 portal = SPI_cursor_open(NULL, plan, NULL, NULL,
2512 estate->readonly_func);
2514 elog(ERROR, "could not open implicit cursor for query \"%s\": %s",
2515 querystr, SPI_result_code_string(SPI_result));
2520 * Fetch the initial 10 tuples
2522 SPI_cursor_fetch(portal, true, 10);
2523 tuptab = SPI_tuptable;
2527 * If the query didn't return any rows, set the target to NULL and
2528 * return with FOUND = false.
2531 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
2533 found = true; /* processed at least one tuple */
2542 for (i = 0; i < n; i++)
2547 * Assign the tuple to the target
2549 exec_move_row(estate, rec, row, tuptab->vals[i], tuptab->tupdesc);
2552 * Execute the statements
2554 rc = exec_stmts(estate, stmt->body);
2556 if (rc != PLPGSQL_RC_OK)
2558 if (rc == PLPGSQL_RC_EXIT)
2560 if (estate->exitlabel == NULL)
2561 /* unlabelled exit, finish the current loop */
2563 else if (stmt->label != NULL &&
2564 strcmp(stmt->label, estate->exitlabel) == 0)
2566 /* labelled exit, matches the current stmt's label */
2567 estate->exitlabel = NULL;
2572 * otherwise, we processed a labelled exit that does
2573 * not match the current statement's label, if any:
2574 * return RC_EXIT so that the EXIT continues to
2578 else if (rc == PLPGSQL_RC_CONTINUE)
2580 if (estate->exitlabel == NULL)
2581 /* unlabelled continue, continue the current loop */
2583 else if (stmt->label != NULL &&
2584 strcmp(stmt->label, estate->exitlabel) == 0)
2586 /* labelled continue, matches the current stmt's label */
2587 estate->exitlabel = NULL;
2592 * otherwise, we process a labelled continue that
2593 * does not match the current statement's label,
2594 * so propagate RC_CONTINUE upward in the stack.
2599 * We're aborting the loop, so cleanup and set FOUND.
2600 * (This code should match the code after the loop.)
2602 SPI_freetuptable(tuptab);
2603 SPI_cursor_close(portal);
2604 exec_set_found(estate, found);
2610 SPI_freetuptable(tuptab);
2613 * Fetch the next 50 tuples
2615 SPI_cursor_fetch(portal, true, 50);
2617 tuptab = SPI_tuptable;
2621 * Release last group of tuples
2623 SPI_freetuptable(tuptab);
2626 * Close the implicit cursor
2628 SPI_cursor_close(portal);
2631 * Set the FOUND variable to indicate the result of executing the loop
2632 * (namely, whether we looped one or more times). This must be set
2633 * here so that it does not interfere with the value of the FOUND
2634 * variable inside the loop processing itself.
2636 exec_set_found(estate, found);
2638 return PLPGSQL_RC_OK;
2643 * exec_stmt_open Execute an OPEN cursor statement
2647 exec_stmt_open(PLpgSQL_execstate *estate, PLpgSQL_stmt_open *stmt)
2649 PLpgSQL_var *curvar = NULL;
2650 char *curname = NULL;
2651 PLpgSQL_expr *query = NULL;
2660 * Get the cursor variable and if it has an assigned name, check
2661 * that it's not in use currently.
2664 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
2665 if (!curvar->isnull)
2667 curname = DatumGetCString(DirectFunctionCall1(textout, curvar->value));
2668 if (SPI_cursor_find(curname) != NULL)
2670 (errcode(ERRCODE_DUPLICATE_CURSOR),
2671 errmsg("cursor \"%s\" already in use", curname)));
2675 * Process the OPEN according to it's type.
2678 if (stmt->query != NULL)
2681 * This is an OPEN refcursor FOR SELECT ...
2683 * We just make sure the query is planned. The real work is
2687 query = stmt->query;
2688 if (query->plan == NULL)
2689 exec_prepare_plan(estate, query);
2691 else if (stmt->dynquery != NULL)
2694 * This is an OPEN refcursor FOR EXECUTE ...
2703 * We evaluate the string expression after the
2704 * EXECUTE keyword. It's result is the querystring we have
2708 queryD = exec_eval_expr(estate, stmt->dynquery, &isnull, &restype);
2711 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2712 errmsg("cannot EXECUTE a null querystring")));
2714 /* Get the C-String representation */
2715 querystr = convert_value_to_string(queryD, restype);
2717 exec_eval_cleanup(estate);
2720 * Now we prepare a query plan for it and open a cursor
2723 curplan = SPI_prepare(querystr, 0, NULL);
2724 if (curplan == NULL)
2725 elog(ERROR, "SPI_prepare failed for \"%s\": %s",
2726 querystr, SPI_result_code_string(SPI_result));
2727 portal = SPI_cursor_open(curname, curplan, NULL, NULL,
2728 estate->readonly_func);
2730 elog(ERROR, "could not open cursor for query \"%s\": %s",
2731 querystr, SPI_result_code_string(SPI_result));
2733 SPI_freeplan(curplan);
2736 * Store the eventually assigned cursor name in the cursor variable
2740 curvar->value = DirectFunctionCall1(textin, CStringGetDatum(portal->name));
2741 curvar->isnull = false;
2742 curvar->freeval = true;
2744 return PLPGSQL_RC_OK;
2749 * This is an OPEN cursor
2751 * Note: parser should already have checked that statement supplies
2752 * args iff cursor needs them, but we check again to be safe.
2755 if (stmt->argquery != NULL)
2758 * Er - OPEN CURSOR (args). We fake a SELECT ... INTO ...
2759 * statement to evaluate the args and put 'em into the
2763 PLpgSQL_stmt_select set_args;
2765 if (curvar->cursor_explicit_argrow < 0)
2767 (errcode(ERRCODE_SYNTAX_ERROR),
2768 errmsg("arguments given for cursor without arguments")));
2770 memset(&set_args, 0, sizeof(set_args));
2771 set_args.cmd_type = PLPGSQL_STMT_SELECT;
2772 set_args.lineno = stmt->lineno;
2773 set_args.row = (PLpgSQL_row *)
2774 (estate->datums[curvar->cursor_explicit_argrow]);
2775 set_args.query = stmt->argquery;
2777 if (exec_stmt_select(estate, &set_args) != PLPGSQL_RC_OK)
2778 elog(ERROR, "open cursor failed during argument processing");
2782 if (curvar->cursor_explicit_argrow >= 0)
2784 (errcode(ERRCODE_SYNTAX_ERROR),
2785 errmsg("arguments required for cursor")));
2788 query = curvar->cursor_explicit_expr;
2789 if (query->plan == NULL)
2790 exec_prepare_plan(estate, query);
2794 * Here we go if we have a saved plan where we have to put
2795 * values into, either from an explicit cursor or from a
2796 * refcursor opened with OPEN ... FOR SELECT ...;
2799 values = (Datum *) palloc(query->nparams * sizeof(Datum));
2800 nulls = (char *) palloc(query->nparams * sizeof(char));
2802 for (i = 0; i < query->nparams; i++)
2804 PLpgSQL_datum *datum = estate->datums[query->params[i]];
2808 exec_eval_datum(estate, datum, query->plan_argtypes[i],
2809 ¶mtypeid, &values[i], ¶misnull);
2820 portal = SPI_cursor_open(curname, query->plan, values, nulls,
2821 estate->readonly_func);
2823 elog(ERROR, "could not open cursor: %s",
2824 SPI_result_code_string(SPI_result));
2832 * Store the eventually assigned portal name in the cursor variable
2836 curvar->value = DirectFunctionCall1(textin, CStringGetDatum(portal->name));
2837 curvar->isnull = false;
2838 curvar->freeval = true;
2840 return PLPGSQL_RC_OK;
2845 * exec_stmt_fetch Fetch from a cursor into a target
2849 exec_stmt_fetch(PLpgSQL_execstate *estate, PLpgSQL_stmt_fetch *stmt)
2851 PLpgSQL_var *curvar = NULL;
2852 PLpgSQL_rec *rec = NULL;
2853 PLpgSQL_row *row = NULL;
2854 SPITupleTable *tuptab;
2860 * Get the portal of the cursor by name
2863 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
2866 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2867 errmsg("cursor variable \"%s\" is NULL", curvar->refname)));
2868 curname = DatumGetCString(DirectFunctionCall1(textout, curvar->value));
2870 portal = SPI_cursor_find(curname);
2873 (errcode(ERRCODE_UNDEFINED_CURSOR),
2874 errmsg("cursor \"%s\" does not exist", curname)));
2878 * Determine if we fetch into a record or a row
2881 if (stmt->rec != NULL)
2882 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
2883 else if (stmt->row != NULL)
2884 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
2886 elog(ERROR, "unsupported target");
2889 * Fetch 1 tuple from the cursor
2892 SPI_cursor_fetch(portal, true, 1);
2893 tuptab = SPI_tuptable;
2897 * Set the target and the global FOUND variable appropriately.
2902 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
2903 exec_set_found(estate, false);
2907 exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
2908 exec_set_found(estate, true);
2911 SPI_freetuptable(tuptab);
2913 return PLPGSQL_RC_OK;
2918 * exec_stmt_close Close a cursor
2922 exec_stmt_close(PLpgSQL_execstate *estate, PLpgSQL_stmt_close *stmt)
2924 PLpgSQL_var *curvar = NULL;
2929 * Get the portal of the cursor by name
2932 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
2935 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2936 errmsg("cursor variable \"%s\" is NULL", curvar->refname)));
2937 curname = DatumGetCString(DirectFunctionCall1(textout, curvar->value));
2939 portal = SPI_cursor_find(curname);
2942 (errcode(ERRCODE_UNDEFINED_CURSOR),
2943 errmsg("cursor \"%s\" does not exist", curname)));
2950 SPI_cursor_close(portal);
2952 return PLPGSQL_RC_OK;
2957 * exec_assign_expr Put an expression's result into
2962 exec_assign_expr(PLpgSQL_execstate *estate, PLpgSQL_datum *target,
2967 bool isnull = false;
2969 value = exec_eval_expr(estate, expr, &isnull, &valtype);
2970 exec_assign_value(estate, target, value, valtype, &isnull);
2971 exec_eval_cleanup(estate);
2976 * exec_assign_value Put a value into a target field
2980 exec_assign_value(PLpgSQL_execstate *estate,
2981 PLpgSQL_datum *target,
2982 Datum value, Oid valtype, bool *isNull)
2984 switch (target->dtype)
2986 case PLPGSQL_DTYPE_VAR:
2989 * Target is a variable
2991 PLpgSQL_var *var = (PLpgSQL_var *) target;
2994 newvalue = exec_cast_value(value, valtype, var->datatype->typoid,
2995 &(var->datatype->typinput),
2996 var->datatype->typioparam,
2997 var->datatype->atttypmod,
3000 if (*isNull && var->notnull)
3002 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3003 errmsg("NULL cannot be assigned to variable \"%s\" declared NOT NULL",
3007 * If type is by-reference, make sure we have a freshly
3008 * palloc'd copy; the originally passed value may not live
3009 * as long as the variable! But we don't need to re-copy
3010 * if exec_cast_value performed a conversion; its output
3011 * must already be palloc'd.
3013 if (!var->datatype->typbyval && !*isNull)
3015 if (newvalue == value)
3016 newvalue = datumCopy(newvalue,
3018 var->datatype->typlen);
3022 * Now free the old value. (We can't do this any earlier
3023 * because of the possibility that we are assigning the
3024 * var's old value to it, eg "foo := foo". We could optimize
3025 * out the assignment altogether in such cases, but it's too
3026 * infrequent to be worth testing for.)
3030 var->value = newvalue;
3031 var->isnull = *isNull;
3032 if (!var->datatype->typbyval && !*isNull)
3033 var->freeval = true;
3037 case PLPGSQL_DTYPE_ROW:
3040 * Target is a row variable
3042 PLpgSQL_row *row = (PLpgSQL_row *) target;
3044 /* Source must be of RECORD or composite type */
3045 if (!(valtype == RECORDOID ||
3046 get_typtype(valtype) == 'c'))
3048 (errcode(ERRCODE_DATATYPE_MISMATCH),
3049 errmsg("cannot assign non-composite value to a row variable")));
3052 /* If source is null, just assign nulls to the row */
3053 exec_move_row(estate, NULL, row, NULL, NULL);
3061 HeapTupleData tmptup;
3063 /* Else source is a tuple Datum, safe to do this: */
3064 td = DatumGetHeapTupleHeader(value);
3065 /* Extract rowtype info and find a tupdesc */
3066 tupType = HeapTupleHeaderGetTypeId(td);
3067 tupTypmod = HeapTupleHeaderGetTypMod(td);
3068 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
3069 /* Build a temporary HeapTuple control structure */
3070 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
3071 ItemPointerSetInvalid(&(tmptup.t_self));
3072 tmptup.t_tableOid = InvalidOid;
3074 exec_move_row(estate, NULL, row, &tmptup, tupdesc);
3079 case PLPGSQL_DTYPE_REC:
3082 * Target is a record variable
3084 PLpgSQL_rec *rec = (PLpgSQL_rec *) target;
3086 /* Source must be of RECORD or composite type */
3087 if (!(valtype == RECORDOID ||
3088 get_typtype(valtype) == 'c'))
3090 (errcode(ERRCODE_DATATYPE_MISMATCH),
3091 errmsg("cannot assign non-composite value to a record variable")));
3094 /* If source is null, just assign nulls to the record */
3095 exec_move_row(estate, rec, NULL, NULL, NULL);
3103 HeapTupleData tmptup;
3105 /* Else source is a tuple Datum, safe to do this: */
3106 td = DatumGetHeapTupleHeader(value);
3107 /* Extract rowtype info and find a tupdesc */
3108 tupType = HeapTupleHeaderGetTypeId(td);
3109 tupTypmod = HeapTupleHeaderGetTypMod(td);
3110 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
3111 /* Build a temporary HeapTuple control structure */
3112 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
3113 ItemPointerSetInvalid(&(tmptup.t_self));
3114 tmptup.t_tableOid = InvalidOid;
3116 exec_move_row(estate, rec, NULL, &tmptup, tupdesc);
3121 case PLPGSQL_DTYPE_RECFIELD:
3124 * Target is a field of a record
3126 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) target;
3139 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
3142 * Check that there is already a tuple in the record. We
3143 * need that because records don't have any predefined
3146 if (!HeapTupleIsValid(rec->tup))
3148 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3149 errmsg("record \"%s\" is not assigned yet",
3151 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
3154 * Get the number of the records field to change and the
3155 * number of attributes in the tuple.
3157 fno = SPI_fnumber(rec->tupdesc, recfield->fieldname);
3158 if (fno == SPI_ERROR_NOATTRIBUTE)
3160 (errcode(ERRCODE_UNDEFINED_COLUMN),
3161 errmsg("record \"%s\" has no field \"%s\"",
3162 rec->refname, recfield->fieldname)));
3164 natts = rec->tupdesc->natts;
3167 * Set up values/datums arrays for heap_formtuple. For
3168 * all the attributes except the one we want to replace,
3169 * use the value that's in the old tuple.
3171 values = palloc(sizeof(Datum) * natts);
3172 nulls = palloc(natts);
3174 for (i = 0; i < natts; i++)
3178 values[i] = SPI_getbinval(rec->tup, rec->tupdesc,
3187 * Now insert the new value, being careful to cast it to
3190 atttype = SPI_gettypeid(rec->tupdesc, fno + 1);
3191 atttypmod = rec->tupdesc->attrs[fno]->atttypmod;
3192 attisnull = *isNull;
3193 values[fno] = exec_simple_cast_value(value,
3204 * Avoid leaking the result of exec_simple_cast_value, if
3205 * it performed a conversion to a pass-by-ref type.
3207 if (!attisnull && values[fno] != value && !get_typbyval(atttype))
3208 mustfree = DatumGetPointer(values[fno]);
3213 * Now call heap_formtuple() to create a new tuple that
3214 * replaces the old one in the record.
3216 newtup = heap_formtuple(rec->tupdesc, values, nulls);
3219 heap_freetuple(rec->tup);
3222 rec->freetup = true;
3232 case PLPGSQL_DTYPE_ARRAYELEM:
3236 PLpgSQL_expr *subscripts[MAXDIM];
3237 int subscriptvals[MAXDIM];
3238 bool havenullsubscript,
3246 Datum oldarraydatum,
3248 ArrayType *oldarrayval;
3249 ArrayType *newarrayval;
3252 * Target is an element of an array
3254 * To handle constructs like x[1][2] := something, we have to
3255 * be prepared to deal with a chain of arrayelem datums.
3256 * Chase back to find the base array datum, and save the
3257 * subscript expressions as we go. (We are scanning right
3258 * to left here, but want to evaluate the subscripts
3259 * left-to-right to minimize surprises.)
3264 PLpgSQL_arrayelem *arrayelem = (PLpgSQL_arrayelem *) target;
3266 if (nsubscripts >= MAXDIM)
3268 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
3269 errmsg("number of array dimensions exceeds the maximum allowed, %d",
3271 subscripts[nsubscripts++] = arrayelem->subscript;
3272 target = estate->datums[arrayelem->arrayparentno];
3273 } while (target->dtype == PLPGSQL_DTYPE_ARRAYELEM);
3275 /* Fetch current value of array datum */
3276 exec_eval_datum(estate, target, InvalidOid,
3277 &arraytypeid, &oldarraydatum, &oldarrayisnull);
3279 arrayelemtypeid = get_element_type(arraytypeid);
3280 if (!OidIsValid(arrayelemtypeid))
3282 (errcode(ERRCODE_DATATYPE_MISMATCH),
3283 errmsg("subscripted object is not an array")));
3285 get_typlenbyvalalign(arrayelemtypeid,
3289 arraytyplen = get_typlen(arraytypeid);
3292 * Evaluate the subscripts, switch into left-to-right
3295 havenullsubscript = false;
3296 for (i = 0; i < nsubscripts; i++)
3301 exec_eval_integer(estate,
3302 subscripts[nsubscripts - 1 - i],
3304 havenullsubscript |= subisnull;
3308 * Skip the assignment if we have any nulls in the subscripts
3309 * or the righthand side. This is pretty bogus but it
3310 * corresponds to the current behavior of ExecEvalArrayRef().
3312 if (havenullsubscript || *isNull)
3316 * If the original array is null, cons up an empty array
3317 * so that the assignment can proceed; we'll end with a
3318 * one-element array containing just the assigned-to
3319 * subscript. This only works for varlena arrays, though;
3320 * for fixed-length array types we skip the assignment.
3321 * Again, this corresponds to the current behavior of
3322 * ExecEvalArrayRef().
3326 if (arraytyplen > 0) /* fixed-length array? */
3329 oldarrayval = construct_md_array(NULL, 0, NULL, NULL,
3336 oldarrayval = (ArrayType *) DatumGetPointer(oldarraydatum);
3338 /* Coerce source value to match array element type. */
3339 coerced_value = exec_simple_cast_value(value,
3346 * Build the modified array value.
3348 newarrayval = array_set(oldarrayval,
3359 * Assign it to the base variable.
3361 exec_assign_value(estate, target,
3362 PointerGetDatum(newarrayval),
3363 arraytypeid, isNull);
3366 * Avoid leaking the result of exec_simple_cast_value, if
3367 * it performed a conversion to a pass-by-ref type.
3369 if (!*isNull && coerced_value != value && !elemtypbyval)
3370 pfree(DatumGetPointer(coerced_value));
3373 * Avoid leaking the modified array value, too.
3380 elog(ERROR, "unrecognized dtype: %d", target->dtype);
3385 * exec_eval_datum Get current value of a PLpgSQL_datum
3387 * The type oid, value in Datum format, and null flag are returned.
3389 * If expectedtypeid isn't InvalidOid, it is checked against the actual type.
3391 * At present this doesn't handle PLpgSQL_expr or PLpgSQL_arrayelem datums.
3393 * NOTE: caller must not modify the returned value, since it points right
3394 * at the stored value in the case of pass-by-reference datatypes. In some
3395 * cases we have to palloc a return value, and in such cases we put it into
3396 * the estate's short-term memory context.
3399 exec_eval_datum(PLpgSQL_execstate *estate,
3400 PLpgSQL_datum *datum,
3406 MemoryContext oldcontext;
3408 switch (datum->dtype)
3410 case PLPGSQL_DTYPE_VAR:
3412 PLpgSQL_var *var = (PLpgSQL_var *) datum;
3414 *typeid = var->datatype->typoid;
3415 *value = var->value;
3416 *isnull = var->isnull;
3417 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3419 (errcode(ERRCODE_DATATYPE_MISMATCH),
3420 errmsg("type of \"%s\" does not match that when preparing the plan",
3425 case PLPGSQL_DTYPE_ROW:
3427 PLpgSQL_row *row = (PLpgSQL_row *) datum;
3430 if (!row->rowtupdesc) /* should not happen */
3431 elog(ERROR, "row variable has no tupdesc");
3432 /* Make sure we have a valid type/typmod setting */
3433 BlessTupleDesc(row->rowtupdesc);
3434 oldcontext = MemoryContextSwitchTo(estate->eval_econtext->ecxt_per_tuple_memory);
3435 tup = make_tuple_from_row(estate, row, row->rowtupdesc);
3436 if (tup == NULL) /* should not happen */
3437 elog(ERROR, "row not compatible with its own tupdesc");
3438 MemoryContextSwitchTo(oldcontext);
3439 *typeid = row->rowtupdesc->tdtypeid;
3440 *value = HeapTupleGetDatum(tup);
3442 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3444 (errcode(ERRCODE_DATATYPE_MISMATCH),
3445 errmsg("type of \"%s\" does not match that when preparing the plan",
3450 case PLPGSQL_DTYPE_REC:
3452 PLpgSQL_rec *rec = (PLpgSQL_rec *) datum;
3453 HeapTupleData worktup;
3455 if (!HeapTupleIsValid(rec->tup))
3457 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3458 errmsg("record \"%s\" is not assigned yet",
3460 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
3461 Assert(rec->tupdesc != NULL);
3462 /* Make sure we have a valid type/typmod setting */
3463 BlessTupleDesc(rec->tupdesc);
3466 * In a trigger, the NEW and OLD parameters are likely to
3467 * be on-disk tuples that don't have the desired Datum
3468 * fields. Copy the tuple body and insert the right
3471 oldcontext = MemoryContextSwitchTo(estate->eval_econtext->ecxt_per_tuple_memory);
3472 heap_copytuple_with_tuple(rec->tup, &worktup);
3473 HeapTupleHeaderSetDatumLength(worktup.t_data, worktup.t_len);
3474 HeapTupleHeaderSetTypeId(worktup.t_data, rec->tupdesc->tdtypeid);
3475 HeapTupleHeaderSetTypMod(worktup.t_data, rec->tupdesc->tdtypmod);
3476 MemoryContextSwitchTo(oldcontext);
3477 *typeid = rec->tupdesc->tdtypeid;
3478 *value = HeapTupleGetDatum(&worktup);
3480 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3482 (errcode(ERRCODE_DATATYPE_MISMATCH),
3483 errmsg("type of \"%s\" does not match that when preparing the plan",
3488 case PLPGSQL_DTYPE_RECFIELD:
3490 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) datum;
3494 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
3495 if (!HeapTupleIsValid(rec->tup))
3497 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3498 errmsg("record \"%s\" is not assigned yet",
3500 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
3501 fno = SPI_fnumber(rec->tupdesc, recfield->fieldname);
3502 if (fno == SPI_ERROR_NOATTRIBUTE)
3504 (errcode(ERRCODE_UNDEFINED_COLUMN),
3505 errmsg("record \"%s\" has no field \"%s\"",
3506 rec->refname, recfield->fieldname)));
3507 *typeid = SPI_gettypeid(rec->tupdesc, fno);
3508 *value = SPI_getbinval(rec->tup, rec->tupdesc, fno, isnull);
3509 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3511 (errcode(ERRCODE_DATATYPE_MISMATCH),
3512 errmsg("type of \"%s.%s\" does not match that when preparing the plan",
3513 rec->refname, recfield->fieldname)));
3517 case PLPGSQL_DTYPE_TRIGARG:
3519 PLpgSQL_trigarg *trigarg = (PLpgSQL_trigarg *) datum;
3523 tgargno = exec_eval_integer(estate, trigarg->argnum, isnull);
3524 if (*isnull || tgargno < 0 || tgargno >= estate->trig_nargs)
3531 *value = estate->trig_argv[tgargno];
3534 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3536 (errcode(ERRCODE_DATATYPE_MISMATCH),
3537 errmsg("type of tgargv[%d] does not match that when preparing the plan",
3543 elog(ERROR, "unrecognized dtype: %d", datum->dtype);
3548 * exec_eval_integer Evaluate an expression, coerce result to int4
3550 * Note we do not do exec_eval_cleanup here; the caller must do it at
3551 * some later point. (We do this because the caller may be holding the
3552 * results of other, pass-by-reference, expression evaluations, such as
3553 * an array value to be subscripted. Also see notes in exec_eval_simple_expr
3554 * about allocation of the parameter array.)
3558 exec_eval_integer(PLpgSQL_execstate *estate,
3565 exprdatum = exec_eval_expr(estate, expr, isNull, &exprtypeid);
3566 exprdatum = exec_simple_cast_value(exprdatum, exprtypeid,
3569 return DatumGetInt32(exprdatum);
3573 * exec_eval_boolean Evaluate an expression, coerce result to bool
3575 * Note we do not do exec_eval_cleanup here; the caller must do it at
3580 exec_eval_boolean(PLpgSQL_execstate *estate,
3587 exprdatum = exec_eval_expr(estate, expr, isNull, &exprtypeid);
3588 exprdatum = exec_simple_cast_value(exprdatum, exprtypeid,
3591 return DatumGetBool(exprdatum);
3595 * exec_eval_expr Evaluate an expression and return
3598 * NOTE: caller must do exec_eval_cleanup when done with the Datum.
3602 exec_eval_expr(PLpgSQL_execstate *estate,
3610 * If not already done create a plan for this expression
3612 if (expr->plan == NULL)
3613 exec_prepare_plan(estate, expr);
3616 * If this is a simple expression, bypass SPI and use the executor
3619 if (expr->expr_simple_expr != NULL)
3620 return exec_eval_simple_expr(estate, expr, isNull, rettype);
3622 rc = exec_run_select(estate, expr, 2, NULL);
3623 if (rc != SPI_OK_SELECT)
3625 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3626 errmsg("query \"%s\" did not return data", expr->query)));
3629 * If there are no rows selected, the result is NULL.
3631 if (estate->eval_processed == 0)
3638 * Check that the expression returned one single Datum
3640 if (estate->eval_processed > 1)
3642 (errcode(ERRCODE_CARDINALITY_VIOLATION),
3643 errmsg("query \"%s\" returned more than one row",
3645 if (estate->eval_tuptable->tupdesc->natts != 1)
3647 (errcode(ERRCODE_SYNTAX_ERROR),
3648 errmsg("query \"%s\" returned %d columns", expr->query,
3649 estate->eval_tuptable->tupdesc->natts)));
3652 * Return the result and its type
3654 *rettype = SPI_gettypeid(estate->eval_tuptable->tupdesc, 1);
3655 return SPI_getbinval(estate->eval_tuptable->vals[0],
3656 estate->eval_tuptable->tupdesc, 1, isNull);
3661 * exec_run_select Execute a select query
3665 exec_run_select(PLpgSQL_execstate *estate,
3666 PLpgSQL_expr *expr, long maxtuples, Portal *portalP)
3674 * On the first call for this expression generate the plan
3676 if (expr->plan == NULL)
3677 exec_prepare_plan(estate, expr);
3680 * Now build up the values and nulls arguments for SPI_execute_plan()
3682 values = (Datum *) palloc(expr->nparams * sizeof(Datum));
3683 nulls = (char *) palloc(expr->nparams * sizeof(char));
3685 for (i = 0; i < expr->nparams; i++)
3687 PLpgSQL_datum *datum = estate->datums[expr->params[i]];
3691 exec_eval_datum(estate, datum, expr->plan_argtypes[i],
3692 ¶mtypeid, &values[i], ¶misnull);
3700 * If a portal was requested, put the query into the portal
3702 if (portalP != NULL)
3704 *portalP = SPI_cursor_open(NULL, expr->plan, values, nulls,
3705 estate->readonly_func);
3706 if (*portalP == NULL)
3707 elog(ERROR, "could not open implicit cursor for query \"%s\": %s",
3708 expr->query, SPI_result_code_string(SPI_result));
3711 return SPI_OK_CURSOR;
3717 rc = SPI_execute_plan(expr->plan, values, nulls,
3718 estate->readonly_func, maxtuples);
3719 if (rc != SPI_OK_SELECT)
3721 (errcode(ERRCODE_SYNTAX_ERROR),
3722 errmsg("query \"%s\" is not a SELECT", expr->query)));
3724 /* Save query results for eventual cleanup */
3725 Assert(estate->eval_tuptable == NULL);
3726 estate->eval_tuptable = SPI_tuptable;
3727 estate->eval_processed = SPI_processed;
3728 estate->eval_lastoid = SPI_lastoid;
3738 * exec_eval_simple_expr - Evaluate a simple expression returning
3739 * a Datum by directly calling ExecEvalExpr().
3741 * Note: if pass-by-reference, the result is in the eval_econtext's
3742 * temporary memory context. It will be freed when exec_eval_cleanup
3747 exec_eval_simple_expr(PLpgSQL_execstate *estate,
3753 ExprContext *econtext = estate->eval_econtext;
3754 ParamListInfo paramLI;
3756 Snapshot saveActiveSnapshot;
3759 * Pass back previously-determined result type.
3761 *rettype = expr->expr_simple_type;
3764 * Prepare the expression for execution, if it's not been done already
3765 * in the current transaction.
3767 if (expr->expr_simple_state == NULL)
3769 expr->expr_simple_state = ExecPrepareExpr(expr->expr_simple_expr,
3770 simple_eval_estate);
3771 /* Add it to list for cleanup */
3772 expr->expr_simple_next = active_simple_exprs;
3773 active_simple_exprs = expr;
3777 * Param list can live in econtext's temporary memory context.
3779 * XXX think about avoiding repeated palloc's for param lists? Beware
3780 * however that this routine is re-entrant: exec_eval_datum() can call
3781 * it back for subscript evaluation, and so there can be a need to
3782 * have more than one active param list.
3784 paramLI = (ParamListInfo)
3785 MemoryContextAlloc(econtext->ecxt_per_tuple_memory,
3786 (expr->nparams + 1) * sizeof(ParamListInfoData));
3789 * Put the parameter values into the parameter list entries.
3791 for (i = 0; i < expr->nparams; i++)
3793 PLpgSQL_datum *datum = estate->datums[expr->params[i]];
3795 paramLI[i].kind = PARAM_NUM;
3796 paramLI[i].id = i + 1;
3797 exec_eval_datum(estate, datum, expr->plan_argtypes[i],
3799 ¶mLI[i].value, ¶mLI[i].isnull);
3801 paramLI[i].kind = PARAM_INVALID;
3804 * Now we can safely make the econtext point to the param list.
3806 econtext->ecxt_param_list_info = paramLI;
3809 * We have to do some of the things SPI_execute_plan would do,
3810 * in particular advance the snapshot if we are in a non-read-only
3811 * function. Without this, stable functions within the expression
3812 * would fail to see updates made so far by our own function.
3815 saveActiveSnapshot = ActiveSnapshot;
3819 MemoryContext oldcontext;
3821 oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
3822 if (!estate->readonly_func)
3824 CommandCounterIncrement();
3825 ActiveSnapshot = CopySnapshot(GetTransactionSnapshot());
3829 * Finally we can call the executor to evaluate the expression
3831 retval = ExecEvalExpr(expr->expr_simple_state,
3835 MemoryContextSwitchTo(oldcontext);
3839 /* Restore global vars and propagate error */
3840 ActiveSnapshot = saveActiveSnapshot;
3845 ActiveSnapshot = saveActiveSnapshot;
3856 * exec_move_row Move one tuple's values into a record or row
3860 exec_move_row(PLpgSQL_execstate *estate,
3863 HeapTuple tup, TupleDesc tupdesc)
3866 * Record is simple - just copy the tuple and its descriptor into the
3872 * copy input first, just in case it is pointing at variable's value
3874 if (HeapTupleIsValid(tup))
3875 tup = heap_copytuple(tup);
3877 tupdesc = CreateTupleDescCopy(tupdesc);
3881 heap_freetuple(rec->tup);
3882 rec->freetup = false;
3884 if (rec->freetupdesc)
3886 FreeTupleDesc(rec->tupdesc);
3887 rec->freetupdesc = false;
3890 if (HeapTupleIsValid(tup))
3893 rec->freetup = true;
3897 /* If we have a tupdesc but no data, form an all-nulls tuple */
3900 nulls = (char *) palloc(tupdesc->natts * sizeof(char));
3901 memset(nulls, 'n', tupdesc->natts * sizeof(char));
3903 rec->tup = heap_formtuple(tupdesc, NULL, nulls);
3904 rec->freetup = true;
3913 rec->tupdesc = tupdesc;
3914 rec->freetupdesc = true;
3917 rec->tupdesc = NULL;
3923 * Row is a bit more complicated in that we assign the individual
3924 * attributes of the tuple to the variables the row points to.
3926 * NOTE: this code used to demand row->nfields == tup->t_data->t_natts,
3927 * but that's wrong. The tuple might have more fields than we
3928 * expected if it's from an inheritance-child table of the current
3929 * table, or it might have fewer if the table has had columns added by
3930 * ALTER TABLE. Ignore extra columns and assume NULL for missing
3931 * columns, the same as heap_getattr would do. We also have to skip
3932 * over dropped columns in either the source or destination.
3934 * If we have no tuple data at all, we'll assign NULL to all columns of
3943 if (HeapTupleIsValid(tup))
3944 t_natts = tup->t_data->t_natts;
3949 for (fnum = 0; fnum < row->nfields; fnum++)
3956 if (row->varnos[fnum] < 0)
3957 continue; /* skip dropped column in row struct */
3959 var = (PLpgSQL_var *) (estate->datums[row->varnos[fnum]]);
3961 while (anum < t_natts && tupdesc->attrs[anum]->attisdropped)
3962 anum++; /* skip dropped column in tuple */
3966 value = SPI_getbinval(tup, tupdesc, anum + 1, &isnull);
3967 valtype = SPI_gettypeid(tupdesc, anum + 1);
3974 valtype = InvalidOid;
3977 exec_assign_value(estate, (PLpgSQL_datum *) var,
3978 value, valtype, &isnull);
3984 elog(ERROR, "unsupported target");
3988 * make_tuple_from_row Make a tuple from the values of a row object
3990 * A NULL return indicates rowtype mismatch; caller must raise suitable error
3994 make_tuple_from_row(PLpgSQL_execstate *estate,
3998 int natts = tupdesc->natts;
4004 if (natts != row->nfields)
4007 dvalues = (Datum *) palloc0(natts * sizeof(Datum));
4008 nulls = (bool *) palloc(natts * sizeof(bool));
4010 for (i = 0; i < natts; i++)
4014 if (tupdesc->attrs[i]->attisdropped)
4016 nulls[i] = true; /* leave the column as null */
4019 if (row->varnos[i] < 0) /* should not happen */
4020 elog(ERROR, "dropped rowtype entry for non-dropped column");
4022 exec_eval_datum(estate, estate->datums[row->varnos[i]],
4023 InvalidOid, &fieldtypeid, &dvalues[i], &nulls[i]);
4024 if (fieldtypeid != tupdesc->attrs[i]->atttypid)
4028 tuple = heap_form_tuple(tupdesc, dvalues, nulls);
4037 * convert_value_to_string Convert a non-null Datum to C string
4039 * Note: callers generally assume that the result is a palloc'd string and
4040 * should be pfree'd. This is not all that safe an assumption ...
4044 convert_value_to_string(Datum value, Oid valtype)
4049 getTypeOutputInfo(valtype, &typoutput, &typIsVarlena);
4051 return DatumGetCString(OidFunctionCall1(typoutput, value));
4055 * exec_cast_value Cast a value if required
4059 exec_cast_value(Datum value, Oid valtype,
4069 * If the type of the queries return value isn't that of the
4070 * variable, convert it.
4072 if (valtype != reqtype || reqtypmod != -1)
4076 extval = convert_value_to_string(value, valtype);
4077 value = FunctionCall3(reqinput,
4078 CStringGetDatum(extval),
4079 ObjectIdGetDatum(reqtypioparam),
4080 Int32GetDatum(reqtypmod));
4089 * exec_simple_cast_value Cast a value if required
4091 * As above, but need not supply details about target type. Note that this
4092 * is slower than exec_cast_value with cached type info, and so should be
4093 * avoided in heavily used code paths.
4097 exec_simple_cast_value(Datum value, Oid valtype,
4098 Oid reqtype, int32 reqtypmod,
4103 if (valtype != reqtype || reqtypmod != -1)
4107 FmgrInfo finfo_input;
4109 getTypeInputInfo(reqtype, &typinput, &typioparam);
4111 fmgr_info(typinput, &finfo_input);
4113 value = exec_cast_value(value,
4128 * exec_simple_check_node - Recursively check if an expression
4129 * is made only of simple things we can
4130 * hand out directly to ExecEvalExpr()
4131 * instead of calling SPI.
4135 exec_simple_check_node(Node *node)
4140 switch (nodeTag(node))
4150 ArrayRef *expr = (ArrayRef *) node;
4152 if (!exec_simple_check_node((Node *) expr->refupperindexpr))
4154 if (!exec_simple_check_node((Node *) expr->reflowerindexpr))
4156 if (!exec_simple_check_node((Node *) expr->refexpr))
4158 if (!exec_simple_check_node((Node *) expr->refassgnexpr))
4166 FuncExpr *expr = (FuncExpr *) node;
4168 if (expr->funcretset)
4170 if (!exec_simple_check_node((Node *) expr->args))
4178 OpExpr *expr = (OpExpr *) node;
4182 if (!exec_simple_check_node((Node *) expr->args))
4188 case T_DistinctExpr:
4190 DistinctExpr *expr = (DistinctExpr *) node;
4194 if (!exec_simple_check_node((Node *) expr->args))
4200 case T_ScalarArrayOpExpr:
4202 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
4204 if (!exec_simple_check_node((Node *) expr->args))
4212 BoolExpr *expr = (BoolExpr *) node;
4214 if (!exec_simple_check_node((Node *) expr->args))
4221 return exec_simple_check_node((Node *) ((FieldSelect *) node)->arg);
4225 FieldStore *expr = (FieldStore *) node;
4227 if (!exec_simple_check_node((Node *) expr->arg))
4229 if (!exec_simple_check_node((Node *) expr->newvals))
4236 return exec_simple_check_node((Node *) ((RelabelType *) node)->arg);
4238 case T_ConvertRowtypeExpr:
4239 return exec_simple_check_node((Node *) ((ConvertRowtypeExpr *) node)->arg);
4243 CaseExpr *expr = (CaseExpr *) node;
4245 if (!exec_simple_check_node((Node *) expr->arg))
4247 if (!exec_simple_check_node((Node *) expr->args))
4249 if (!exec_simple_check_node((Node *) expr->defresult))
4257 CaseWhen *when = (CaseWhen *) node;
4259 if (!exec_simple_check_node((Node *) when->expr))
4261 if (!exec_simple_check_node((Node *) when->result))
4267 case T_CaseTestExpr:
4272 ArrayExpr *expr = (ArrayExpr *) node;
4274 if (!exec_simple_check_node((Node *) expr->elements))
4282 RowExpr *expr = (RowExpr *) node;
4284 if (!exec_simple_check_node((Node *) expr->args))
4290 case T_CoalesceExpr:
4292 CoalesceExpr *expr = (CoalesceExpr *) node;
4294 if (!exec_simple_check_node((Node *) expr->args))
4302 MinMaxExpr *expr = (MinMaxExpr *) node;
4304 if (!exec_simple_check_node((Node *) expr->args))
4312 NullIfExpr *expr = (NullIfExpr *) node;
4316 if (!exec_simple_check_node((Node *) expr->args))
4323 return exec_simple_check_node((Node *) ((NullTest *) node)->arg);
4326 return exec_simple_check_node((Node *) ((BooleanTest *) node)->arg);
4328 case T_CoerceToDomain:
4329 return exec_simple_check_node((Node *) ((CoerceToDomain *) node)->arg);
4331 case T_CoerceToDomainValue:
4336 List *expr = (List *) node;
4341 if (!exec_simple_check_node(lfirst(l)))
4355 * exec_simple_check_plan - Check if a plan is simple enough to
4356 * be evaluated by ExecEvalExpr() instead
4361 exec_simple_check_plan(PLpgSQL_expr *expr)
4363 _SPI_plan *spi_plan = (_SPI_plan *) expr->plan;
4367 expr->expr_simple_expr = NULL;
4370 * 1. We can only evaluate queries that resulted in one single
4373 if (list_length(spi_plan->ptlist) != 1)
4376 plan = (Plan *) linitial(spi_plan->ptlist);
4379 * 2. It must be a RESULT plan --> no scan's required
4381 if (plan == NULL) /* utility statement produces this */
4384 if (!IsA(plan, Result))
4388 * 3. Can't have any subplan or qual clause, either
4390 if (plan->lefttree != NULL ||
4391 plan->righttree != NULL ||
4392 plan->initPlan != NULL ||
4393 plan->qual != NULL ||
4394 ((Result *) plan)->resconstantqual != NULL)
4398 * 4. The plan must have a single attribute as result
4400 if (list_length(plan->targetlist) != 1)
4403 tle = (TargetEntry *) linitial(plan->targetlist);
4406 * 5. Check that all the nodes in the expression are non-scary.
4408 if (!exec_simple_check_node((Node *) tle->expr))
4412 * Yes - this is a simple expression. Mark it as such, and initialize
4413 * state to "not executing".
4415 expr->expr_simple_expr = tle->expr;
4416 expr->expr_simple_state = NULL;
4417 expr->expr_simple_next = NULL;
4418 /* Also stash away the expression result type */
4419 expr->expr_simple_type = exprType((Node *) tle->expr);
4423 * Check two tupledescs have matching number and types of attributes
4426 compatible_tupdesc(TupleDesc td1, TupleDesc td2)
4430 if (td1->natts != td2->natts)
4433 for (i = 0; i < td1->natts; i++)
4435 if (td1->attrs[i]->atttypid != td2->attrs[i]->atttypid)
4443 * exec_set_found Set the global found variable
4448 exec_set_found(PLpgSQL_execstate *estate, bool state)
4452 var = (PLpgSQL_var *) (estate->datums[estate->found_varno]);
4453 var->value = (Datum) state;
4454 var->isnull = false;
4458 * plpgsql_xact_cb --- post-transaction-commit-or-abort cleanup
4460 * If a simple_eval_estate was created in the current transaction,
4461 * it has to be cleaned up, and we have to mark all active PLpgSQL_expr
4462 * structs that are using it as no longer active.
4464 * XXX Do we need to do anything at subtransaction events?
4465 * Maybe subtransactions need to have their own simple_eval_estate?
4466 * It would get a lot messier, so for now let's assume we don't need that.
4469 plpgsql_xact_cb(XactEvent event, void *arg)
4472 PLpgSQL_expr *enext;
4474 /* Mark all active exprs as inactive */
4475 for (expr = active_simple_exprs; expr; expr = enext)
4477 enext = expr->expr_simple_next;
4478 expr->expr_simple_state = NULL;
4479 expr->expr_simple_next = NULL;
4481 active_simple_exprs = NULL;
4484 * If we are doing a clean transaction shutdown, free the
4485 * EState (so that any remaining resources will be released
4486 * correctly). In an abort, we expect the regular abort
4487 * recovery procedures to release everything of interest.
4489 if (event == XACT_EVENT_COMMIT && simple_eval_estate)
4490 FreeExecutorState(simple_eval_estate);
4491 simple_eval_estate = NULL;
4495 free_var(PLpgSQL_var *var)
4499 pfree(DatumGetPointer(var->value));
4500 var->freeval = false;