1 /**********************************************************************
2 * pl_exec.c - Executor for the PL/pgSQL
6 * $PostgreSQL: pgsql/src/pl/plpgsql/src/pl_exec.c,v 1.145 2005/06/20 20:44:44 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;
199 * Setup the execution state
201 plpgsql_estate_setup(&estate, func, (ReturnSetInfo *) fcinfo->resultinfo);
204 * Setup error traceback support for ereport()
206 plerrcontext.callback = plpgsql_exec_error_callback;
207 plerrcontext.arg = &estate;
208 plerrcontext.previous = error_context_stack;
209 error_context_stack = &plerrcontext;
212 * Make local execution copies of all the datums
214 estate.err_text = gettext_noop("during initialization of execution state");
215 for (i = 0; i < estate.ndatums; i++)
216 estate.datums[i] = copy_plpgsql_datum(func->datums[i]);
219 * Store the actual call argument values into the appropriate variables
221 estate.err_text = gettext_noop("while storing call arguments into local variables");
222 for (i = 0; i < func->fn_nargs; i++)
224 int n = func->fn_argvarnos[i];
226 switch (estate.datums[n]->dtype)
228 case PLPGSQL_DTYPE_VAR:
230 PLpgSQL_var *var = (PLpgSQL_var *) estate.datums[n];
232 var->value = fcinfo->arg[i];
233 var->isnull = fcinfo->argnull[i];
234 var->freeval = false;
238 case PLPGSQL_DTYPE_ROW:
240 PLpgSQL_row *row = (PLpgSQL_row *) estate.datums[n];
242 if (!fcinfo->argnull[i])
248 HeapTupleData tmptup;
250 td = DatumGetHeapTupleHeader(fcinfo->arg[i]);
251 /* Extract rowtype info and find a tupdesc */
252 tupType = HeapTupleHeaderGetTypeId(td);
253 tupTypmod = HeapTupleHeaderGetTypMod(td);
254 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
255 /* Build a temporary HeapTuple control structure */
256 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
257 ItemPointerSetInvalid(&(tmptup.t_self));
258 tmptup.t_tableOid = InvalidOid;
260 exec_move_row(&estate, NULL, row, &tmptup, tupdesc);
264 /* If arg is null, treat it as an empty row */
265 exec_move_row(&estate, NULL, row, NULL, NULL);
271 elog(ERROR, "unrecognized dtype: %d", func->datums[i]->dtype);
276 * Set the magic variable FOUND to false
278 exec_set_found(&estate, false);
281 * Now call the toplevel block of statements
283 estate.err_text = NULL;
284 estate.err_stmt = (PLpgSQL_stmt *) (func->action);
285 if (exec_stmt_block(&estate, func->action) != PLPGSQL_RC_RETURN)
287 estate.err_stmt = NULL;
288 estate.err_text = NULL;
290 (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
291 errmsg("control reached end of function without RETURN")));
295 * We got a return value - process it
297 estate.err_stmt = NULL;
298 estate.err_text = gettext_noop("while casting return value to function's return type");
300 fcinfo->isnull = estate.retisnull;
304 ReturnSetInfo *rsi = estate.rsi;
306 /* Check caller can handle a set result */
307 if (!rsi || !IsA(rsi, ReturnSetInfo) ||
308 (rsi->allowedModes & SFRM_Materialize) == 0)
310 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
311 errmsg("set-valued function called in context that cannot accept a set")));
312 rsi->returnMode = SFRM_Materialize;
314 /* If we produced any tuples, send back the result */
315 if (estate.tuple_store)
317 rsi->setResult = estate.tuple_store;
318 if (estate.rettupdesc)
320 MemoryContext oldcxt;
322 oldcxt = MemoryContextSwitchTo(estate.tuple_store_cxt);
323 rsi->setDesc = CreateTupleDescCopy(estate.rettupdesc);
324 MemoryContextSwitchTo(oldcxt);
327 estate.retval = (Datum) 0;
328 fcinfo->isnull = true;
330 else if (!estate.retisnull)
332 if (estate.retistuple)
334 /* Copy tuple to upper executor memory, as a tuple Datum */
336 PointerGetDatum(SPI_returntuple((HeapTuple) (estate.retval),
341 /* Cast value to proper type */
342 estate.retval = exec_cast_value(estate.retval, estate.rettype,
344 &(func->fn_retinput),
345 func->fn_rettypioparam,
350 * If the function's return type isn't by value, copy the value
351 * into upper executor memory context.
353 if (!fcinfo->isnull && !func->fn_retbyval)
358 len = datumGetSize(estate.retval, false, func->fn_rettyplen);
359 tmp = (void *) SPI_palloc(len);
360 memcpy(tmp, DatumGetPointer(estate.retval), len);
361 estate.retval = PointerGetDatum(tmp);
366 /* Clean up any leftover temporary memory */
367 if (estate.eval_econtext != NULL)
368 FreeExprContext(estate.eval_econtext);
369 estate.eval_econtext = NULL;
370 exec_eval_cleanup(&estate);
373 * Pop the error context stack
375 error_context_stack = plerrcontext.previous;
378 * Return the function's result
380 return estate.retval;
385 * plpgsql_exec_trigger Called by the call handler for
390 plpgsql_exec_trigger(PLpgSQL_function *func,
391 TriggerData *trigdata)
393 PLpgSQL_execstate estate;
394 ErrorContextCallback plerrcontext;
397 PLpgSQL_rec *rec_new,
402 * Setup the execution state
404 plpgsql_estate_setup(&estate, func, NULL);
407 * Setup error traceback support for ereport()
409 plerrcontext.callback = plpgsql_exec_error_callback;
410 plerrcontext.arg = &estate;
411 plerrcontext.previous = error_context_stack;
412 error_context_stack = &plerrcontext;
415 * Make local execution copies of all the datums
417 estate.err_text = gettext_noop("during initialization of execution state");
418 for (i = 0; i < estate.ndatums; i++)
419 estate.datums[i] = copy_plpgsql_datum(func->datums[i]);
422 * Put the OLD and NEW tuples into record variables
424 rec_new = (PLpgSQL_rec *) (estate.datums[func->new_varno]);
425 rec_new->freetup = false;
426 rec_new->freetupdesc = false;
427 rec_old = (PLpgSQL_rec *) (estate.datums[func->old_varno]);
428 rec_old->freetup = false;
429 rec_old->freetupdesc = false;
431 if (TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
434 * Per-statement triggers don't use OLD/NEW variables
437 rec_new->tupdesc = NULL;
439 rec_old->tupdesc = NULL;
441 else if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
443 rec_new->tup = trigdata->tg_trigtuple;
444 rec_new->tupdesc = trigdata->tg_relation->rd_att;
446 rec_old->tupdesc = NULL;
448 else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
450 rec_new->tup = trigdata->tg_newtuple;
451 rec_new->tupdesc = trigdata->tg_relation->rd_att;
452 rec_old->tup = trigdata->tg_trigtuple;
453 rec_old->tupdesc = trigdata->tg_relation->rd_att;
455 else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
458 rec_new->tupdesc = NULL;
459 rec_old->tup = trigdata->tg_trigtuple;
460 rec_old->tupdesc = trigdata->tg_relation->rd_att;
463 elog(ERROR, "unrecognized trigger action: not INSERT, DELETE, or UPDATE");
466 * Assign the special tg_ variables
469 var = (PLpgSQL_var *) (estate.datums[func->tg_op_varno]);
470 if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
471 var->value = DirectFunctionCall1(textin, CStringGetDatum("INSERT"));
472 else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
473 var->value = DirectFunctionCall1(textin, CStringGetDatum("UPDATE"));
474 else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
475 var->value = DirectFunctionCall1(textin, CStringGetDatum("DELETE"));
477 elog(ERROR, "unrecognized trigger action: not INSERT, DELETE, or UPDATE");
481 var = (PLpgSQL_var *) (estate.datums[func->tg_name_varno]);
482 var->value = DirectFunctionCall1(namein,
483 CStringGetDatum(trigdata->tg_trigger->tgname));
487 var = (PLpgSQL_var *) (estate.datums[func->tg_when_varno]);
488 if (TRIGGER_FIRED_BEFORE(trigdata->tg_event))
489 var->value = DirectFunctionCall1(textin, CStringGetDatum("BEFORE"));
490 else if (TRIGGER_FIRED_AFTER(trigdata->tg_event))
491 var->value = DirectFunctionCall1(textin, CStringGetDatum("AFTER"));
493 elog(ERROR, "unrecognized trigger execution time: not BEFORE or AFTER");
497 var = (PLpgSQL_var *) (estate.datums[func->tg_level_varno]);
498 if (TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
499 var->value = DirectFunctionCall1(textin, CStringGetDatum("ROW"));
500 else if (TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
501 var->value = DirectFunctionCall1(textin, CStringGetDatum("STATEMENT"));
503 elog(ERROR, "unrecognized trigger event type: not ROW or STATEMENT");
507 var = (PLpgSQL_var *) (estate.datums[func->tg_relid_varno]);
508 var->value = ObjectIdGetDatum(trigdata->tg_relation->rd_id);
510 var->freeval = false;
512 var = (PLpgSQL_var *) (estate.datums[func->tg_relname_varno]);
513 var->value = DirectFunctionCall1(namein,
514 CStringGetDatum(RelationGetRelationName(trigdata->tg_relation)));
518 var = (PLpgSQL_var *) (estate.datums[func->tg_nargs_varno]);
519 var->value = Int16GetDatum(trigdata->tg_trigger->tgnargs);
521 var->freeval = false;
524 * Store the trigger argument values into the special execution
527 estate.err_text = gettext_noop("while storing call arguments into local variables");
528 estate.trig_nargs = trigdata->tg_trigger->tgnargs;
529 if (estate.trig_nargs == 0)
530 estate.trig_argv = NULL;
533 estate.trig_argv = palloc(sizeof(Datum) * estate.trig_nargs);
534 for (i = 0; i < trigdata->tg_trigger->tgnargs; i++)
535 estate.trig_argv[i] = DirectFunctionCall1(textin,
536 CStringGetDatum(trigdata->tg_trigger->tgargs[i]));
540 * Set the magic variable FOUND to false
542 exec_set_found(&estate, false);
545 * Now call the toplevel block of statements
547 estate.err_text = NULL;
548 estate.err_stmt = (PLpgSQL_stmt *) (func->action);
549 if (exec_stmt_block(&estate, func->action) != PLPGSQL_RC_RETURN)
551 estate.err_stmt = NULL;
552 estate.err_text = NULL;
554 (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
555 errmsg("control reached end of trigger procedure without RETURN")));
560 (errcode(ERRCODE_DATATYPE_MISMATCH),
561 errmsg("trigger procedure cannot return a set")));
564 * Check that the returned tuple structure has the same attributes,
565 * the relation that fired the trigger has. A per-statement trigger
566 * always needs to return NULL, so we ignore any return value the
567 * function itself produces (XXX: is this a good idea?)
569 * XXX This way it is possible, that the trigger returns a tuple where
570 * attributes don't have the correct atttypmod's length. It's up to
571 * the trigger's programmer to ensure that this doesn't happen. Jan
573 if (estate.retisnull || TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
577 if (!compatible_tupdesc(estate.rettupdesc,
578 trigdata->tg_relation->rd_att))
580 (errcode(ERRCODE_DATATYPE_MISMATCH),
581 errmsg("returned tuple structure does not match table of trigger event")));
582 /* Copy tuple to upper executor memory */
583 rettup = SPI_copytuple((HeapTuple) (estate.retval));
586 /* Clean up any leftover temporary memory */
587 if (estate.eval_econtext != NULL)
588 FreeExprContext(estate.eval_econtext);
589 estate.eval_econtext = NULL;
590 exec_eval_cleanup(&estate);
593 * Pop the error context stack
595 error_context_stack = plerrcontext.previous;
598 * Return the trigger's result
605 * error context callback to let us supply a call-stack traceback
608 plpgsql_exec_error_callback(void *arg)
610 PLpgSQL_execstate *estate = (PLpgSQL_execstate *) arg;
612 /* safety check, shouldn't happen */
613 if (estate->err_func == NULL)
616 /* if we are doing RAISE, don't report its location */
617 if (estate->err_text == raise_skip_msg)
620 if (estate->err_stmt != NULL)
622 /* translator: last %s is a plpgsql statement type name */
623 errcontext("PL/pgSQL function \"%s\" line %d at %s",
624 estate->err_func->fn_name,
625 estate->err_stmt->lineno,
626 plpgsql_stmt_typename(estate->err_stmt));
628 else if (estate->err_text != NULL)
631 * We don't expend the cycles to run gettext() on err_text unless
632 * we actually need it. Therefore, places that set up err_text
633 * should use gettext_noop() to ensure the strings get recorded in
634 * the message dictionary.
638 * translator: last %s is a phrase such as "while storing call
639 * arguments into local variables"
641 errcontext("PL/pgSQL function \"%s\" %s",
642 estate->err_func->fn_name,
643 gettext(estate->err_text));
646 errcontext("PL/pgSQL function \"%s\"",
647 estate->err_func->fn_name);
652 * Support function for initializing local execution variables
655 static PLpgSQL_datum *
656 copy_plpgsql_datum(PLpgSQL_datum *datum)
658 PLpgSQL_datum *result;
660 switch (datum->dtype)
662 case PLPGSQL_DTYPE_VAR:
664 PLpgSQL_var *new = palloc(sizeof(PLpgSQL_var));
666 memcpy(new, datum, sizeof(PLpgSQL_var));
667 /* Ensure the value is null (possibly not needed?) */
670 new->freeval = false;
672 result = (PLpgSQL_datum *) new;
676 case PLPGSQL_DTYPE_REC:
678 PLpgSQL_rec *new = palloc(sizeof(PLpgSQL_rec));
680 memcpy(new, datum, sizeof(PLpgSQL_rec));
681 /* Ensure the value is null (possibly not needed?) */
684 new->freetup = false;
685 new->freetupdesc = false;
687 result = (PLpgSQL_datum *) new;
691 case PLPGSQL_DTYPE_ROW:
692 case PLPGSQL_DTYPE_RECFIELD:
693 case PLPGSQL_DTYPE_ARRAYELEM:
694 case PLPGSQL_DTYPE_TRIGARG:
696 * These datum records are read-only at runtime, so no need
703 elog(ERROR, "unrecognized dtype: %d", datum->dtype);
704 result = NULL; /* keep compiler quiet */
713 exception_matches_conditions(ErrorData *edata, PLpgSQL_condition *cond)
715 for (; cond != NULL; cond = cond->next)
717 int sqlerrstate = cond->sqlerrstate;
720 * OTHERS matches everything *except* query-canceled; if you're
721 * foolish enough, you can match that explicitly.
723 if (sqlerrstate == 0)
725 if (edata->sqlerrcode != ERRCODE_QUERY_CANCELED)
729 else if (edata->sqlerrcode == sqlerrstate)
731 /* Category match? */
732 else if (ERRCODE_IS_CATEGORY(sqlerrstate) &&
733 ERRCODE_TO_CATEGORY(edata->sqlerrcode) == sqlerrstate)
741 * exec_stmt_block Execute a block of statements
745 exec_stmt_block(PLpgSQL_execstate *estate, PLpgSQL_stmt_block *block)
747 volatile int rc = -1;
752 * First initialize all variables declared in this block
754 for (i = 0; i < block->n_initvars; i++)
756 n = block->initvarnos[i];
758 switch (estate->datums[n]->dtype)
760 case PLPGSQL_DTYPE_VAR:
762 PLpgSQL_var *var = (PLpgSQL_var *) (estate->datums[n]);
765 if (!var->isconst || var->isnull)
767 if (var->default_val == NULL)
769 var->value = (Datum) 0;
773 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
774 errmsg("variable \"%s\" declared NOT NULL cannot default to NULL",
779 exec_assign_expr(estate, (PLpgSQL_datum *) var,
786 case PLPGSQL_DTYPE_REC:
788 PLpgSQL_rec *rec = (PLpgSQL_rec *) (estate->datums[n]);
792 heap_freetuple(rec->tup);
793 FreeTupleDesc(rec->tupdesc);
794 rec->freetup = false;
802 case PLPGSQL_DTYPE_RECFIELD:
803 case PLPGSQL_DTYPE_ARRAYELEM:
807 elog(ERROR, "unrecognized dtype: %d",
808 estate->datums[n]->dtype);
812 if (block->exceptions)
815 * Execute the statements in the block's body inside a
818 MemoryContext oldcontext = CurrentMemoryContext;
819 ResourceOwner oldowner = CurrentResourceOwner;
821 BeginInternalSubTransaction(NULL);
822 /* Want to run statements inside function's memory context */
823 MemoryContextSwitchTo(oldcontext);
827 rc = exec_stmts(estate, block->body);
829 /* Commit the inner transaction, return to outer xact context */
830 ReleaseCurrentSubTransaction();
831 MemoryContextSwitchTo(oldcontext);
832 CurrentResourceOwner = oldowner;
835 * AtEOSubXact_SPI() should not have popped any SPI context,
836 * but just in case it did, make sure we remain connected.
838 SPI_restore_connection();
845 /* Save error info */
846 MemoryContextSwitchTo(oldcontext);
847 edata = CopyErrorData();
850 /* Abort the inner transaction */
851 RollbackAndReleaseCurrentSubTransaction();
852 MemoryContextSwitchTo(oldcontext);
853 CurrentResourceOwner = oldowner;
856 * If AtEOSubXact_SPI() popped any SPI context of the subxact,
857 * it will have left us in a disconnected state. We need this
858 * hack to return to connected state.
860 SPI_restore_connection();
862 /* Look for a matching exception handler */
863 foreach (e, block->exceptions->exc_list)
865 PLpgSQL_exception *exception = (PLpgSQL_exception *) lfirst(e);
867 if (exception_matches_conditions(edata, exception->conditions))
870 * Initialize the magic SQLSTATE and SQLERRM
871 * variables for the exception block. We needn't
872 * do this until we have found a matching
875 PLpgSQL_var *state_var;
876 PLpgSQL_var *errm_var;
878 state_var = (PLpgSQL_var *)
879 estate->datums[block->exceptions->sqlstate_varno];
880 state_var->value = DirectFunctionCall1(textin,
881 CStringGetDatum(unpack_sql_state(edata->sqlerrcode)));
882 state_var->freeval = true;
883 state_var->isnull = false;
885 errm_var = (PLpgSQL_var *)
886 estate->datums[block->exceptions->sqlerrm_varno];
887 errm_var->value = DirectFunctionCall1(textin,
888 CStringGetDatum(edata->message));
889 errm_var->freeval = true;
890 errm_var->isnull = false;
892 rc = exec_stmts(estate, exception->action);
900 /* If no match found, re-throw the error */
904 FreeErrorData(edata);
911 * Just execute the statements in the block's body
913 rc = exec_stmts(estate, block->body);
917 * Handle the return code.
922 return PLPGSQL_RC_OK;
924 case PLPGSQL_RC_EXIT:
925 if (estate->exitlabel == NULL)
926 return PLPGSQL_RC_OK;
927 if (block->label == NULL)
928 return PLPGSQL_RC_EXIT;
929 if (strcmp(block->label, estate->exitlabel))
930 return PLPGSQL_RC_EXIT;
931 estate->exitlabel = NULL;
932 return PLPGSQL_RC_OK;
934 case PLPGSQL_RC_RETURN:
935 return PLPGSQL_RC_RETURN;
938 elog(ERROR, "unrecognized rc: %d", rc);
941 return PLPGSQL_RC_OK;
946 * exec_stmts Iterate over a list of statements
947 * as long as their return code is OK
951 exec_stmts(PLpgSQL_execstate *estate, List *stmts)
957 PLpgSQL_stmt *stmt = (PLpgSQL_stmt *) lfirst(s);
958 int rc = exec_stmt(estate, stmt);
959 if (rc != PLPGSQL_RC_OK)
963 return PLPGSQL_RC_OK;
968 * exec_stmt Distribute one statement to the statements
969 * type specific execution function.
973 exec_stmt(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
975 PLpgSQL_stmt *save_estmt;
978 save_estmt = estate->err_stmt;
979 estate->err_stmt = stmt;
981 CHECK_FOR_INTERRUPTS();
983 switch (stmt->cmd_type)
985 case PLPGSQL_STMT_BLOCK:
986 rc = exec_stmt_block(estate, (PLpgSQL_stmt_block *) stmt);
989 case PLPGSQL_STMT_ASSIGN:
990 rc = exec_stmt_assign(estate, (PLpgSQL_stmt_assign *) stmt);
993 case PLPGSQL_STMT_PERFORM:
994 rc = exec_stmt_perform(estate, (PLpgSQL_stmt_perform *) stmt);
997 case PLPGSQL_STMT_GETDIAG:
998 rc = exec_stmt_getdiag(estate, (PLpgSQL_stmt_getdiag *) stmt);
1001 case PLPGSQL_STMT_IF:
1002 rc = exec_stmt_if(estate, (PLpgSQL_stmt_if *) stmt);
1005 case PLPGSQL_STMT_LOOP:
1006 rc = exec_stmt_loop(estate, (PLpgSQL_stmt_loop *) stmt);
1009 case PLPGSQL_STMT_WHILE:
1010 rc = exec_stmt_while(estate, (PLpgSQL_stmt_while *) stmt);
1013 case PLPGSQL_STMT_FORI:
1014 rc = exec_stmt_fori(estate, (PLpgSQL_stmt_fori *) stmt);
1017 case PLPGSQL_STMT_FORS:
1018 rc = exec_stmt_fors(estate, (PLpgSQL_stmt_fors *) stmt);
1021 case PLPGSQL_STMT_SELECT:
1022 rc = exec_stmt_select(estate, (PLpgSQL_stmt_select *) stmt);
1025 case PLPGSQL_STMT_EXIT:
1026 rc = exec_stmt_exit(estate, (PLpgSQL_stmt_exit *) stmt);
1029 case PLPGSQL_STMT_RETURN:
1030 rc = exec_stmt_return(estate, (PLpgSQL_stmt_return *) stmt);
1033 case PLPGSQL_STMT_RETURN_NEXT:
1034 rc = exec_stmt_return_next(estate, (PLpgSQL_stmt_return_next *) stmt);
1037 case PLPGSQL_STMT_RAISE:
1038 rc = exec_stmt_raise(estate, (PLpgSQL_stmt_raise *) stmt);
1041 case PLPGSQL_STMT_EXECSQL:
1042 rc = exec_stmt_execsql(estate, (PLpgSQL_stmt_execsql *) stmt);
1045 case PLPGSQL_STMT_DYNEXECUTE:
1046 rc = exec_stmt_dynexecute(estate, (PLpgSQL_stmt_dynexecute *) stmt);
1049 case PLPGSQL_STMT_DYNFORS:
1050 rc = exec_stmt_dynfors(estate, (PLpgSQL_stmt_dynfors *) stmt);
1053 case PLPGSQL_STMT_OPEN:
1054 rc = exec_stmt_open(estate, (PLpgSQL_stmt_open *) stmt);
1057 case PLPGSQL_STMT_FETCH:
1058 rc = exec_stmt_fetch(estate, (PLpgSQL_stmt_fetch *) stmt);
1061 case PLPGSQL_STMT_CLOSE:
1062 rc = exec_stmt_close(estate, (PLpgSQL_stmt_close *) stmt);
1066 estate->err_stmt = save_estmt;
1067 elog(ERROR, "unrecognized cmdtype: %d", stmt->cmd_type);
1070 estate->err_stmt = save_estmt;
1077 * exec_stmt_assign Evaluate an expression and
1078 * put the result into a variable.
1082 exec_stmt_assign(PLpgSQL_execstate *estate, PLpgSQL_stmt_assign *stmt)
1084 Assert(stmt->varno >= 0);
1086 exec_assign_expr(estate, estate->datums[stmt->varno], stmt->expr);
1088 return PLPGSQL_RC_OK;
1092 * exec_stmt_perform Evaluate query and discard result (but set
1093 * FOUND depending on whether at least one row
1098 exec_stmt_perform(PLpgSQL_execstate *estate, PLpgSQL_stmt_perform *stmt)
1100 PLpgSQL_expr *expr = stmt->expr;
1102 (void) exec_run_select(estate, expr, 0, NULL);
1103 exec_set_found(estate, (estate->eval_processed != 0));
1104 exec_eval_cleanup(estate);
1106 return PLPGSQL_RC_OK;
1110 * exec_stmt_getdiag Put internal PG information into
1111 * specified variables.
1115 exec_stmt_getdiag(PLpgSQL_execstate *estate, PLpgSQL_stmt_getdiag *stmt)
1119 foreach (lc, stmt->diag_items)
1121 PLpgSQL_diag_item *diag_item = (PLpgSQL_diag_item *) lfirst(lc);
1123 bool isnull = false;
1125 if (diag_item->target <= 0)
1128 var = estate->datums[diag_item->target];
1133 switch (diag_item->kind)
1135 case PLPGSQL_GETDIAG_ROW_COUNT:
1137 exec_assign_value(estate, var,
1138 UInt32GetDatum(estate->eval_processed),
1142 case PLPGSQL_GETDIAG_RESULT_OID:
1144 exec_assign_value(estate, var,
1145 ObjectIdGetDatum(estate->eval_lastoid),
1150 elog(ERROR, "unrecognized attribute request: %d",
1155 return PLPGSQL_RC_OK;
1159 * exec_stmt_if Evaluate a bool expression and
1160 * execute the true or false body
1165 exec_stmt_if(PLpgSQL_execstate *estate, PLpgSQL_stmt_if *stmt)
1168 bool isnull = false;
1170 value = exec_eval_boolean(estate, stmt->cond, &isnull);
1171 exec_eval_cleanup(estate);
1173 if (!isnull && value)
1175 if (stmt->true_body != NIL)
1176 return exec_stmts(estate, stmt->true_body);
1180 if (stmt->false_body != NIL)
1181 return exec_stmts(estate, stmt->false_body);
1184 return PLPGSQL_RC_OK;
1189 * exec_stmt_loop Loop over statements until
1194 exec_stmt_loop(PLpgSQL_execstate *estate, PLpgSQL_stmt_loop *stmt)
1200 rc = exec_stmts(estate, stmt->body);
1207 case PLPGSQL_RC_EXIT:
1208 if (estate->exitlabel == NULL)
1209 return PLPGSQL_RC_OK;
1210 if (stmt->label == NULL)
1211 return PLPGSQL_RC_EXIT;
1212 if (strcmp(stmt->label, estate->exitlabel))
1213 return PLPGSQL_RC_EXIT;
1214 estate->exitlabel = NULL;
1215 return PLPGSQL_RC_OK;
1217 case PLPGSQL_RC_RETURN:
1218 return PLPGSQL_RC_RETURN;
1221 elog(ERROR, "unrecognized rc: %d", rc);
1225 return PLPGSQL_RC_OK;
1230 * exec_stmt_while Loop over statements as long
1231 * as an expression evaluates to
1232 * true or an exit occurs.
1236 exec_stmt_while(PLpgSQL_execstate *estate, PLpgSQL_stmt_while *stmt)
1239 bool isnull = false;
1244 value = exec_eval_boolean(estate, stmt->cond, &isnull);
1245 exec_eval_cleanup(estate);
1247 if (isnull || !value)
1250 rc = exec_stmts(estate, stmt->body);
1257 case PLPGSQL_RC_EXIT:
1258 if (estate->exitlabel == NULL)
1259 return PLPGSQL_RC_OK;
1260 if (stmt->label == NULL)
1261 return PLPGSQL_RC_EXIT;
1262 if (strcmp(stmt->label, estate->exitlabel))
1263 return PLPGSQL_RC_EXIT;
1264 estate->exitlabel = NULL;
1265 return PLPGSQL_RC_OK;
1267 case PLPGSQL_RC_RETURN:
1268 return PLPGSQL_RC_RETURN;
1271 elog(ERROR, "unrecognized rc: %d", rc);
1275 return PLPGSQL_RC_OK;
1280 * exec_stmt_fori Iterate an integer variable
1281 * from a lower to an upper value.
1282 * Loop can be left with exit.
1286 exec_stmt_fori(PLpgSQL_execstate *estate, PLpgSQL_stmt_fori *stmt)
1291 bool isnull = false;
1293 int rc = PLPGSQL_RC_OK;
1295 var = (PLpgSQL_var *) (estate->datums[stmt->var->varno]);
1298 * Get the value of the lower bound into the loop var
1300 value = exec_eval_expr(estate, stmt->lower, &isnull, &valtype);
1301 value = exec_cast_value(value, valtype, var->datatype->typoid,
1302 &(var->datatype->typinput),
1303 var->datatype->typioparam,
1304 var->datatype->atttypmod, &isnull);
1307 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1308 errmsg("lower bound of FOR loop cannot be NULL")));
1310 var->isnull = false;
1311 exec_eval_cleanup(estate);
1314 * Get the value of the upper bound
1316 value = exec_eval_expr(estate, stmt->upper, &isnull, &valtype);
1317 value = exec_cast_value(value, valtype, var->datatype->typoid,
1318 &(var->datatype->typinput),
1319 var->datatype->typioparam,
1320 var->datatype->atttypmod, &isnull);
1323 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1324 errmsg("upper bound of FOR loop cannot be NULL")));
1325 exec_eval_cleanup(estate);
1337 if ((int4) (var->value) < (int4) value)
1342 if ((int4) (var->value) > (int4) value)
1346 found = true; /* looped at least once */
1349 * Execute the statements
1351 rc = exec_stmts(estate, stmt->body);
1353 if (rc == PLPGSQL_RC_RETURN)
1354 break; /* return from function */
1355 else if (rc == PLPGSQL_RC_EXIT)
1357 if (estate->exitlabel == NULL)
1358 /* unlabelled exit, finish the current loop */
1360 else if (stmt->label != NULL &&
1361 strcmp(stmt->label, estate->exitlabel) == 0)
1363 /* labelled exit, matches the current stmt's label */
1364 estate->exitlabel = NULL;
1369 * otherwise, we processed a labelled exit that does not match
1370 * the current statement's label, if any: return RC_EXIT so
1371 * that the EXIT continues to recurse upward.
1378 * Increase/decrease loop var
1387 * Set the FOUND variable to indicate the result of executing the loop
1388 * (namely, whether we looped one or more times). This must be set
1389 * here so that it does not interfere with the value of the FOUND
1390 * variable inside the loop processing itself.
1392 exec_set_found(estate, found);
1399 * exec_stmt_fors Execute a query, assign each
1400 * tuple to a record or row and
1401 * execute a group of statements
1406 exec_stmt_fors(PLpgSQL_execstate *estate, PLpgSQL_stmt_fors *stmt)
1408 PLpgSQL_rec *rec = NULL;
1409 PLpgSQL_row *row = NULL;
1410 SPITupleTable *tuptab;
1413 int rc = PLPGSQL_RC_OK;
1418 * Determine if we assign to a record or a row
1420 if (stmt->rec != NULL)
1421 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
1422 else if (stmt->row != NULL)
1423 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
1425 elog(ERROR, "unsupported target");
1428 * Open the implicit cursor for the statement and fetch the initial 10
1431 exec_run_select(estate, stmt->query, 0, &portal);
1433 SPI_cursor_fetch(portal, true, 10);
1434 tuptab = SPI_tuptable;
1438 * If the query didn't return any rows, set the target to NULL and
1439 * return with FOUND = false.
1442 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
1444 found = true; /* processed at least one tuple */
1451 for (i = 0; i < n; i++)
1454 * Assign the tuple to the target
1456 exec_move_row(estate, rec, row, tuptab->vals[i], tuptab->tupdesc);
1459 * Execute the statements
1461 rc = exec_stmts(estate, stmt->body);
1463 if (rc != PLPGSQL_RC_OK)
1466 * We're aborting the loop, so cleanup and set FOUND.
1467 * (This code should match the code after the loop.)
1469 SPI_freetuptable(tuptab);
1470 SPI_cursor_close(portal);
1471 exec_set_found(estate, found);
1473 if (rc == PLPGSQL_RC_EXIT)
1475 if (estate->exitlabel == NULL)
1476 /* unlabelled exit, finish the current loop */
1478 else if (stmt->label != NULL &&
1479 strcmp(stmt->label, estate->exitlabel) == 0)
1481 /* labelled exit, matches the current stmt's label */
1482 estate->exitlabel = NULL;
1487 * otherwise, we processed a labelled exit that does
1488 * not match the current statement's label, if any:
1489 * return RC_EXIT so that the EXIT continues to
1498 SPI_freetuptable(tuptab);
1501 * Fetch the next 50 tuples
1503 SPI_cursor_fetch(portal, true, 50);
1505 tuptab = SPI_tuptable;
1509 * Release last group of tuples
1511 SPI_freetuptable(tuptab);
1514 * Close the implicit cursor
1516 SPI_cursor_close(portal);
1519 * Set the FOUND variable to indicate the result of executing the loop
1520 * (namely, whether we looped one or more times). This must be set
1521 * here so that it does not interfere with the value of the FOUND
1522 * variable inside the loop processing itself.
1524 exec_set_found(estate, found);
1531 * exec_stmt_select Run a query and assign the first
1532 * row to a record or rowtype.
1536 exec_stmt_select(PLpgSQL_execstate *estate, PLpgSQL_stmt_select *stmt)
1538 PLpgSQL_rec *rec = NULL;
1539 PLpgSQL_row *row = NULL;
1540 SPITupleTable *tuptab;
1544 * Initialize the global found variable to false
1546 exec_set_found(estate, false);
1549 * Determine if we assign to a record or a row
1551 if (stmt->rec != NULL)
1552 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
1553 else if (stmt->row != NULL)
1554 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
1556 elog(ERROR, "unsupported target");
1561 exec_run_select(estate, stmt->query, 1, NULL);
1562 tuptab = estate->eval_tuptable;
1563 n = estate->eval_processed;
1566 * If the query didn't return any row, set the target to NULL and
1571 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
1572 exec_eval_cleanup(estate);
1573 return PLPGSQL_RC_OK;
1577 * Put the result into the target and set found to true
1579 exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
1580 exec_set_found(estate, true);
1582 exec_eval_cleanup(estate);
1584 return PLPGSQL_RC_OK;
1589 * exec_stmt_exit Start exiting loop(s) or blocks
1593 exec_stmt_exit(PLpgSQL_execstate *estate, PLpgSQL_stmt_exit *stmt)
1596 * If the exit has a condition, check that it's true
1598 if (stmt->cond != NULL)
1601 bool isnull = false;
1603 value = exec_eval_boolean(estate, stmt->cond, &isnull);
1604 exec_eval_cleanup(estate);
1605 if (isnull || !value)
1606 return PLPGSQL_RC_OK;
1609 estate->exitlabel = stmt->label;
1610 return PLPGSQL_RC_EXIT;
1615 * exec_stmt_return Evaluate an expression and start
1616 * returning from the function.
1620 exec_stmt_return(PLpgSQL_execstate *estate, PLpgSQL_stmt_return *stmt)
1623 * If processing a set-returning PL/PgSQL function, the final RETURN
1624 * indicates that the function is finished producing tuples. The rest
1625 * of the work will be done at the top level.
1627 if (estate->retisset)
1628 return PLPGSQL_RC_RETURN;
1630 /* initialize for null result (possibly a tuple) */
1631 estate->retval = (Datum) 0;
1632 estate->rettupdesc = NULL;
1633 estate->retisnull = true;
1635 if (stmt->retvarno >= 0)
1637 PLpgSQL_datum *retvar = estate->datums[stmt->retvarno];
1639 switch (retvar->dtype)
1641 case PLPGSQL_DTYPE_VAR:
1643 PLpgSQL_var *var = (PLpgSQL_var *) retvar;
1645 estate->retval = var->value;
1646 estate->retisnull = var->isnull;
1647 estate->rettype = var->datatype->typoid;
1651 case PLPGSQL_DTYPE_REC:
1653 PLpgSQL_rec *rec = (PLpgSQL_rec *) retvar;
1655 if (HeapTupleIsValid(rec->tup))
1657 estate->retval = (Datum) rec->tup;
1658 estate->rettupdesc = rec->tupdesc;
1659 estate->retisnull = false;
1664 case PLPGSQL_DTYPE_ROW:
1666 PLpgSQL_row *row = (PLpgSQL_row *) retvar;
1668 Assert(row->rowtupdesc);
1669 estate->retval = (Datum) make_tuple_from_row(estate, row,
1671 if (estate->retval == (Datum) NULL) /* should not happen */
1672 elog(ERROR, "row not compatible with its own tupdesc");
1673 estate->rettupdesc = row->rowtupdesc;
1674 estate->retisnull = false;
1679 elog(ERROR, "unrecognized dtype: %d", retvar->dtype);
1682 return PLPGSQL_RC_RETURN;
1685 if (stmt->expr != NULL)
1687 if (estate->retistuple)
1689 exec_run_select(estate, stmt->expr, 1, NULL);
1690 if (estate->eval_processed > 0)
1692 estate->retval = (Datum) estate->eval_tuptable->vals[0];
1693 estate->rettupdesc = estate->eval_tuptable->tupdesc;
1694 estate->retisnull = false;
1699 /* Normal case for scalar results */
1700 estate->retval = exec_eval_expr(estate, stmt->expr,
1701 &(estate->retisnull),
1702 &(estate->rettype));
1705 return PLPGSQL_RC_RETURN;
1709 * Special hack for function returning VOID: instead of NULL, return a
1710 * non-null VOID value. This is of dubious importance but is kept for
1711 * backwards compatibility. Note that the only other way to get here
1712 * is to have written "RETURN NULL" in a function returning tuple.
1714 if (estate->fn_rettype == VOIDOID)
1716 estate->retval = (Datum) 0;
1717 estate->retisnull = false;
1718 estate->rettype = VOIDOID;
1721 return PLPGSQL_RC_RETURN;
1725 * exec_stmt_return_next Evaluate an expression and add it to the
1726 * list of tuples returned by the current
1731 exec_stmt_return_next(PLpgSQL_execstate *estate,
1732 PLpgSQL_stmt_return_next *stmt)
1737 bool free_tuple = false;
1739 if (!estate->retisset)
1741 (errcode(ERRCODE_SYNTAX_ERROR),
1742 errmsg("cannot use RETURN NEXT in a non-SETOF function")));
1744 if (estate->tuple_store == NULL)
1745 exec_init_tuple_store(estate);
1747 /* rettupdesc will be filled by exec_init_tuple_store */
1748 tupdesc = estate->rettupdesc;
1749 natts = tupdesc->natts;
1751 if (stmt->retvarno >= 0)
1753 PLpgSQL_datum *retvar = estate->datums[stmt->retvarno];
1755 switch (retvar->dtype)
1757 case PLPGSQL_DTYPE_VAR:
1759 PLpgSQL_var *var = (PLpgSQL_var *) retvar;
1760 Datum retval = var->value;
1761 bool isNull = var->isnull;
1765 (errcode(ERRCODE_DATATYPE_MISMATCH),
1766 errmsg("wrong result type supplied in RETURN NEXT")));
1768 /* coerce type if needed */
1769 retval = exec_simple_cast_value(retval,
1770 var->datatype->typoid,
1771 tupdesc->attrs[0]->atttypid,
1772 tupdesc->attrs[0]->atttypmod,
1775 tuple = heap_form_tuple(tupdesc, &retval, &isNull);
1781 case PLPGSQL_DTYPE_REC:
1783 PLpgSQL_rec *rec = (PLpgSQL_rec *) retvar;
1785 if (!HeapTupleIsValid(rec->tup))
1787 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1788 errmsg("record \"%s\" is not assigned yet",
1790 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
1791 if (!compatible_tupdesc(tupdesc, rec->tupdesc))
1793 (errcode(ERRCODE_DATATYPE_MISMATCH),
1794 errmsg("wrong record type supplied in RETURN NEXT")));
1799 case PLPGSQL_DTYPE_ROW:
1801 PLpgSQL_row *row = (PLpgSQL_row *) retvar;
1803 tuple = make_tuple_from_row(estate, row, tupdesc);
1806 (errcode(ERRCODE_DATATYPE_MISMATCH),
1807 errmsg("wrong record type supplied in RETURN NEXT")));
1813 elog(ERROR, "unrecognized dtype: %d", retvar->dtype);
1814 tuple = NULL; /* keep compiler quiet */
1818 else if (stmt->expr)
1826 (errcode(ERRCODE_DATATYPE_MISMATCH),
1827 errmsg("wrong result type supplied in RETURN NEXT")));
1829 retval = exec_eval_expr(estate,
1834 /* coerce type if needed */
1835 retval = exec_simple_cast_value(retval,
1837 tupdesc->attrs[0]->atttypid,
1838 tupdesc->attrs[0]->atttypmod,
1841 tuple = heap_form_tuple(tupdesc, &retval, &isNull);
1845 exec_eval_cleanup(estate);
1850 (errcode(ERRCODE_SYNTAX_ERROR),
1851 errmsg("RETURN NEXT must have a parameter")));
1852 tuple = NULL; /* keep compiler quiet */
1855 if (HeapTupleIsValid(tuple))
1857 MemoryContext oldcxt;
1859 oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
1860 tuplestore_puttuple(estate->tuple_store, tuple);
1861 MemoryContextSwitchTo(oldcxt);
1864 heap_freetuple(tuple);
1867 return PLPGSQL_RC_OK;
1871 exec_init_tuple_store(PLpgSQL_execstate *estate)
1873 ReturnSetInfo *rsi = estate->rsi;
1874 MemoryContext oldcxt;
1877 * Check caller can handle a set result in the way we want
1879 if (!rsi || !IsA(rsi, ReturnSetInfo) ||
1880 (rsi->allowedModes & SFRM_Materialize) == 0 ||
1881 rsi->expectedDesc == NULL)
1883 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1884 errmsg("set-valued function called in context that cannot accept a set")));
1886 estate->tuple_store_cxt = rsi->econtext->ecxt_per_query_memory;
1888 oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
1889 estate->tuple_store = tuplestore_begin_heap(true, false, work_mem);
1890 MemoryContextSwitchTo(oldcxt);
1892 estate->rettupdesc = rsi->expectedDesc;
1896 * exec_stmt_raise Build a message and throw it with elog()
1900 exec_stmt_raise(PLpgSQL_execstate *estate, PLpgSQL_stmt_raise *stmt)
1904 ListCell *current_param;
1906 plpgsql_dstring_init(&ds);
1907 current_param = list_head(stmt->params);
1909 for (cp = stmt->message; *cp; cp++)
1912 * Occurrences of a single % are replaced by the next parameter's
1913 * external representation. Double %'s are converted to one %.
1924 plpgsql_dstring_append_char(&ds, cp[1]);
1929 if (current_param == NULL)
1931 (errcode(ERRCODE_SYNTAX_ERROR),
1932 errmsg("too few parameters specified for RAISE")));
1934 paramvalue = exec_eval_expr(estate,
1935 (PLpgSQL_expr *) lfirst(current_param),
1942 extval = convert_value_to_string(paramvalue, paramtypeid);
1943 plpgsql_dstring_append(&ds, extval);
1944 current_param = lnext(current_param);
1945 exec_eval_cleanup(estate);
1949 plpgsql_dstring_append_char(&ds, cp[0]);
1953 * If more parameters were specified than were required to process
1954 * the format string, throw an error
1956 if (current_param != NULL)
1958 (errcode(ERRCODE_SYNTAX_ERROR),
1959 errmsg("too many parameters specified for RAISE")));
1962 * Throw the error (may or may not come back)
1964 estate->err_text = raise_skip_msg; /* suppress traceback of raise */
1966 ereport(stmt->elog_level,
1967 ((stmt->elog_level >= ERROR) ? errcode(ERRCODE_RAISE_EXCEPTION) : 0,
1968 errmsg_internal("%s", plpgsql_dstring_get(&ds))));
1970 estate->err_text = NULL; /* un-suppress... */
1972 plpgsql_dstring_free(&ds);
1974 return PLPGSQL_RC_OK;
1979 * Initialize a mostly empty execution state
1983 plpgsql_estate_setup(PLpgSQL_execstate *estate,
1984 PLpgSQL_function *func,
1987 estate->retval = (Datum) 0;
1988 estate->retisnull = true;
1989 estate->rettype = InvalidOid;
1991 estate->fn_rettype = func->fn_rettype;
1992 estate->retistuple = func->fn_retistuple;
1993 estate->retisset = func->fn_retset;
1995 estate->readonly_func = func->fn_readonly;
1997 estate->rettupdesc = NULL;
1998 estate->exitlabel = NULL;
2000 estate->tuple_store = NULL;
2001 estate->tuple_store_cxt = NULL;
2004 estate->trig_nargs = 0;
2005 estate->trig_argv = NULL;
2007 estate->found_varno = func->found_varno;
2008 estate->ndatums = func->ndatums;
2009 estate->datums = palloc(sizeof(PLpgSQL_datum *) * estate->ndatums);
2010 /* caller is expected to fill the datums array */
2012 estate->eval_tuptable = NULL;
2013 estate->eval_processed = 0;
2014 estate->eval_lastoid = InvalidOid;
2015 estate->eval_econtext = NULL;
2017 estate->err_func = func;
2018 estate->err_stmt = NULL;
2019 estate->err_text = NULL;
2023 * Release temporary memory used by expression/subselect evaluation
2025 * NB: the result of the evaluation is no longer valid after this is done,
2026 * unless it is a pass-by-value datatype.
2030 exec_eval_cleanup(PLpgSQL_execstate *estate)
2032 /* Clear result of a full SPI_execute */
2033 if (estate->eval_tuptable != NULL)
2034 SPI_freetuptable(estate->eval_tuptable);
2035 estate->eval_tuptable = NULL;
2037 /* Clear result of exec_eval_simple_expr (but keep the econtext) */
2038 if (estate->eval_econtext != NULL)
2039 ResetExprContext(estate->eval_econtext);
2044 * Generate a prepared plan
2048 exec_prepare_plan(PLpgSQL_execstate *estate,
2052 _SPI_plan *spi_plan;
2057 * We need a temporary argtypes array to load with data. (The finished
2058 * plan structure will contain a copy of it.)
2060 argtypes = (Oid *) palloc(expr->nparams * sizeof(Oid));
2062 for (i = 0; i < expr->nparams; i++)
2067 exec_eval_datum(estate, estate->datums[expr->params[i]],
2069 &argtypes[i], ¶mval, ¶misnull);
2073 * Generate and save the plan
2075 plan = SPI_prepare(expr->query, expr->nparams, argtypes);
2078 /* Some SPI errors deserve specific error messages */
2081 case SPI_ERROR_COPY:
2083 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2084 errmsg("cannot COPY to/from client in PL/pgSQL")));
2085 case SPI_ERROR_CURSOR:
2087 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2088 errmsg("cannot manipulate cursors directly in PL/pgSQL"),
2089 errhint("Use PL/pgSQL's cursor features instead.")));
2090 case SPI_ERROR_TRANSACTION:
2092 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2093 errmsg("cannot begin/end transactions in PL/pgSQL"),
2094 errhint("Use a BEGIN block with an EXCEPTION clause instead.")));
2096 elog(ERROR, "SPI_prepare failed for \"%s\": %s",
2097 expr->query, SPI_result_code_string(SPI_result));
2100 expr->plan = SPI_saveplan(plan);
2101 spi_plan = (_SPI_plan *) expr->plan;
2102 expr->plan_argtypes = spi_plan->argtypes;
2103 expr->expr_simple_expr = NULL;
2104 exec_simple_check_plan(expr);
2112 * exec_stmt_execsql Execute an SQL statement not
2113 * returning any data.
2117 exec_stmt_execsql(PLpgSQL_execstate *estate,
2118 PLpgSQL_stmt_execsql *stmt)
2124 PLpgSQL_expr *expr = stmt->sqlstmt;
2127 * On the first call for this expression generate the plan
2129 if (expr->plan == NULL)
2130 exec_prepare_plan(estate, expr);
2133 * Now build up the values and nulls arguments for SPI_execute_plan()
2135 values = (Datum *) palloc(expr->nparams * sizeof(Datum));
2136 nulls = (char *) palloc(expr->nparams * sizeof(char));
2138 for (i = 0; i < expr->nparams; i++)
2140 PLpgSQL_datum *datum = estate->datums[expr->params[i]];
2144 exec_eval_datum(estate, datum, expr->plan_argtypes[i],
2145 ¶mtypeid, &values[i], ¶misnull);
2155 rc = SPI_execute_plan(expr->plan, values, nulls,
2156 estate->readonly_func, 0);
2159 case SPI_OK_UTILITY:
2160 case SPI_OK_SELINTO:
2168 * If the INSERT, DELETE, or UPDATE query affected at least
2169 * one tuple, set the magic 'FOUND' variable to true. This
2170 * conforms with the behavior of PL/SQL.
2172 exec_set_found(estate, (SPI_processed != 0));
2177 (errcode(ERRCODE_SYNTAX_ERROR),
2178 errmsg("SELECT query has no destination for result data"),
2179 errhint("If you want to discard the results, use PERFORM instead.")));
2182 elog(ERROR, "SPI_execute_plan failed executing query \"%s\": %s",
2183 expr->query, SPI_result_code_string(rc));
2187 * Release any result tuples from SPI_execute_plan (probably shouldn't be
2190 SPI_freetuptable(SPI_tuptable);
2192 /* Save result info for GET DIAGNOSTICS */
2193 estate->eval_processed = SPI_processed;
2194 estate->eval_lastoid = SPI_lastoid;
2199 return PLPGSQL_RC_OK;
2204 * exec_stmt_dynexecute Execute a dynamic SQL query not
2205 * returning any data.
2209 exec_stmt_dynexecute(PLpgSQL_execstate *estate,
2210 PLpgSQL_stmt_dynexecute *stmt)
2213 bool isnull = false;
2217 PLpgSQL_rec *rec = NULL;
2218 PLpgSQL_row *row = NULL;
2220 if (stmt->rec != NULL)
2221 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
2222 else if (stmt->row != NULL)
2223 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
2226 * First we evaluate the string expression after the EXECUTE keyword.
2227 * It's result is the querystring we have to execute.
2229 query = exec_eval_expr(estate, stmt->query, &isnull, &restype);
2232 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2233 errmsg("cannot EXECUTE a null querystring")));
2235 /* Get the C-String representation */
2236 querystr = convert_value_to_string(query, restype);
2238 exec_eval_cleanup(estate);
2241 * Call SPI_execute() without preparing a saved plan. The returncode can
2242 * be any standard OK. Note that while a SELECT is allowed, its
2243 * results will be discarded unless an INTO clause is specified.
2245 exec_res = SPI_execute(querystr, estate->readonly_func, 0);
2247 /* Assign to INTO variable */
2250 if (exec_res != SPI_OK_SELECT)
2252 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2253 errmsg("EXECUTE ... INTO is only for SELECT")));
2256 if (SPI_processed == 0)
2257 exec_move_row(estate, rec, row, NULL, SPI_tuptable->tupdesc);
2259 exec_move_row(estate, rec, row,
2260 SPI_tuptable->vals[0], SPI_tuptable->tupdesc);
2270 case SPI_OK_UTILITY:
2276 * Also allow a zero return, which implies the querystring
2277 * contained no commands.
2281 case SPI_OK_SELINTO:
2284 * We want to disallow SELECT INTO for now, because its
2285 * behavior is not consistent with SELECT INTO in a normal
2286 * plpgsql context. (We need to reimplement EXECUTE to parse
2287 * the string as a plpgsql command, not just feed it to
2288 * SPI_execute.) However, CREATE AS should be allowed ... and
2289 * since it produces the same parsetree as SELECT INTO,
2290 * there's no way to tell the difference except to look at the
2291 * source text. Wotta kluge!
2296 for (ptr = querystr; *ptr; ptr++)
2297 if (!isspace((unsigned char) *ptr))
2299 if (*ptr == 'S' || *ptr == 's')
2301 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2302 errmsg("EXECUTE of SELECT ... INTO is not implemented yet")));
2306 /* Some SPI errors deserve specific error messages */
2307 case SPI_ERROR_COPY:
2309 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2310 errmsg("cannot COPY to/from client in PL/pgSQL")));
2311 case SPI_ERROR_CURSOR:
2313 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2314 errmsg("cannot manipulate cursors directly in PL/pgSQL"),
2315 errhint("Use PL/pgSQL's cursor features instead.")));
2316 case SPI_ERROR_TRANSACTION:
2318 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2319 errmsg("cannot begin/end transactions in PL/pgSQL"),
2320 errhint("Use a BEGIN block with an EXCEPTION clause instead.")));
2323 elog(ERROR, "SPI_execute failed executing query \"%s\": %s",
2324 querystr, SPI_result_code_string(exec_res));
2328 /* Release any result from SPI_execute, as well as the querystring */
2329 SPI_freetuptable(SPI_tuptable);
2332 /* Save result info for GET DIAGNOSTICS */
2333 estate->eval_processed = SPI_processed;
2334 estate->eval_lastoid = SPI_lastoid;
2336 return PLPGSQL_RC_OK;
2341 * exec_stmt_dynfors Execute a dynamic query, assign each
2342 * tuple to a record or row and
2343 * execute a group of statements
2348 exec_stmt_dynfors(PLpgSQL_execstate *estate, PLpgSQL_stmt_dynfors *stmt)
2351 bool isnull = false;
2354 PLpgSQL_rec *rec = NULL;
2355 PLpgSQL_row *row = NULL;
2356 SPITupleTable *tuptab;
2357 int rc = PLPGSQL_RC_OK;
2365 * Determine if we assign to a record or a row
2367 if (stmt->rec != NULL)
2368 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
2369 else if (stmt->row != NULL)
2370 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
2372 elog(ERROR, "unsupported target");
2375 * Evaluate the string expression after the EXECUTE keyword. It's
2376 * result is the querystring we have to execute.
2378 query = exec_eval_expr(estate, stmt->query, &isnull, &restype);
2381 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2382 errmsg("cannot EXECUTE a null querystring")));
2384 /* Get the C-String representation */
2385 querystr = convert_value_to_string(query, restype);
2387 exec_eval_cleanup(estate);
2390 * Prepare a plan and open an implicit cursor for the query
2392 plan = SPI_prepare(querystr, 0, NULL);
2394 elog(ERROR, "SPI_prepare failed for \"%s\": %s",
2395 querystr, SPI_result_code_string(SPI_result));
2396 portal = SPI_cursor_open(NULL, plan, NULL, NULL,
2397 estate->readonly_func);
2399 elog(ERROR, "could not open implicit cursor for query \"%s\": %s",
2400 querystr, SPI_result_code_string(SPI_result));
2405 * Fetch the initial 10 tuples
2407 SPI_cursor_fetch(portal, true, 10);
2408 tuptab = SPI_tuptable;
2412 * If the query didn't return any rows, set the target to NULL and
2413 * return with FOUND = false.
2416 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
2418 found = true; /* processed at least one tuple */
2425 for (i = 0; i < n; i++)
2428 * Assign the tuple to the target
2430 exec_move_row(estate, rec, row, tuptab->vals[i], tuptab->tupdesc);
2433 * Execute the statements
2435 rc = exec_stmts(estate, stmt->body);
2437 if (rc != PLPGSQL_RC_OK)
2440 * We're aborting the loop, so cleanup and set FOUND.
2441 * (This code should match the code after the loop.)
2443 SPI_freetuptable(tuptab);
2444 SPI_cursor_close(portal);
2445 exec_set_found(estate, found);
2447 if (rc == PLPGSQL_RC_EXIT)
2449 if (estate->exitlabel == NULL)
2450 /* unlabelled exit, finish the current loop */
2452 else if (stmt->label != NULL &&
2453 strcmp(stmt->label, estate->exitlabel) == 0)
2455 /* labelled exit, matches the current stmt's label */
2456 estate->exitlabel = NULL;
2461 * otherwise, we processed a labelled exit that does
2462 * not match the current statement's label, if any:
2463 * return RC_EXIT so that the EXIT continues to
2472 SPI_freetuptable(tuptab);
2475 * Fetch the next 50 tuples
2477 SPI_cursor_fetch(portal, true, 50);
2479 tuptab = SPI_tuptable;
2483 * Release last group of tuples
2485 SPI_freetuptable(tuptab);
2488 * Close the implicit cursor
2490 SPI_cursor_close(portal);
2493 * Set the FOUND variable to indicate the result of executing the loop
2494 * (namely, whether we looped one or more times). This must be set
2495 * here so that it does not interfere with the value of the FOUND
2496 * variable inside the loop processing itself.
2498 exec_set_found(estate, found);
2500 return PLPGSQL_RC_OK;
2505 * exec_stmt_open Execute an OPEN cursor statement
2509 exec_stmt_open(PLpgSQL_execstate *estate, PLpgSQL_stmt_open *stmt)
2511 PLpgSQL_var *curvar = NULL;
2512 char *curname = NULL;
2513 PLpgSQL_expr *query = NULL;
2522 * Get the cursor variable and if it has an assigned name, check
2523 * that it's not in use currently.
2526 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
2527 if (!curvar->isnull)
2529 curname = DatumGetCString(DirectFunctionCall1(textout, curvar->value));
2530 if (SPI_cursor_find(curname) != NULL)
2532 (errcode(ERRCODE_DUPLICATE_CURSOR),
2533 errmsg("cursor \"%s\" already in use", curname)));
2537 * Process the OPEN according to it's type.
2540 if (stmt->query != NULL)
2543 * This is an OPEN refcursor FOR SELECT ...
2545 * We just make sure the query is planned. The real work is
2549 query = stmt->query;
2550 if (query->plan == NULL)
2551 exec_prepare_plan(estate, query);
2553 else if (stmt->dynquery != NULL)
2556 * This is an OPEN refcursor FOR EXECUTE ...
2565 * We evaluate the string expression after the
2566 * EXECUTE keyword. It's result is the querystring we have
2570 queryD = exec_eval_expr(estate, stmt->dynquery, &isnull, &restype);
2573 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2574 errmsg("cannot EXECUTE a null querystring")));
2576 /* Get the C-String representation */
2577 querystr = convert_value_to_string(queryD, restype);
2579 exec_eval_cleanup(estate);
2582 * Now we prepare a query plan for it and open a cursor
2585 curplan = SPI_prepare(querystr, 0, NULL);
2586 if (curplan == NULL)
2587 elog(ERROR, "SPI_prepare failed for \"%s\": %s",
2588 querystr, SPI_result_code_string(SPI_result));
2589 portal = SPI_cursor_open(curname, curplan, NULL, NULL,
2590 estate->readonly_func);
2592 elog(ERROR, "could not open cursor for query \"%s\": %s",
2593 querystr, SPI_result_code_string(SPI_result));
2595 SPI_freeplan(curplan);
2598 * Store the eventually assigned cursor name in the cursor variable
2602 curvar->value = DirectFunctionCall1(textin, CStringGetDatum(portal->name));
2603 curvar->isnull = false;
2604 curvar->freeval = true;
2606 return PLPGSQL_RC_OK;
2611 * This is an OPEN cursor
2613 * Note: parser should already have checked that statement supplies
2614 * args iff cursor needs them, but we check again to be safe.
2617 if (stmt->argquery != NULL)
2620 * Er - OPEN CURSOR (args). We fake a SELECT ... INTO ...
2621 * statement to evaluate the args and put 'em into the
2625 PLpgSQL_stmt_select set_args;
2627 if (curvar->cursor_explicit_argrow < 0)
2629 (errcode(ERRCODE_SYNTAX_ERROR),
2630 errmsg("arguments given for cursor without arguments")));
2632 memset(&set_args, 0, sizeof(set_args));
2633 set_args.cmd_type = PLPGSQL_STMT_SELECT;
2634 set_args.lineno = stmt->lineno;
2635 set_args.row = (PLpgSQL_row *)
2636 (estate->datums[curvar->cursor_explicit_argrow]);
2637 set_args.query = stmt->argquery;
2639 if (exec_stmt_select(estate, &set_args) != PLPGSQL_RC_OK)
2640 elog(ERROR, "open cursor failed during argument processing");
2644 if (curvar->cursor_explicit_argrow >= 0)
2646 (errcode(ERRCODE_SYNTAX_ERROR),
2647 errmsg("arguments required for cursor")));
2650 query = curvar->cursor_explicit_expr;
2651 if (query->plan == NULL)
2652 exec_prepare_plan(estate, query);
2656 * Here we go if we have a saved plan where we have to put
2657 * values into, either from an explicit cursor or from a
2658 * refcursor opened with OPEN ... FOR SELECT ...;
2661 values = (Datum *) palloc(query->nparams * sizeof(Datum));
2662 nulls = (char *) palloc(query->nparams * sizeof(char));
2664 for (i = 0; i < query->nparams; i++)
2666 PLpgSQL_datum *datum = estate->datums[query->params[i]];
2670 exec_eval_datum(estate, datum, query->plan_argtypes[i],
2671 ¶mtypeid, &values[i], ¶misnull);
2682 portal = SPI_cursor_open(curname, query->plan, values, nulls,
2683 estate->readonly_func);
2685 elog(ERROR, "could not open cursor: %s",
2686 SPI_result_code_string(SPI_result));
2694 * Store the eventually assigned portal name in the cursor variable
2698 curvar->value = DirectFunctionCall1(textin, CStringGetDatum(portal->name));
2699 curvar->isnull = false;
2700 curvar->freeval = true;
2702 return PLPGSQL_RC_OK;
2707 * exec_stmt_fetch Fetch from a cursor into a target
2711 exec_stmt_fetch(PLpgSQL_execstate *estate, PLpgSQL_stmt_fetch *stmt)
2713 PLpgSQL_var *curvar = NULL;
2714 PLpgSQL_rec *rec = NULL;
2715 PLpgSQL_row *row = NULL;
2716 SPITupleTable *tuptab;
2722 * Get the portal of the cursor by name
2725 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
2728 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2729 errmsg("cursor variable \"%s\" is NULL", curvar->refname)));
2730 curname = DatumGetCString(DirectFunctionCall1(textout, curvar->value));
2732 portal = SPI_cursor_find(curname);
2735 (errcode(ERRCODE_UNDEFINED_CURSOR),
2736 errmsg("cursor \"%s\" does not exist", curname)));
2740 * Determine if we fetch into a record or a row
2743 if (stmt->rec != NULL)
2744 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
2745 else if (stmt->row != NULL)
2746 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
2748 elog(ERROR, "unsupported target");
2751 * Fetch 1 tuple from the cursor
2754 SPI_cursor_fetch(portal, true, 1);
2755 tuptab = SPI_tuptable;
2759 * Set the target and the global FOUND variable appropriately.
2764 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
2765 exec_set_found(estate, false);
2769 exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
2770 exec_set_found(estate, true);
2773 SPI_freetuptable(tuptab);
2775 return PLPGSQL_RC_OK;
2780 * exec_stmt_close Close a cursor
2784 exec_stmt_close(PLpgSQL_execstate *estate, PLpgSQL_stmt_close *stmt)
2786 PLpgSQL_var *curvar = NULL;
2791 * Get the portal of the cursor by name
2794 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
2797 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2798 errmsg("cursor variable \"%s\" is NULL", curvar->refname)));
2799 curname = DatumGetCString(DirectFunctionCall1(textout, curvar->value));
2801 portal = SPI_cursor_find(curname);
2804 (errcode(ERRCODE_UNDEFINED_CURSOR),
2805 errmsg("cursor \"%s\" does not exist", curname)));
2812 SPI_cursor_close(portal);
2814 return PLPGSQL_RC_OK;
2819 * exec_assign_expr Put an expression's result into
2824 exec_assign_expr(PLpgSQL_execstate *estate, PLpgSQL_datum *target,
2829 bool isnull = false;
2831 value = exec_eval_expr(estate, expr, &isnull, &valtype);
2832 exec_assign_value(estate, target, value, valtype, &isnull);
2833 exec_eval_cleanup(estate);
2838 * exec_assign_value Put a value into a target field
2842 exec_assign_value(PLpgSQL_execstate *estate,
2843 PLpgSQL_datum *target,
2844 Datum value, Oid valtype, bool *isNull)
2846 switch (target->dtype)
2848 case PLPGSQL_DTYPE_VAR:
2851 * Target is a variable
2853 PLpgSQL_var *var = (PLpgSQL_var *) target;
2856 newvalue = exec_cast_value(value, valtype, var->datatype->typoid,
2857 &(var->datatype->typinput),
2858 var->datatype->typioparam,
2859 var->datatype->atttypmod,
2862 if (*isNull && var->notnull)
2864 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2865 errmsg("NULL cannot be assigned to variable \"%s\" declared NOT NULL",
2869 * If type is by-reference, make sure we have a freshly
2870 * palloc'd copy; the originally passed value may not live
2871 * as long as the variable! But we don't need to re-copy
2872 * if exec_cast_value performed a conversion; its output
2873 * must already be palloc'd.
2875 if (!var->datatype->typbyval && !*isNull)
2877 if (newvalue == value)
2878 newvalue = datumCopy(newvalue,
2880 var->datatype->typlen);
2884 * Now free the old value. (We can't do this any earlier
2885 * because of the possibility that we are assigning the
2886 * var's old value to it, eg "foo := foo". We could optimize
2887 * out the assignment altogether in such cases, but it's too
2888 * infrequent to be worth testing for.)
2892 var->value = newvalue;
2893 var->isnull = *isNull;
2894 if (!var->datatype->typbyval && !*isNull)
2895 var->freeval = true;
2899 case PLPGSQL_DTYPE_ROW:
2902 * Target is a row variable
2904 PLpgSQL_row *row = (PLpgSQL_row *) target;
2906 /* Source must be of RECORD or composite type */
2907 if (!(valtype == RECORDOID ||
2908 get_typtype(valtype) == 'c'))
2910 (errcode(ERRCODE_DATATYPE_MISMATCH),
2911 errmsg("cannot assign non-composite value to a row variable")));
2914 /* If source is null, just assign nulls to the row */
2915 exec_move_row(estate, NULL, row, NULL, NULL);
2923 HeapTupleData tmptup;
2925 /* Else source is a tuple Datum, safe to do this: */
2926 td = DatumGetHeapTupleHeader(value);
2927 /* Extract rowtype info and find a tupdesc */
2928 tupType = HeapTupleHeaderGetTypeId(td);
2929 tupTypmod = HeapTupleHeaderGetTypMod(td);
2930 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
2931 /* Build a temporary HeapTuple control structure */
2932 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
2933 ItemPointerSetInvalid(&(tmptup.t_self));
2934 tmptup.t_tableOid = InvalidOid;
2936 exec_move_row(estate, NULL, row, &tmptup, tupdesc);
2941 case PLPGSQL_DTYPE_REC:
2944 * Target is a record variable
2946 PLpgSQL_rec *rec = (PLpgSQL_rec *) target;
2948 /* Source must be of RECORD or composite type */
2949 if (!(valtype == RECORDOID ||
2950 get_typtype(valtype) == 'c'))
2952 (errcode(ERRCODE_DATATYPE_MISMATCH),
2953 errmsg("cannot assign non-composite value to a record variable")));
2956 /* If source is null, just assign nulls to the record */
2957 exec_move_row(estate, rec, NULL, NULL, NULL);
2965 HeapTupleData tmptup;
2967 /* Else source is a tuple Datum, safe to do this: */
2968 td = DatumGetHeapTupleHeader(value);
2969 /* Extract rowtype info and find a tupdesc */
2970 tupType = HeapTupleHeaderGetTypeId(td);
2971 tupTypmod = HeapTupleHeaderGetTypMod(td);
2972 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
2973 /* Build a temporary HeapTuple control structure */
2974 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
2975 ItemPointerSetInvalid(&(tmptup.t_self));
2976 tmptup.t_tableOid = InvalidOid;
2978 exec_move_row(estate, rec, NULL, &tmptup, tupdesc);
2983 case PLPGSQL_DTYPE_RECFIELD:
2986 * Target is a field of a record
2988 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) target;
3001 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
3004 * Check that there is already a tuple in the record. We
3005 * need that because records don't have any predefined
3008 if (!HeapTupleIsValid(rec->tup))
3010 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3011 errmsg("record \"%s\" is not assigned yet",
3013 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
3016 * Get the number of the records field to change and the
3017 * number of attributes in the tuple.
3019 fno = SPI_fnumber(rec->tupdesc, recfield->fieldname);
3020 if (fno == SPI_ERROR_NOATTRIBUTE)
3022 (errcode(ERRCODE_UNDEFINED_COLUMN),
3023 errmsg("record \"%s\" has no field \"%s\"",
3024 rec->refname, recfield->fieldname)));
3026 natts = rec->tupdesc->natts;
3029 * Set up values/datums arrays for heap_formtuple. For
3030 * all the attributes except the one we want to replace,
3031 * use the value that's in the old tuple.
3033 values = palloc(sizeof(Datum) * natts);
3034 nulls = palloc(natts);
3036 for (i = 0; i < natts; i++)
3040 values[i] = SPI_getbinval(rec->tup, rec->tupdesc,
3049 * Now insert the new value, being careful to cast it to
3052 atttype = SPI_gettypeid(rec->tupdesc, fno + 1);
3053 atttypmod = rec->tupdesc->attrs[fno]->atttypmod;
3054 attisnull = *isNull;
3055 values[fno] = exec_simple_cast_value(value,
3066 * Avoid leaking the result of exec_simple_cast_value, if
3067 * it performed a conversion to a pass-by-ref type.
3069 if (!attisnull && values[fno] != value && !get_typbyval(atttype))
3070 mustfree = DatumGetPointer(values[fno]);
3075 * Now call heap_formtuple() to create a new tuple that
3076 * replaces the old one in the record.
3078 newtup = heap_formtuple(rec->tupdesc, values, nulls);
3081 heap_freetuple(rec->tup);
3084 rec->freetup = true;
3094 case PLPGSQL_DTYPE_ARRAYELEM:
3098 PLpgSQL_expr *subscripts[MAXDIM];
3099 int subscriptvals[MAXDIM];
3100 bool havenullsubscript,
3108 Datum oldarraydatum,
3110 ArrayType *oldarrayval;
3111 ArrayType *newarrayval;
3114 * Target is an element of an array
3116 * To handle constructs like x[1][2] := something, we have to
3117 * be prepared to deal with a chain of arrayelem datums.
3118 * Chase back to find the base array datum, and save the
3119 * subscript expressions as we go. (We are scanning right
3120 * to left here, but want to evaluate the subscripts
3121 * left-to-right to minimize surprises.)
3126 PLpgSQL_arrayelem *arrayelem = (PLpgSQL_arrayelem *) target;
3128 if (nsubscripts >= MAXDIM)
3130 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
3131 errmsg("number of array dimensions exceeds the maximum allowed, %d",
3133 subscripts[nsubscripts++] = arrayelem->subscript;
3134 target = estate->datums[arrayelem->arrayparentno];
3135 } while (target->dtype == PLPGSQL_DTYPE_ARRAYELEM);
3137 /* Fetch current value of array datum */
3138 exec_eval_datum(estate, target, InvalidOid,
3139 &arraytypeid, &oldarraydatum, &oldarrayisnull);
3141 arrayelemtypeid = get_element_type(arraytypeid);
3142 if (!OidIsValid(arrayelemtypeid))
3144 (errcode(ERRCODE_DATATYPE_MISMATCH),
3145 errmsg("subscripted object is not an array")));
3147 get_typlenbyvalalign(arrayelemtypeid,
3151 arraytyplen = get_typlen(arraytypeid);
3154 * Evaluate the subscripts, switch into left-to-right
3157 havenullsubscript = false;
3158 for (i = 0; i < nsubscripts; i++)
3163 exec_eval_integer(estate,
3164 subscripts[nsubscripts - 1 - i],
3166 havenullsubscript |= subisnull;
3170 * Skip the assignment if we have any nulls in the subscripts
3171 * or the righthand side. This is pretty bogus but it
3172 * corresponds to the current behavior of ExecEvalArrayRef().
3174 if (havenullsubscript || *isNull)
3178 * If the original array is null, cons up an empty array
3179 * so that the assignment can proceed; we'll end with a
3180 * one-element array containing just the assigned-to
3181 * subscript. This only works for varlena arrays, though;
3182 * for fixed-length array types we skip the assignment.
3183 * Again, this corresponds to the current behavior of
3184 * ExecEvalArrayRef().
3188 if (arraytyplen > 0) /* fixed-length array? */
3191 oldarrayval = construct_md_array(NULL, 0, NULL, NULL,
3198 oldarrayval = (ArrayType *) DatumGetPointer(oldarraydatum);
3200 /* Coerce source value to match array element type. */
3201 coerced_value = exec_simple_cast_value(value,
3208 * Build the modified array value.
3210 newarrayval = array_set(oldarrayval,
3221 * Assign it to the base variable.
3223 exec_assign_value(estate, target,
3224 PointerGetDatum(newarrayval),
3225 arraytypeid, isNull);
3228 * Avoid leaking the result of exec_simple_cast_value, if
3229 * it performed a conversion to a pass-by-ref type.
3231 if (!*isNull && coerced_value != value && !elemtypbyval)
3232 pfree(DatumGetPointer(coerced_value));
3235 * Avoid leaking the modified array value, too.
3242 elog(ERROR, "unrecognized dtype: %d", target->dtype);
3247 * exec_eval_datum Get current value of a PLpgSQL_datum
3249 * The type oid, value in Datum format, and null flag are returned.
3251 * If expectedtypeid isn't InvalidOid, it is checked against the actual type.
3253 * This obviously only handles scalar datums (not whole records or rows);
3254 * at present it doesn't need to handle PLpgSQL_expr datums, either.
3256 * NOTE: caller must not modify the returned value, since it points right
3257 * at the stored value in the case of pass-by-reference datatypes.
3260 exec_eval_datum(PLpgSQL_execstate *estate,
3261 PLpgSQL_datum *datum,
3267 switch (datum->dtype)
3269 case PLPGSQL_DTYPE_VAR:
3271 PLpgSQL_var *var = (PLpgSQL_var *) datum;
3273 *typeid = var->datatype->typoid;
3274 *value = var->value;
3275 *isnull = var->isnull;
3276 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3278 (errcode(ERRCODE_DATATYPE_MISMATCH),
3279 errmsg("type of \"%s\" does not match that when preparing the plan",
3284 case PLPGSQL_DTYPE_ROW:
3286 PLpgSQL_row *row = (PLpgSQL_row *) datum;
3289 if (!row->rowtupdesc) /* should not happen */
3290 elog(ERROR, "row variable has no tupdesc");
3291 /* Make sure we have a valid type/typmod setting */
3292 BlessTupleDesc(row->rowtupdesc);
3293 tup = make_tuple_from_row(estate, row, row->rowtupdesc);
3294 if (tup == NULL) /* should not happen */
3295 elog(ERROR, "row not compatible with its own tupdesc");
3296 *typeid = row->rowtupdesc->tdtypeid;
3297 *value = HeapTupleGetDatum(tup);
3299 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3301 (errcode(ERRCODE_DATATYPE_MISMATCH),
3302 errmsg("type of \"%s\" does not match that when preparing the plan",
3307 case PLPGSQL_DTYPE_REC:
3309 PLpgSQL_rec *rec = (PLpgSQL_rec *) datum;
3310 HeapTupleData worktup;
3312 if (!HeapTupleIsValid(rec->tup))
3314 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3315 errmsg("record \"%s\" is not assigned yet",
3317 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
3318 Assert(rec->tupdesc != NULL);
3319 /* Make sure we have a valid type/typmod setting */
3320 BlessTupleDesc(rec->tupdesc);
3323 * In a trigger, the NEW and OLD parameters are likely to
3324 * be on-disk tuples that don't have the desired Datum
3325 * fields. Copy the tuple body and insert the right
3328 heap_copytuple_with_tuple(rec->tup, &worktup);
3329 HeapTupleHeaderSetDatumLength(worktup.t_data, worktup.t_len);
3330 HeapTupleHeaderSetTypeId(worktup.t_data, rec->tupdesc->tdtypeid);
3331 HeapTupleHeaderSetTypMod(worktup.t_data, rec->tupdesc->tdtypmod);
3332 *typeid = rec->tupdesc->tdtypeid;
3333 *value = HeapTupleGetDatum(&worktup);
3335 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3337 (errcode(ERRCODE_DATATYPE_MISMATCH),
3338 errmsg("type of \"%s\" does not match that when preparing the plan",
3343 case PLPGSQL_DTYPE_RECFIELD:
3345 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) datum;
3349 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
3350 if (!HeapTupleIsValid(rec->tup))
3352 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3353 errmsg("record \"%s\" is not assigned yet",
3355 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
3356 fno = SPI_fnumber(rec->tupdesc, recfield->fieldname);
3357 if (fno == SPI_ERROR_NOATTRIBUTE)
3359 (errcode(ERRCODE_UNDEFINED_COLUMN),
3360 errmsg("record \"%s\" has no field \"%s\"",
3361 rec->refname, recfield->fieldname)));
3362 *typeid = SPI_gettypeid(rec->tupdesc, fno);
3363 *value = SPI_getbinval(rec->tup, rec->tupdesc, fno, isnull);
3364 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3366 (errcode(ERRCODE_DATATYPE_MISMATCH),
3367 errmsg("type of \"%s.%s\" does not match that when preparing the plan",
3368 rec->refname, recfield->fieldname)));
3372 case PLPGSQL_DTYPE_TRIGARG:
3374 PLpgSQL_trigarg *trigarg = (PLpgSQL_trigarg *) datum;
3378 tgargno = exec_eval_integer(estate, trigarg->argnum, isnull);
3379 if (*isnull || tgargno < 0 || tgargno >= estate->trig_nargs)
3386 *value = estate->trig_argv[tgargno];
3389 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3391 (errcode(ERRCODE_DATATYPE_MISMATCH),
3392 errmsg("type of tgargv[%d] does not match that when preparing the plan",
3398 elog(ERROR, "unrecognized dtype: %d", datum->dtype);
3403 * exec_eval_integer Evaluate an expression, coerce result to int4
3405 * Note we do not do exec_eval_cleanup here; the caller must do it at
3406 * some later point. (We do this because the caller may be holding the
3407 * results of other, pass-by-reference, expression evaluations, such as
3408 * an array value to be subscripted. Also see notes in exec_eval_simple_expr
3409 * about allocation of the parameter array.)
3413 exec_eval_integer(PLpgSQL_execstate *estate,
3420 exprdatum = exec_eval_expr(estate, expr, isNull, &exprtypeid);
3421 exprdatum = exec_simple_cast_value(exprdatum, exprtypeid,
3424 return DatumGetInt32(exprdatum);
3428 * exec_eval_boolean Evaluate an expression, coerce result to bool
3430 * Note we do not do exec_eval_cleanup here; the caller must do it at
3435 exec_eval_boolean(PLpgSQL_execstate *estate,
3442 exprdatum = exec_eval_expr(estate, expr, isNull, &exprtypeid);
3443 exprdatum = exec_simple_cast_value(exprdatum, exprtypeid,
3446 return DatumGetBool(exprdatum);
3450 * exec_eval_expr Evaluate an expression and return
3453 * NOTE: caller must do exec_eval_cleanup when done with the Datum.
3457 exec_eval_expr(PLpgSQL_execstate *estate,
3465 * If not already done create a plan for this expression
3467 if (expr->plan == NULL)
3468 exec_prepare_plan(estate, expr);
3471 * If this is a simple expression, bypass SPI and use the executor
3474 if (expr->expr_simple_expr != NULL)
3475 return exec_eval_simple_expr(estate, expr, isNull, rettype);
3477 rc = exec_run_select(estate, expr, 2, NULL);
3478 if (rc != SPI_OK_SELECT)
3480 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3481 errmsg("query \"%s\" did not return data", expr->query)));
3484 * If there are no rows selected, the result is NULL.
3486 if (estate->eval_processed == 0)
3493 * Check that the expression returned one single Datum
3495 if (estate->eval_processed > 1)
3497 (errcode(ERRCODE_CARDINALITY_VIOLATION),
3498 errmsg("query \"%s\" returned more than one row",
3500 if (estate->eval_tuptable->tupdesc->natts != 1)
3502 (errcode(ERRCODE_SYNTAX_ERROR),
3503 errmsg("query \"%s\" returned %d columns", expr->query,
3504 estate->eval_tuptable->tupdesc->natts)));
3507 * Return the result and its type
3509 *rettype = SPI_gettypeid(estate->eval_tuptable->tupdesc, 1);
3510 return SPI_getbinval(estate->eval_tuptable->vals[0],
3511 estate->eval_tuptable->tupdesc, 1, isNull);
3516 * exec_run_select Execute a select query
3520 exec_run_select(PLpgSQL_execstate *estate,
3521 PLpgSQL_expr *expr, long maxtuples, Portal *portalP)
3529 * On the first call for this expression generate the plan
3531 if (expr->plan == NULL)
3532 exec_prepare_plan(estate, expr);
3535 * Now build up the values and nulls arguments for SPI_execute_plan()
3537 values = (Datum *) palloc(expr->nparams * sizeof(Datum));
3538 nulls = (char *) palloc(expr->nparams * sizeof(char));
3540 for (i = 0; i < expr->nparams; i++)
3542 PLpgSQL_datum *datum = estate->datums[expr->params[i]];
3546 exec_eval_datum(estate, datum, expr->plan_argtypes[i],
3547 ¶mtypeid, &values[i], ¶misnull);
3555 * If a portal was requested, put the query into the portal
3557 if (portalP != NULL)
3559 *portalP = SPI_cursor_open(NULL, expr->plan, values, nulls,
3560 estate->readonly_func);
3561 if (*portalP == NULL)
3562 elog(ERROR, "could not open implicit cursor for query \"%s\": %s",
3563 expr->query, SPI_result_code_string(SPI_result));
3566 return SPI_OK_CURSOR;
3572 rc = SPI_execute_plan(expr->plan, values, nulls,
3573 estate->readonly_func, maxtuples);
3574 if (rc != SPI_OK_SELECT)
3576 (errcode(ERRCODE_SYNTAX_ERROR),
3577 errmsg("query \"%s\" is not a SELECT", expr->query)));
3579 /* Save query results for eventual cleanup */
3580 Assert(estate->eval_tuptable == NULL);
3581 estate->eval_tuptable = SPI_tuptable;
3582 estate->eval_processed = SPI_processed;
3583 estate->eval_lastoid = SPI_lastoid;
3593 * exec_eval_simple_expr - Evaluate a simple expression returning
3594 * a Datum by directly calling ExecEvalExpr().
3596 * Note: if pass-by-reference, the result is in the eval_econtext's
3597 * temporary memory context. It will be freed when exec_eval_cleanup
3602 exec_eval_simple_expr(PLpgSQL_execstate *estate,
3608 ExprContext * volatile econtext;
3609 ParamListInfo paramLI;
3611 Snapshot saveActiveSnapshot;
3614 * Pass back previously-determined result type.
3616 *rettype = expr->expr_simple_type;
3619 * Create an EState for evaluation of simple expressions, if there's
3620 * not one already in the current transaction. The EState is made a
3621 * child of TopTransactionContext so it will have the right lifespan.
3623 if (simple_eval_estate == NULL)
3625 MemoryContext oldcontext;
3627 oldcontext = MemoryContextSwitchTo(TopTransactionContext);
3628 simple_eval_estate = CreateExecutorState();
3629 MemoryContextSwitchTo(oldcontext);
3633 * Prepare the expression for execution, if it's not been done already
3634 * in the current transaction.
3636 if (expr->expr_simple_state == NULL)
3638 expr->expr_simple_state = ExecPrepareExpr(expr->expr_simple_expr,
3639 simple_eval_estate);
3640 /* Add it to list for cleanup */
3641 expr->expr_simple_next = active_simple_exprs;
3642 active_simple_exprs = expr;
3646 * Create an expression context for simple expressions, if there's not
3647 * one already in the current function call. This must be a child of
3648 * simple_eval_estate.
3650 econtext = estate->eval_econtext;
3651 if (econtext == NULL)
3653 econtext = CreateExprContext(simple_eval_estate);
3654 estate->eval_econtext = econtext;
3658 * Param list can live in econtext's temporary memory context.
3660 * XXX think about avoiding repeated palloc's for param lists? Beware
3661 * however that this routine is re-entrant: exec_eval_datum() can call
3662 * it back for subscript evaluation, and so there can be a need to
3663 * have more than one active param list.
3665 paramLI = (ParamListInfo)
3666 MemoryContextAlloc(econtext->ecxt_per_tuple_memory,
3667 (expr->nparams + 1) * sizeof(ParamListInfoData));
3670 * Put the parameter values into the parameter list entries.
3672 for (i = 0; i < expr->nparams; i++)
3674 PLpgSQL_datum *datum = estate->datums[expr->params[i]];
3676 paramLI[i].kind = PARAM_NUM;
3677 paramLI[i].id = i + 1;
3678 exec_eval_datum(estate, datum, expr->plan_argtypes[i],
3680 ¶mLI[i].value, ¶mLI[i].isnull);
3682 paramLI[i].kind = PARAM_INVALID;
3685 * Now we can safely make the econtext point to the param list.
3687 econtext->ecxt_param_list_info = paramLI;
3690 * We have to do some of the things SPI_execute_plan would do,
3691 * in particular advance the snapshot if we are in a non-read-only
3692 * function. Without this, stable functions within the expression
3693 * would fail to see updates made so far by our own function.
3696 saveActiveSnapshot = ActiveSnapshot;
3700 MemoryContext oldcontext;
3702 oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
3703 if (!estate->readonly_func)
3705 CommandCounterIncrement();
3706 ActiveSnapshot = CopySnapshot(GetTransactionSnapshot());
3710 * Finally we can call the executor to evaluate the expression
3712 retval = ExecEvalExpr(expr->expr_simple_state,
3716 MemoryContextSwitchTo(oldcontext);
3720 /* Restore global vars and propagate error */
3721 ActiveSnapshot = saveActiveSnapshot;
3726 ActiveSnapshot = saveActiveSnapshot;
3737 * exec_move_row Move one tuple's values into a record or row
3741 exec_move_row(PLpgSQL_execstate *estate,
3744 HeapTuple tup, TupleDesc tupdesc)
3747 * Record is simple - just copy the tuple and its descriptor into the
3753 * copy input first, just in case it is pointing at variable's value
3755 if (HeapTupleIsValid(tup))
3756 tup = heap_copytuple(tup);
3758 tupdesc = CreateTupleDescCopy(tupdesc);
3762 heap_freetuple(rec->tup);
3763 rec->freetup = false;
3765 if (rec->freetupdesc)
3767 FreeTupleDesc(rec->tupdesc);
3768 rec->freetupdesc = false;
3771 if (HeapTupleIsValid(tup))
3774 rec->freetup = true;
3778 /* If we have a tupdesc but no data, form an all-nulls tuple */
3781 nulls = (char *) palloc(tupdesc->natts * sizeof(char));
3782 memset(nulls, 'n', tupdesc->natts * sizeof(char));
3784 rec->tup = heap_formtuple(tupdesc, NULL, nulls);
3785 rec->freetup = true;
3794 rec->tupdesc = tupdesc;
3795 rec->freetupdesc = true;
3798 rec->tupdesc = NULL;
3804 * Row is a bit more complicated in that we assign the individual
3805 * attributes of the tuple to the variables the row points to.
3807 * NOTE: this code used to demand row->nfields == tup->t_data->t_natts,
3808 * but that's wrong. The tuple might have more fields than we
3809 * expected if it's from an inheritance-child table of the current
3810 * table, or it might have fewer if the table has had columns added by
3811 * ALTER TABLE. Ignore extra columns and assume NULL for missing
3812 * columns, the same as heap_getattr would do. We also have to skip
3813 * over dropped columns in either the source or destination.
3815 * If we have no tuple data at all, we'll assign NULL to all columns of
3824 if (HeapTupleIsValid(tup))
3825 t_natts = tup->t_data->t_natts;
3830 for (fnum = 0; fnum < row->nfields; fnum++)
3837 if (row->varnos[fnum] < 0)
3838 continue; /* skip dropped column in row struct */
3840 var = (PLpgSQL_var *) (estate->datums[row->varnos[fnum]]);
3842 while (anum < t_natts && tupdesc->attrs[anum]->attisdropped)
3843 anum++; /* skip dropped column in tuple */
3847 value = SPI_getbinval(tup, tupdesc, anum + 1, &isnull);
3848 valtype = SPI_gettypeid(tupdesc, anum + 1);
3855 valtype = InvalidOid;
3858 exec_assign_value(estate, (PLpgSQL_datum *) var,
3859 value, valtype, &isnull);
3865 elog(ERROR, "unsupported target");
3869 * make_tuple_from_row Make a tuple from the values of a row object
3871 * A NULL return indicates rowtype mismatch; caller must raise suitable error
3875 make_tuple_from_row(PLpgSQL_execstate *estate,
3879 int natts = tupdesc->natts;
3885 if (natts != row->nfields)
3888 dvalues = (Datum *) palloc0(natts * sizeof(Datum));
3889 nulls = (char *) palloc(natts * sizeof(char));
3890 MemSet(nulls, 'n', natts);
3892 for (i = 0; i < natts; i++)
3896 if (tupdesc->attrs[i]->attisdropped)
3897 continue; /* leave the column as null */
3898 if (row->varnos[i] < 0) /* should not happen */
3899 elog(ERROR, "dropped rowtype entry for non-dropped column");
3901 var = (PLpgSQL_var *) (estate->datums[row->varnos[i]]);
3902 if (var->datatype->typoid != tupdesc->attrs[i]->atttypid)
3904 dvalues[i] = var->value;
3909 tuple = heap_formtuple(tupdesc, dvalues, nulls);
3918 * convert_value_to_string Convert a non-null Datum to C string
3920 * Note: callers generally assume that the result is a palloc'd string and
3921 * should be pfree'd. This is not all that safe an assumption ...
3925 convert_value_to_string(Datum value, Oid valtype)
3930 getTypeOutputInfo(valtype, &typoutput, &typIsVarlena);
3932 return DatumGetCString(OidFunctionCall1(typoutput, value));
3936 * exec_cast_value Cast a value if required
3940 exec_cast_value(Datum value, Oid valtype,
3950 * If the type of the queries return value isn't that of the
3951 * variable, convert it.
3953 if (valtype != reqtype || reqtypmod != -1)
3957 extval = convert_value_to_string(value, valtype);
3958 value = FunctionCall3(reqinput,
3959 CStringGetDatum(extval),
3960 ObjectIdGetDatum(reqtypioparam),
3961 Int32GetDatum(reqtypmod));
3970 * exec_simple_cast_value Cast a value if required
3972 * As above, but need not supply details about target type. Note that this
3973 * is slower than exec_cast_value with cached type info, and so should be
3974 * avoided in heavily used code paths.
3978 exec_simple_cast_value(Datum value, Oid valtype,
3979 Oid reqtype, int32 reqtypmod,
3984 if (valtype != reqtype || reqtypmod != -1)
3988 FmgrInfo finfo_input;
3990 getTypeInputInfo(reqtype, &typinput, &typioparam);
3992 fmgr_info(typinput, &finfo_input);
3994 value = exec_cast_value(value,
4009 * exec_simple_check_node - Recursively check if an expression
4010 * is made only of simple things we can
4011 * hand out directly to ExecEvalExpr()
4012 * instead of calling SPI.
4016 exec_simple_check_node(Node *node)
4021 switch (nodeTag(node))
4031 ArrayRef *expr = (ArrayRef *) node;
4033 if (!exec_simple_check_node((Node *) expr->refupperindexpr))
4035 if (!exec_simple_check_node((Node *) expr->reflowerindexpr))
4037 if (!exec_simple_check_node((Node *) expr->refexpr))
4039 if (!exec_simple_check_node((Node *) expr->refassgnexpr))
4047 FuncExpr *expr = (FuncExpr *) node;
4049 if (expr->funcretset)
4051 if (!exec_simple_check_node((Node *) expr->args))
4059 OpExpr *expr = (OpExpr *) node;
4063 if (!exec_simple_check_node((Node *) expr->args))
4069 case T_DistinctExpr:
4071 DistinctExpr *expr = (DistinctExpr *) node;
4075 if (!exec_simple_check_node((Node *) expr->args))
4081 case T_ScalarArrayOpExpr:
4083 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
4085 if (!exec_simple_check_node((Node *) expr->args))
4093 BoolExpr *expr = (BoolExpr *) node;
4095 if (!exec_simple_check_node((Node *) expr->args))
4102 return exec_simple_check_node((Node *) ((FieldSelect *) node)->arg);
4106 FieldStore *expr = (FieldStore *) node;
4108 if (!exec_simple_check_node((Node *) expr->arg))
4110 if (!exec_simple_check_node((Node *) expr->newvals))
4117 return exec_simple_check_node((Node *) ((RelabelType *) node)->arg);
4119 case T_ConvertRowtypeExpr:
4120 return exec_simple_check_node((Node *) ((ConvertRowtypeExpr *) node)->arg);
4124 CaseExpr *expr = (CaseExpr *) node;
4126 if (!exec_simple_check_node((Node *) expr->arg))
4128 if (!exec_simple_check_node((Node *) expr->args))
4130 if (!exec_simple_check_node((Node *) expr->defresult))
4138 CaseWhen *when = (CaseWhen *) node;
4140 if (!exec_simple_check_node((Node *) when->expr))
4142 if (!exec_simple_check_node((Node *) when->result))
4148 case T_CaseTestExpr:
4153 ArrayExpr *expr = (ArrayExpr *) node;
4155 if (!exec_simple_check_node((Node *) expr->elements))
4163 RowExpr *expr = (RowExpr *) node;
4165 if (!exec_simple_check_node((Node *) expr->args))
4171 case T_CoalesceExpr:
4173 CoalesceExpr *expr = (CoalesceExpr *) node;
4175 if (!exec_simple_check_node((Node *) expr->args))
4183 NullIfExpr *expr = (NullIfExpr *) node;
4187 if (!exec_simple_check_node((Node *) expr->args))
4194 return exec_simple_check_node((Node *) ((NullTest *) node)->arg);
4197 return exec_simple_check_node((Node *) ((BooleanTest *) node)->arg);
4199 case T_CoerceToDomain:
4200 return exec_simple_check_node((Node *) ((CoerceToDomain *) node)->arg);
4202 case T_CoerceToDomainValue:
4207 List *expr = (List *) node;
4212 if (!exec_simple_check_node(lfirst(l)))
4226 * exec_simple_check_plan - Check if a plan is simple enough to
4227 * be evaluated by ExecEvalExpr() instead
4232 exec_simple_check_plan(PLpgSQL_expr *expr)
4234 _SPI_plan *spi_plan = (_SPI_plan *) expr->plan;
4238 expr->expr_simple_expr = NULL;
4241 * 1. We can only evaluate queries that resulted in one single
4244 if (list_length(spi_plan->ptlist) != 1)
4247 plan = (Plan *) linitial(spi_plan->ptlist);
4250 * 2. It must be a RESULT plan --> no scan's required
4252 if (plan == NULL) /* utility statement produces this */
4255 if (!IsA(plan, Result))
4259 * 3. Can't have any subplan or qual clause, either
4261 if (plan->lefttree != NULL ||
4262 plan->righttree != NULL ||
4263 plan->initPlan != NULL ||
4264 plan->qual != NULL ||
4265 ((Result *) plan)->resconstantqual != NULL)
4269 * 4. The plan must have a single attribute as result
4271 if (list_length(plan->targetlist) != 1)
4274 tle = (TargetEntry *) linitial(plan->targetlist);
4277 * 5. Check that all the nodes in the expression are non-scary.
4279 if (!exec_simple_check_node((Node *) tle->expr))
4283 * Yes - this is a simple expression. Mark it as such, and initialize
4284 * state to "not executing".
4286 expr->expr_simple_expr = tle->expr;
4287 expr->expr_simple_state = NULL;
4288 expr->expr_simple_next = NULL;
4289 /* Also stash away the expression result type */
4290 expr->expr_simple_type = exprType((Node *) tle->expr);
4294 * Check two tupledescs have matching number and types of attributes
4297 compatible_tupdesc(TupleDesc td1, TupleDesc td2)
4301 if (td1->natts != td2->natts)
4304 for (i = 0; i < td1->natts; i++)
4306 if (td1->attrs[i]->atttypid != td2->attrs[i]->atttypid)
4314 * exec_set_found Set the global found variable
4319 exec_set_found(PLpgSQL_execstate *estate, bool state)
4323 var = (PLpgSQL_var *) (estate->datums[estate->found_varno]);
4324 var->value = (Datum) state;
4325 var->isnull = false;
4329 * plpgsql_xact_cb --- post-transaction-commit-or-abort cleanup
4331 * If a simple_eval_estate was created in the current transaction,
4332 * it has to be cleaned up, and we have to mark all active PLpgSQL_expr
4333 * structs that are using it as no longer active.
4335 * XXX Do we need to do anything at subtransaction events?
4336 * Maybe subtransactions need to have their own simple_eval_estate?
4337 * It would get a lot messier, so for now let's assume we don't need that.
4340 plpgsql_xact_cb(XactEvent event, void *arg)
4343 PLpgSQL_expr *enext;
4345 /* Mark all active exprs as inactive */
4346 for (expr = active_simple_exprs; expr; expr = enext)
4348 enext = expr->expr_simple_next;
4349 expr->expr_simple_state = NULL;
4350 expr->expr_simple_next = NULL;
4352 active_simple_exprs = NULL;
4355 * If we are doing a clean transaction shutdown, free the
4356 * EState (so that any remaining resources will be released
4357 * correctly). In an abort, we expect the regular abort
4358 * recovery procedures to release everything of interest.
4360 if (event == XACT_EVENT_COMMIT && simple_eval_estate)
4361 FreeExecutorState(simple_eval_estate);
4362 simple_eval_estate = NULL;
4366 free_var(PLpgSQL_var *var)
4370 pfree(DatumGetPointer(var->value));
4371 var->freeval = false;