1 /**********************************************************************
2 * pl_exec.c - Executor for the PL/pgSQL
6 * $PostgreSQL: pgsql/src/pl/plpgsql/src/pl_exec.c,v 1.138 2005/05/06 17:24:55 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);
186 * plpgsql_exec_function Called by the call handler for
187 * function execution.
191 plpgsql_exec_function(PLpgSQL_function *func, FunctionCallInfo fcinfo)
193 PLpgSQL_execstate estate;
194 ErrorContextCallback plerrcontext;
198 * Setup the execution state
200 plpgsql_estate_setup(&estate, func, (ReturnSetInfo *) fcinfo->resultinfo);
203 * Setup error traceback support for ereport()
205 plerrcontext.callback = plpgsql_exec_error_callback;
206 plerrcontext.arg = &estate;
207 plerrcontext.previous = error_context_stack;
208 error_context_stack = &plerrcontext;
211 * Make local execution copies of all the datums
213 estate.err_text = gettext_noop("during initialization of execution state");
214 for (i = 0; i < estate.ndatums; i++)
215 estate.datums[i] = copy_plpgsql_datum(func->datums[i]);
218 * Store the actual call argument values into the appropriate variables
220 estate.err_text = gettext_noop("while storing call arguments into local variables");
221 for (i = 0; i < func->fn_nargs; i++)
223 int n = func->fn_argvarnos[i];
225 switch (estate.datums[n]->dtype)
227 case PLPGSQL_DTYPE_VAR:
229 PLpgSQL_var *var = (PLpgSQL_var *) estate.datums[n];
231 var->value = fcinfo->arg[i];
232 var->isnull = fcinfo->argnull[i];
233 var->freeval = false;
237 case PLPGSQL_DTYPE_ROW:
239 PLpgSQL_row *row = (PLpgSQL_row *) estate.datums[n];
241 if (!fcinfo->argnull[i])
247 HeapTupleData tmptup;
249 td = DatumGetHeapTupleHeader(fcinfo->arg[i]);
250 /* Extract rowtype info and find a tupdesc */
251 tupType = HeapTupleHeaderGetTypeId(td);
252 tupTypmod = HeapTupleHeaderGetTypMod(td);
253 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
254 /* Build a temporary HeapTuple control structure */
255 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
256 ItemPointerSetInvalid(&(tmptup.t_self));
257 tmptup.t_tableOid = InvalidOid;
259 exec_move_row(&estate, NULL, row, &tmptup, tupdesc);
263 /* If arg is null, treat it as an empty row */
264 exec_move_row(&estate, NULL, row, NULL, NULL);
270 elog(ERROR, "unrecognized dtype: %d", func->datums[i]->dtype);
275 * Set the magic variable FOUND to false
277 exec_set_found(&estate, false);
280 * Now call the toplevel block of statements
282 estate.err_text = NULL;
283 estate.err_stmt = (PLpgSQL_stmt *) (func->action);
284 if (exec_stmt_block(&estate, func->action) != PLPGSQL_RC_RETURN)
286 estate.err_stmt = NULL;
287 estate.err_text = NULL;
289 (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
290 errmsg("control reached end of function without RETURN")));
294 * We got a return value - process it
296 estate.err_stmt = NULL;
297 estate.err_text = gettext_noop("while casting return value to function's return type");
299 fcinfo->isnull = estate.retisnull;
303 ReturnSetInfo *rsi = estate.rsi;
305 /* Check caller can handle a set result */
306 if (!rsi || !IsA(rsi, ReturnSetInfo) ||
307 (rsi->allowedModes & SFRM_Materialize) == 0)
309 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
310 errmsg("set-valued function called in context that cannot accept a set")));
311 rsi->returnMode = SFRM_Materialize;
313 /* If we produced any tuples, send back the result */
314 if (estate.tuple_store)
316 rsi->setResult = estate.tuple_store;
317 if (estate.rettupdesc)
319 MemoryContext oldcxt;
321 oldcxt = MemoryContextSwitchTo(estate.tuple_store_cxt);
322 rsi->setDesc = CreateTupleDescCopy(estate.rettupdesc);
323 MemoryContextSwitchTo(oldcxt);
326 estate.retval = (Datum) 0;
327 fcinfo->isnull = true;
329 else if (!estate.retisnull)
331 if (estate.retistuple)
333 /* Copy tuple to upper executor memory, as a tuple Datum */
335 PointerGetDatum(SPI_returntuple((HeapTuple) (estate.retval),
340 /* Cast value to proper type */
341 estate.retval = exec_cast_value(estate.retval, estate.rettype,
343 &(func->fn_retinput),
344 func->fn_rettypioparam,
349 * If the function's return type isn't by value, copy the value
350 * into upper executor memory context.
352 if (!fcinfo->isnull && !func->fn_retbyval)
357 len = datumGetSize(estate.retval, false, func->fn_rettyplen);
358 tmp = (void *) SPI_palloc(len);
359 memcpy(tmp, DatumGetPointer(estate.retval), len);
360 estate.retval = PointerGetDatum(tmp);
365 /* Clean up any leftover temporary memory */
366 if (estate.eval_econtext != NULL)
367 FreeExprContext(estate.eval_econtext);
368 estate.eval_econtext = NULL;
369 exec_eval_cleanup(&estate);
372 * Pop the error context stack
374 error_context_stack = plerrcontext.previous;
377 * Return the function's result
379 return estate.retval;
384 * plpgsql_exec_trigger Called by the call handler for
389 plpgsql_exec_trigger(PLpgSQL_function *func,
390 TriggerData *trigdata)
392 PLpgSQL_execstate estate;
393 ErrorContextCallback plerrcontext;
396 PLpgSQL_rec *rec_new,
401 * Setup the execution state
403 plpgsql_estate_setup(&estate, func, NULL);
406 * Setup error traceback support for ereport()
408 plerrcontext.callback = plpgsql_exec_error_callback;
409 plerrcontext.arg = &estate;
410 plerrcontext.previous = error_context_stack;
411 error_context_stack = &plerrcontext;
414 * Make local execution copies of all the datums
416 estate.err_text = gettext_noop("during initialization of execution state");
417 for (i = 0; i < estate.ndatums; i++)
418 estate.datums[i] = copy_plpgsql_datum(func->datums[i]);
421 * Put the OLD and NEW tuples into record variables
423 rec_new = (PLpgSQL_rec *) (estate.datums[func->new_varno]);
424 rec_new->freetup = false;
425 rec_new->freetupdesc = false;
426 rec_old = (PLpgSQL_rec *) (estate.datums[func->old_varno]);
427 rec_old->freetup = false;
428 rec_old->freetupdesc = false;
430 if (TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
433 * Per-statement triggers don't use OLD/NEW variables
436 rec_new->tupdesc = NULL;
438 rec_old->tupdesc = NULL;
440 else if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
442 rec_new->tup = trigdata->tg_trigtuple;
443 rec_new->tupdesc = trigdata->tg_relation->rd_att;
445 rec_old->tupdesc = NULL;
447 else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
449 rec_new->tup = trigdata->tg_newtuple;
450 rec_new->tupdesc = trigdata->tg_relation->rd_att;
451 rec_old->tup = trigdata->tg_trigtuple;
452 rec_old->tupdesc = trigdata->tg_relation->rd_att;
454 else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
457 rec_new->tupdesc = NULL;
458 rec_old->tup = trigdata->tg_trigtuple;
459 rec_old->tupdesc = trigdata->tg_relation->rd_att;
462 elog(ERROR, "unrecognized trigger action: not INSERT, DELETE, or UPDATE");
465 * Assign the special tg_ variables
468 var = (PLpgSQL_var *) (estate.datums[func->tg_op_varno]);
469 if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
470 var->value = DirectFunctionCall1(textin, CStringGetDatum("INSERT"));
471 else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
472 var->value = DirectFunctionCall1(textin, CStringGetDatum("UPDATE"));
473 else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
474 var->value = DirectFunctionCall1(textin, CStringGetDatum("DELETE"));
476 elog(ERROR, "unrecognized trigger action: not INSERT, DELETE, or UPDATE");
480 var = (PLpgSQL_var *) (estate.datums[func->tg_name_varno]);
481 var->value = DirectFunctionCall1(namein,
482 CStringGetDatum(trigdata->tg_trigger->tgname));
486 var = (PLpgSQL_var *) (estate.datums[func->tg_when_varno]);
487 if (TRIGGER_FIRED_BEFORE(trigdata->tg_event))
488 var->value = DirectFunctionCall1(textin, CStringGetDatum("BEFORE"));
489 else if (TRIGGER_FIRED_AFTER(trigdata->tg_event))
490 var->value = DirectFunctionCall1(textin, CStringGetDatum("AFTER"));
492 elog(ERROR, "unrecognized trigger execution time: not BEFORE or AFTER");
496 var = (PLpgSQL_var *) (estate.datums[func->tg_level_varno]);
497 if (TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
498 var->value = DirectFunctionCall1(textin, CStringGetDatum("ROW"));
499 else if (TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
500 var->value = DirectFunctionCall1(textin, CStringGetDatum("STATEMENT"));
502 elog(ERROR, "unrecognized trigger event type: not ROW or STATEMENT");
506 var = (PLpgSQL_var *) (estate.datums[func->tg_relid_varno]);
507 var->value = ObjectIdGetDatum(trigdata->tg_relation->rd_id);
509 var->freeval = false;
511 var = (PLpgSQL_var *) (estate.datums[func->tg_relname_varno]);
512 var->value = DirectFunctionCall1(namein,
513 CStringGetDatum(RelationGetRelationName(trigdata->tg_relation)));
517 var = (PLpgSQL_var *) (estate.datums[func->tg_nargs_varno]);
518 var->value = Int16GetDatum(trigdata->tg_trigger->tgnargs);
520 var->freeval = false;
523 * Store the trigger argument values into the special execution
526 estate.err_text = gettext_noop("while storing call arguments into local variables");
527 estate.trig_nargs = trigdata->tg_trigger->tgnargs;
528 if (estate.trig_nargs == 0)
529 estate.trig_argv = NULL;
532 estate.trig_argv = palloc(sizeof(Datum) * estate.trig_nargs);
533 for (i = 0; i < trigdata->tg_trigger->tgnargs; i++)
534 estate.trig_argv[i] = DirectFunctionCall1(textin,
535 CStringGetDatum(trigdata->tg_trigger->tgargs[i]));
539 * Set the magic variable FOUND to false
541 exec_set_found(&estate, false);
544 * Now call the toplevel block of statements
546 estate.err_text = NULL;
547 estate.err_stmt = (PLpgSQL_stmt *) (func->action);
548 if (exec_stmt_block(&estate, func->action) != PLPGSQL_RC_RETURN)
550 estate.err_stmt = NULL;
551 estate.err_text = NULL;
553 (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
554 errmsg("control reached end of trigger procedure without RETURN")));
559 (errcode(ERRCODE_DATATYPE_MISMATCH),
560 errmsg("trigger procedure cannot return a set")));
563 * Check that the returned tuple structure has the same attributes,
564 * the relation that fired the trigger has. A per-statement trigger
565 * always needs to return NULL, so we ignore any return value the
566 * function itself produces (XXX: is this a good idea?)
568 * XXX This way it is possible, that the trigger returns a tuple where
569 * attributes don't have the correct atttypmod's length. It's up to
570 * the trigger's programmer to ensure that this doesn't happen. Jan
572 if (estate.retisnull || TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
576 if (!compatible_tupdesc(estate.rettupdesc,
577 trigdata->tg_relation->rd_att))
579 (errcode(ERRCODE_DATATYPE_MISMATCH),
580 errmsg("returned tuple structure does not match table of trigger event")));
581 /* Copy tuple to upper executor memory */
582 rettup = SPI_copytuple((HeapTuple) (estate.retval));
585 /* Clean up any leftover temporary memory */
586 if (estate.eval_econtext != NULL)
587 FreeExprContext(estate.eval_econtext);
588 estate.eval_econtext = NULL;
589 exec_eval_cleanup(&estate);
592 * Pop the error context stack
594 error_context_stack = plerrcontext.previous;
597 * Return the triggers result
604 * error context callback to let us supply a call-stack traceback
607 plpgsql_exec_error_callback(void *arg)
609 PLpgSQL_execstate *estate = (PLpgSQL_execstate *) arg;
611 /* safety check, shouldn't happen */
612 if (estate->err_func == NULL)
615 /* if we are doing RAISE, don't report its location */
616 if (estate->err_text == raise_skip_msg)
619 if (estate->err_stmt != NULL)
621 /* translator: last %s is a plpgsql statement type name */
622 errcontext("PL/pgSQL function \"%s\" line %d at %s",
623 estate->err_func->fn_name,
624 estate->err_stmt->lineno,
625 plpgsql_stmt_typename(estate->err_stmt));
627 else if (estate->err_text != NULL)
630 * We don't expend the cycles to run gettext() on err_text unless
631 * we actually need it. Therefore, places that set up err_text
632 * should use gettext_noop() to ensure the strings get recorded in
633 * the message dictionary.
637 * translator: last %s is a phrase such as "while storing call
638 * arguments into local variables"
640 errcontext("PL/pgSQL function \"%s\" %s",
641 estate->err_func->fn_name,
642 gettext(estate->err_text));
645 errcontext("PL/pgSQL function \"%s\"",
646 estate->err_func->fn_name);
651 * Support function for initializing local execution variables
654 static PLpgSQL_datum *
655 copy_plpgsql_datum(PLpgSQL_datum *datum)
657 PLpgSQL_datum *result;
659 switch (datum->dtype)
661 case PLPGSQL_DTYPE_VAR:
663 PLpgSQL_var *new = palloc(sizeof(PLpgSQL_var));
665 memcpy(new, datum, sizeof(PLpgSQL_var));
666 /* Ensure the value is null (possibly not needed?) */
669 new->freeval = false;
671 result = (PLpgSQL_datum *) new;
675 case PLPGSQL_DTYPE_REC:
677 PLpgSQL_rec *new = palloc(sizeof(PLpgSQL_rec));
679 memcpy(new, datum, sizeof(PLpgSQL_rec));
680 /* Ensure the value is null (possibly not needed?) */
683 new->freetup = false;
684 new->freetupdesc = false;
686 result = (PLpgSQL_datum *) new;
690 case PLPGSQL_DTYPE_ROW:
691 case PLPGSQL_DTYPE_RECFIELD:
692 case PLPGSQL_DTYPE_ARRAYELEM:
693 case PLPGSQL_DTYPE_TRIGARG:
695 * These datum records are read-only at runtime, so no need
702 elog(ERROR, "unrecognized dtype: %d", datum->dtype);
703 result = NULL; /* keep compiler quiet */
712 exception_matches_conditions(ErrorData *edata, PLpgSQL_condition *cond)
714 for (; cond != NULL; cond = cond->next)
716 int sqlerrstate = cond->sqlerrstate;
719 * OTHERS matches everything *except* query-canceled; if you're
720 * foolish enough, you can match that explicitly.
722 if (sqlerrstate == 0)
724 if (edata->sqlerrcode != ERRCODE_QUERY_CANCELED)
728 else if (edata->sqlerrcode == sqlerrstate)
730 /* Category match? */
731 else if (ERRCODE_IS_CATEGORY(sqlerrstate) &&
732 ERRCODE_TO_CATEGORY(edata->sqlerrcode) == sqlerrstate)
740 * exec_stmt_block Execute a block of statements
744 exec_stmt_block(PLpgSQL_execstate *estate, PLpgSQL_stmt_block *block)
746 volatile int rc = -1;
751 * First initialize all variables declared in this block
753 for (i = 0; i < block->n_initvars; i++)
755 n = block->initvarnos[i];
757 switch (estate->datums[n]->dtype)
759 case PLPGSQL_DTYPE_VAR:
761 PLpgSQL_var *var = (PLpgSQL_var *) (estate->datums[n]);
765 pfree((void *) (var->value));
766 var->freeval = false;
769 if (!var->isconst || var->isnull)
771 if (var->default_val == NULL)
773 var->value = (Datum) 0;
777 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
778 errmsg("variable \"%s\" declared NOT NULL cannot default to NULL",
783 exec_assign_expr(estate, (PLpgSQL_datum *) var,
790 case PLPGSQL_DTYPE_REC:
792 PLpgSQL_rec *rec = (PLpgSQL_rec *) (estate->datums[n]);
796 heap_freetuple(rec->tup);
797 FreeTupleDesc(rec->tupdesc);
798 rec->freetup = false;
806 case PLPGSQL_DTYPE_RECFIELD:
807 case PLPGSQL_DTYPE_ARRAYELEM:
811 elog(ERROR, "unrecognized dtype: %d",
812 estate->datums[n]->dtype);
816 if (block->exceptions)
819 * Execute the statements in the block's body inside a
822 MemoryContext oldcontext = CurrentMemoryContext;
823 ResourceOwner oldowner = CurrentResourceOwner;
825 BeginInternalSubTransaction(NULL);
826 /* Want to run statements inside function's memory context */
827 MemoryContextSwitchTo(oldcontext);
831 rc = exec_stmts(estate, block->body);
833 /* Commit the inner transaction, return to outer xact context */
834 ReleaseCurrentSubTransaction();
835 MemoryContextSwitchTo(oldcontext);
836 CurrentResourceOwner = oldowner;
839 * AtEOSubXact_SPI() should not have popped any SPI context,
840 * but just in case it did, make sure we remain connected.
842 SPI_restore_connection();
849 /* Save error info */
850 MemoryContextSwitchTo(oldcontext);
851 edata = CopyErrorData();
854 /* Abort the inner transaction */
855 RollbackAndReleaseCurrentSubTransaction();
856 MemoryContextSwitchTo(oldcontext);
857 CurrentResourceOwner = oldowner;
860 * If AtEOSubXact_SPI() popped any SPI context of the subxact,
861 * it will have left us in a disconnected state. We need this
862 * hack to return to connected state.
864 SPI_restore_connection();
866 /* Look for a matching exception handler */
867 foreach (e, block->exceptions)
869 PLpgSQL_exception *exception = (PLpgSQL_exception *) lfirst(e);
871 if (exception_matches_conditions(edata, exception->conditions))
873 rc = exec_stmts(estate, exception->action);
878 /* If no match found, re-throw the error */
882 FreeErrorData(edata);
889 * Just execute the statements in the block's body
891 rc = exec_stmts(estate, block->body);
895 * Handle the return code.
900 return PLPGSQL_RC_OK;
902 case PLPGSQL_RC_EXIT:
903 if (estate->exitlabel == NULL)
904 return PLPGSQL_RC_OK;
905 if (block->label == NULL)
906 return PLPGSQL_RC_EXIT;
907 if (strcmp(block->label, estate->exitlabel))
908 return PLPGSQL_RC_EXIT;
909 estate->exitlabel = NULL;
910 return PLPGSQL_RC_OK;
912 case PLPGSQL_RC_RETURN:
913 return PLPGSQL_RC_RETURN;
916 elog(ERROR, "unrecognized rc: %d", rc);
919 return PLPGSQL_RC_OK;
924 * exec_stmts Iterate over a list of statements
925 * as long as their return code is OK
929 exec_stmts(PLpgSQL_execstate *estate, List *stmts)
935 PLpgSQL_stmt *stmt = (PLpgSQL_stmt *) lfirst(s);
936 int rc = exec_stmt(estate, stmt);
937 if (rc != PLPGSQL_RC_OK)
941 return PLPGSQL_RC_OK;
946 * exec_stmt Distribute one statement to the statements
947 * type specific execution function.
951 exec_stmt(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
953 PLpgSQL_stmt *save_estmt;
956 save_estmt = estate->err_stmt;
957 estate->err_stmt = stmt;
959 CHECK_FOR_INTERRUPTS();
961 switch (stmt->cmd_type)
963 case PLPGSQL_STMT_BLOCK:
964 rc = exec_stmt_block(estate, (PLpgSQL_stmt_block *) stmt);
967 case PLPGSQL_STMT_ASSIGN:
968 rc = exec_stmt_assign(estate, (PLpgSQL_stmt_assign *) stmt);
971 case PLPGSQL_STMT_PERFORM:
972 rc = exec_stmt_perform(estate, (PLpgSQL_stmt_perform *) stmt);
975 case PLPGSQL_STMT_GETDIAG:
976 rc = exec_stmt_getdiag(estate, (PLpgSQL_stmt_getdiag *) stmt);
979 case PLPGSQL_STMT_IF:
980 rc = exec_stmt_if(estate, (PLpgSQL_stmt_if *) stmt);
983 case PLPGSQL_STMT_LOOP:
984 rc = exec_stmt_loop(estate, (PLpgSQL_stmt_loop *) stmt);
987 case PLPGSQL_STMT_WHILE:
988 rc = exec_stmt_while(estate, (PLpgSQL_stmt_while *) stmt);
991 case PLPGSQL_STMT_FORI:
992 rc = exec_stmt_fori(estate, (PLpgSQL_stmt_fori *) stmt);
995 case PLPGSQL_STMT_FORS:
996 rc = exec_stmt_fors(estate, (PLpgSQL_stmt_fors *) stmt);
999 case PLPGSQL_STMT_SELECT:
1000 rc = exec_stmt_select(estate, (PLpgSQL_stmt_select *) stmt);
1003 case PLPGSQL_STMT_EXIT:
1004 rc = exec_stmt_exit(estate, (PLpgSQL_stmt_exit *) stmt);
1007 case PLPGSQL_STMT_RETURN:
1008 rc = exec_stmt_return(estate, (PLpgSQL_stmt_return *) stmt);
1011 case PLPGSQL_STMT_RETURN_NEXT:
1012 rc = exec_stmt_return_next(estate, (PLpgSQL_stmt_return_next *) stmt);
1015 case PLPGSQL_STMT_RAISE:
1016 rc = exec_stmt_raise(estate, (PLpgSQL_stmt_raise *) stmt);
1019 case PLPGSQL_STMT_EXECSQL:
1020 rc = exec_stmt_execsql(estate, (PLpgSQL_stmt_execsql *) stmt);
1023 case PLPGSQL_STMT_DYNEXECUTE:
1024 rc = exec_stmt_dynexecute(estate, (PLpgSQL_stmt_dynexecute *) stmt);
1027 case PLPGSQL_STMT_DYNFORS:
1028 rc = exec_stmt_dynfors(estate, (PLpgSQL_stmt_dynfors *) stmt);
1031 case PLPGSQL_STMT_OPEN:
1032 rc = exec_stmt_open(estate, (PLpgSQL_stmt_open *) stmt);
1035 case PLPGSQL_STMT_FETCH:
1036 rc = exec_stmt_fetch(estate, (PLpgSQL_stmt_fetch *) stmt);
1039 case PLPGSQL_STMT_CLOSE:
1040 rc = exec_stmt_close(estate, (PLpgSQL_stmt_close *) stmt);
1044 estate->err_stmt = save_estmt;
1045 elog(ERROR, "unrecognized cmdtype: %d", stmt->cmd_type);
1048 estate->err_stmt = save_estmt;
1055 * exec_stmt_assign Evaluate an expression and
1056 * put the result into a variable.
1060 exec_stmt_assign(PLpgSQL_execstate *estate, PLpgSQL_stmt_assign *stmt)
1062 Assert(stmt->varno >= 0);
1064 exec_assign_expr(estate, estate->datums[stmt->varno], stmt->expr);
1066 return PLPGSQL_RC_OK;
1070 * exec_stmt_perform Evaluate query and discard result (but set
1071 * FOUND depending on whether at least one row
1076 exec_stmt_perform(PLpgSQL_execstate *estate, PLpgSQL_stmt_perform *stmt)
1078 PLpgSQL_expr *expr = stmt->expr;
1082 * If not already done create a plan for this expression
1084 if (expr->plan == NULL)
1085 exec_prepare_plan(estate, expr);
1087 rc = exec_run_select(estate, expr, 0, NULL);
1088 if (rc != SPI_OK_SELECT)
1090 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1091 errmsg("query \"%s\" did not return data", expr->query)));
1093 exec_set_found(estate, (estate->eval_processed != 0));
1095 exec_eval_cleanup(estate);
1097 return PLPGSQL_RC_OK;
1101 * exec_stmt_getdiag Put internal PG information into
1102 * specified variables.
1106 exec_stmt_getdiag(PLpgSQL_execstate *estate, PLpgSQL_stmt_getdiag *stmt)
1110 foreach (lc, stmt->diag_items)
1112 PLpgSQL_diag_item *diag_item = (PLpgSQL_diag_item *) lfirst(lc);
1114 bool isnull = false;
1116 if (diag_item->target <= 0)
1119 var = estate->datums[diag_item->target];
1124 switch (diag_item->kind)
1126 case PLPGSQL_GETDIAG_ROW_COUNT:
1128 exec_assign_value(estate, var,
1129 UInt32GetDatum(estate->eval_processed),
1133 case PLPGSQL_GETDIAG_RESULT_OID:
1135 exec_assign_value(estate, var,
1136 ObjectIdGetDatum(estate->eval_lastoid),
1141 elog(ERROR, "unrecognized attribute request: %d",
1146 return PLPGSQL_RC_OK;
1150 * exec_stmt_if Evaluate a bool expression and
1151 * execute the true or false body
1156 exec_stmt_if(PLpgSQL_execstate *estate, PLpgSQL_stmt_if *stmt)
1159 bool isnull = false;
1161 value = exec_eval_boolean(estate, stmt->cond, &isnull);
1162 exec_eval_cleanup(estate);
1164 if (!isnull && value)
1166 if (stmt->true_body != NIL)
1167 return exec_stmts(estate, stmt->true_body);
1171 if (stmt->false_body != NIL)
1172 return exec_stmts(estate, stmt->false_body);
1175 return PLPGSQL_RC_OK;
1180 * exec_stmt_loop Loop over statements until
1185 exec_stmt_loop(PLpgSQL_execstate *estate, PLpgSQL_stmt_loop *stmt)
1191 rc = exec_stmts(estate, stmt->body);
1198 case PLPGSQL_RC_EXIT:
1199 if (estate->exitlabel == NULL)
1200 return PLPGSQL_RC_OK;
1201 if (stmt->label == NULL)
1202 return PLPGSQL_RC_EXIT;
1203 if (strcmp(stmt->label, estate->exitlabel))
1204 return PLPGSQL_RC_EXIT;
1205 estate->exitlabel = NULL;
1206 return PLPGSQL_RC_OK;
1208 case PLPGSQL_RC_RETURN:
1209 return PLPGSQL_RC_RETURN;
1212 elog(ERROR, "unrecognized rc: %d", rc);
1216 return PLPGSQL_RC_OK;
1221 * exec_stmt_while Loop over statements as long
1222 * as an expression evaluates to
1223 * true or an exit occurs.
1227 exec_stmt_while(PLpgSQL_execstate *estate, PLpgSQL_stmt_while *stmt)
1230 bool isnull = false;
1235 value = exec_eval_boolean(estate, stmt->cond, &isnull);
1236 exec_eval_cleanup(estate);
1238 if (isnull || !value)
1241 rc = exec_stmts(estate, stmt->body);
1248 case PLPGSQL_RC_EXIT:
1249 if (estate->exitlabel == NULL)
1250 return PLPGSQL_RC_OK;
1251 if (stmt->label == NULL)
1252 return PLPGSQL_RC_EXIT;
1253 if (strcmp(stmt->label, estate->exitlabel))
1254 return PLPGSQL_RC_EXIT;
1255 estate->exitlabel = NULL;
1256 return PLPGSQL_RC_OK;
1258 case PLPGSQL_RC_RETURN:
1259 return PLPGSQL_RC_RETURN;
1262 elog(ERROR, "unrecognized rc: %d", rc);
1266 return PLPGSQL_RC_OK;
1271 * exec_stmt_fori Iterate an integer variable
1272 * from a lower to an upper value.
1273 * Loop can be left with exit.
1277 exec_stmt_fori(PLpgSQL_execstate *estate, PLpgSQL_stmt_fori *stmt)
1282 bool isnull = false;
1284 int rc = PLPGSQL_RC_OK;
1286 var = (PLpgSQL_var *) (estate->datums[stmt->var->varno]);
1289 * Get the value of the lower bound into the loop var
1291 value = exec_eval_expr(estate, stmt->lower, &isnull, &valtype);
1292 value = exec_cast_value(value, valtype, var->datatype->typoid,
1293 &(var->datatype->typinput),
1294 var->datatype->typioparam,
1295 var->datatype->atttypmod, &isnull);
1298 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1299 errmsg("lower bound of FOR loop cannot be NULL")));
1301 var->isnull = false;
1302 exec_eval_cleanup(estate);
1305 * Get the value of the upper bound
1307 value = exec_eval_expr(estate, stmt->upper, &isnull, &valtype);
1308 value = exec_cast_value(value, valtype, var->datatype->typoid,
1309 &(var->datatype->typinput),
1310 var->datatype->typioparam,
1311 var->datatype->atttypmod, &isnull);
1314 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1315 errmsg("upper bound of FOR loop cannot be NULL")));
1316 exec_eval_cleanup(estate);
1328 if ((int4) (var->value) < (int4) value)
1333 if ((int4) (var->value) > (int4) value)
1337 found = true; /* looped at least once */
1340 * Execute the statements
1342 rc = exec_stmts(estate, stmt->body);
1344 if (rc == PLPGSQL_RC_RETURN)
1345 break; /* return from function */
1346 else if (rc == PLPGSQL_RC_EXIT)
1348 if (estate->exitlabel == NULL)
1349 /* unlabelled exit, finish the current loop */
1351 else if (stmt->label != NULL &&
1352 strcmp(stmt->label, estate->exitlabel) == 0)
1354 /* labelled exit, matches the current stmt's label */
1355 estate->exitlabel = NULL;
1360 * otherwise, we processed a labelled exit that does not match
1361 * the current statement's label, if any: return RC_EXIT so
1362 * that the EXIT continues to recurse upward.
1369 * Increase/decrease loop var
1378 * Set the FOUND variable to indicate the result of executing the loop
1379 * (namely, whether we looped one or more times). This must be set
1380 * here so that it does not interfere with the value of the FOUND
1381 * variable inside the loop processing itself.
1383 exec_set_found(estate, found);
1390 * exec_stmt_fors Execute a query, assign each
1391 * tuple to a record or row and
1392 * execute a group of statements
1397 exec_stmt_fors(PLpgSQL_execstate *estate, PLpgSQL_stmt_fors *stmt)
1399 PLpgSQL_rec *rec = NULL;
1400 PLpgSQL_row *row = NULL;
1401 SPITupleTable *tuptab;
1404 int rc = PLPGSQL_RC_OK;
1409 * Determine if we assign to a record or a row
1411 if (stmt->rec != NULL)
1412 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
1413 else if (stmt->row != NULL)
1414 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
1416 elog(ERROR, "unsupported target");
1419 * Open the implicit cursor for the statement and fetch the initial 10
1422 exec_run_select(estate, stmt->query, 0, &portal);
1424 SPI_cursor_fetch(portal, true, 10);
1425 tuptab = SPI_tuptable;
1429 * If the query didn't return any rows, set the target to NULL and
1430 * return with FOUND = false.
1433 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
1435 found = true; /* processed at least one tuple */
1442 for (i = 0; i < n; i++)
1445 * Assign the tuple to the target
1447 exec_move_row(estate, rec, row, tuptab->vals[i], tuptab->tupdesc);
1450 * Execute the statements
1452 rc = exec_stmts(estate, stmt->body);
1454 if (rc != PLPGSQL_RC_OK)
1457 * We're aborting the loop, so cleanup and set FOUND.
1458 * (This code should match the code after the loop.)
1460 SPI_freetuptable(tuptab);
1461 SPI_cursor_close(portal);
1462 exec_set_found(estate, found);
1464 if (rc == PLPGSQL_RC_EXIT)
1466 if (estate->exitlabel == NULL)
1467 /* unlabelled exit, finish the current loop */
1469 else if (stmt->label != NULL &&
1470 strcmp(stmt->label, estate->exitlabel) == 0)
1472 /* labelled exit, matches the current stmt's label */
1473 estate->exitlabel = NULL;
1478 * otherwise, we processed a labelled exit that does
1479 * not match the current statement's label, if any:
1480 * return RC_EXIT so that the EXIT continues to
1489 SPI_freetuptable(tuptab);
1492 * Fetch the next 50 tuples
1494 SPI_cursor_fetch(portal, true, 50);
1496 tuptab = SPI_tuptable;
1500 * Release last group of tuples
1502 SPI_freetuptable(tuptab);
1505 * Close the implicit cursor
1507 SPI_cursor_close(portal);
1510 * Set the FOUND variable to indicate the result of executing the loop
1511 * (namely, whether we looped one or more times). This must be set
1512 * here so that it does not interfere with the value of the FOUND
1513 * variable inside the loop processing itself.
1515 exec_set_found(estate, found);
1522 * exec_stmt_select Run a query and assign the first
1523 * row to a record or rowtype.
1527 exec_stmt_select(PLpgSQL_execstate *estate, PLpgSQL_stmt_select *stmt)
1529 PLpgSQL_rec *rec = NULL;
1530 PLpgSQL_row *row = NULL;
1531 SPITupleTable *tuptab;
1535 * Initialize the global found variable to false
1537 exec_set_found(estate, false);
1540 * Determine if we assign to a record or a row
1542 if (stmt->rec != NULL)
1543 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
1544 else if (stmt->row != NULL)
1545 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
1547 elog(ERROR, "unsupported target");
1552 exec_run_select(estate, stmt->query, 1, NULL);
1553 tuptab = estate->eval_tuptable;
1554 n = estate->eval_processed;
1557 * If the query didn't return any row, set the target to NULL and
1562 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
1563 exec_eval_cleanup(estate);
1564 return PLPGSQL_RC_OK;
1568 * Put the result into the target and set found to true
1570 exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
1571 exec_set_found(estate, true);
1573 exec_eval_cleanup(estate);
1575 return PLPGSQL_RC_OK;
1580 * exec_stmt_exit Start exiting loop(s) or blocks
1584 exec_stmt_exit(PLpgSQL_execstate *estate, PLpgSQL_stmt_exit *stmt)
1587 * If the exit has a condition, check that it's true
1589 if (stmt->cond != NULL)
1592 bool isnull = false;
1594 value = exec_eval_boolean(estate, stmt->cond, &isnull);
1595 exec_eval_cleanup(estate);
1596 if (isnull || !value)
1597 return PLPGSQL_RC_OK;
1600 estate->exitlabel = stmt->label;
1601 return PLPGSQL_RC_EXIT;
1606 * exec_stmt_return Evaluate an expression and start
1607 * returning from the function.
1611 exec_stmt_return(PLpgSQL_execstate *estate, PLpgSQL_stmt_return *stmt)
1614 * If processing a set-returning PL/PgSQL function, the final RETURN
1615 * indicates that the function is finished producing tuples. The rest
1616 * of the work will be done at the top level.
1618 if (estate->retisset)
1619 return PLPGSQL_RC_RETURN;
1621 /* initialize for null result (possibly a tuple) */
1622 estate->retval = (Datum) 0;
1623 estate->rettupdesc = NULL;
1624 estate->retisnull = true;
1626 if (stmt->retvarno >= 0)
1628 PLpgSQL_datum *retvar = estate->datums[stmt->retvarno];
1630 switch (retvar->dtype)
1632 case PLPGSQL_DTYPE_VAR:
1634 PLpgSQL_var *var = (PLpgSQL_var *) retvar;
1636 estate->retval = var->value;
1637 estate->retisnull = var->isnull;
1638 estate->rettype = var->datatype->typoid;
1642 case PLPGSQL_DTYPE_REC:
1644 PLpgSQL_rec *rec = (PLpgSQL_rec *) retvar;
1646 if (HeapTupleIsValid(rec->tup))
1648 estate->retval = (Datum) rec->tup;
1649 estate->rettupdesc = rec->tupdesc;
1650 estate->retisnull = false;
1655 case PLPGSQL_DTYPE_ROW:
1657 PLpgSQL_row *row = (PLpgSQL_row *) retvar;
1659 Assert(row->rowtupdesc);
1660 estate->retval = (Datum) make_tuple_from_row(estate, row,
1662 if (estate->retval == (Datum) NULL) /* should not happen */
1663 elog(ERROR, "row not compatible with its own tupdesc");
1664 estate->rettupdesc = row->rowtupdesc;
1665 estate->retisnull = false;
1670 elog(ERROR, "unrecognized dtype: %d", retvar->dtype);
1673 return PLPGSQL_RC_RETURN;
1676 if (stmt->expr != NULL)
1678 if (estate->retistuple)
1680 exec_run_select(estate, stmt->expr, 1, NULL);
1681 if (estate->eval_processed > 0)
1683 estate->retval = (Datum) estate->eval_tuptable->vals[0];
1684 estate->rettupdesc = estate->eval_tuptable->tupdesc;
1685 estate->retisnull = false;
1690 /* Normal case for scalar results */
1691 estate->retval = exec_eval_expr(estate, stmt->expr,
1692 &(estate->retisnull),
1693 &(estate->rettype));
1696 return PLPGSQL_RC_RETURN;
1700 * Special hack for function returning VOID: instead of NULL, return a
1701 * non-null VOID value. This is of dubious importance but is kept for
1702 * backwards compatibility. Note that the only other way to get here
1703 * is to have written "RETURN NULL" in a function returning tuple.
1705 if (estate->fn_rettype == VOIDOID)
1707 estate->retval = (Datum) 0;
1708 estate->retisnull = false;
1709 estate->rettype = VOIDOID;
1712 return PLPGSQL_RC_RETURN;
1716 * exec_stmt_return_next Evaluate an expression and add it to the
1717 * list of tuples returned by the current
1722 exec_stmt_return_next(PLpgSQL_execstate *estate,
1723 PLpgSQL_stmt_return_next *stmt)
1728 bool free_tuple = false;
1730 if (!estate->retisset)
1732 (errcode(ERRCODE_SYNTAX_ERROR),
1733 errmsg("cannot use RETURN NEXT in a non-SETOF function")));
1735 if (estate->tuple_store == NULL)
1736 exec_init_tuple_store(estate);
1738 /* rettupdesc will be filled by exec_init_tuple_store */
1739 tupdesc = estate->rettupdesc;
1740 natts = tupdesc->natts;
1742 if (stmt->retvarno >= 0)
1744 PLpgSQL_datum *retvar = estate->datums[stmt->retvarno];
1746 switch (retvar->dtype)
1748 case PLPGSQL_DTYPE_VAR:
1750 PLpgSQL_var *var = (PLpgSQL_var *) retvar;
1751 Datum retval = var->value;
1752 bool isNull = var->isnull;
1756 (errcode(ERRCODE_DATATYPE_MISMATCH),
1757 errmsg("wrong result type supplied in RETURN NEXT")));
1759 /* coerce type if needed */
1760 retval = exec_simple_cast_value(retval,
1761 var->datatype->typoid,
1762 tupdesc->attrs[0]->atttypid,
1763 tupdesc->attrs[0]->atttypmod,
1766 tuple = heap_form_tuple(tupdesc, &retval, &isNull);
1772 case PLPGSQL_DTYPE_REC:
1774 PLpgSQL_rec *rec = (PLpgSQL_rec *) retvar;
1776 if (!HeapTupleIsValid(rec->tup))
1778 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1779 errmsg("record \"%s\" is not assigned yet",
1781 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
1782 if (!compatible_tupdesc(tupdesc, rec->tupdesc))
1784 (errcode(ERRCODE_DATATYPE_MISMATCH),
1785 errmsg("wrong record type supplied in RETURN NEXT")));
1790 case PLPGSQL_DTYPE_ROW:
1792 PLpgSQL_row *row = (PLpgSQL_row *) retvar;
1794 tuple = make_tuple_from_row(estate, row, tupdesc);
1797 (errcode(ERRCODE_DATATYPE_MISMATCH),
1798 errmsg("wrong record type supplied in RETURN NEXT")));
1804 elog(ERROR, "unrecognized dtype: %d", retvar->dtype);
1805 tuple = NULL; /* keep compiler quiet */
1809 else if (stmt->expr)
1817 (errcode(ERRCODE_DATATYPE_MISMATCH),
1818 errmsg("wrong result type supplied in RETURN NEXT")));
1820 retval = exec_eval_expr(estate,
1825 /* coerce type if needed */
1826 retval = exec_simple_cast_value(retval,
1828 tupdesc->attrs[0]->atttypid,
1829 tupdesc->attrs[0]->atttypmod,
1832 tuple = heap_form_tuple(tupdesc, &retval, &isNull);
1836 exec_eval_cleanup(estate);
1841 (errcode(ERRCODE_SYNTAX_ERROR),
1842 errmsg("RETURN NEXT must have a parameter")));
1843 tuple = NULL; /* keep compiler quiet */
1846 if (HeapTupleIsValid(tuple))
1848 MemoryContext oldcxt;
1850 oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
1851 tuplestore_puttuple(estate->tuple_store, tuple);
1852 MemoryContextSwitchTo(oldcxt);
1855 heap_freetuple(tuple);
1858 return PLPGSQL_RC_OK;
1862 exec_init_tuple_store(PLpgSQL_execstate *estate)
1864 ReturnSetInfo *rsi = estate->rsi;
1865 MemoryContext oldcxt;
1868 * Check caller can handle a set result in the way we want
1870 if (!rsi || !IsA(rsi, ReturnSetInfo) ||
1871 (rsi->allowedModes & SFRM_Materialize) == 0 ||
1872 rsi->expectedDesc == NULL)
1874 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1875 errmsg("set-valued function called in context that cannot accept a set")));
1877 estate->tuple_store_cxt = rsi->econtext->ecxt_per_query_memory;
1879 oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
1880 estate->tuple_store = tuplestore_begin_heap(true, false, work_mem);
1881 MemoryContextSwitchTo(oldcxt);
1883 estate->rettupdesc = rsi->expectedDesc;
1887 * exec_stmt_raise Build a message and throw it with elog()
1891 exec_stmt_raise(PLpgSQL_execstate *estate, PLpgSQL_stmt_raise *stmt)
1895 ListCell *current_param;
1897 plpgsql_dstring_init(&ds);
1898 current_param = list_head(stmt->params);
1900 for (cp = stmt->message; *cp; cp++)
1903 * Occurrences of a single % are replaced by the next parameter's
1904 * external representation. Double %'s are converted to one %.
1915 plpgsql_dstring_append_char(&ds, cp[1]);
1920 if (current_param == NULL)
1922 (errcode(ERRCODE_SYNTAX_ERROR),
1923 errmsg("too few parameters specified for RAISE")));
1925 exec_eval_datum(estate, estate->datums[lfirst_int(current_param)],
1927 ¶mtypeid, ¶mvalue, ¶misnull);
1931 extval = convert_value_to_string(paramvalue, paramtypeid);
1932 plpgsql_dstring_append(&ds, extval);
1933 current_param = lnext(current_param);
1937 plpgsql_dstring_append_char(&ds, cp[0]);
1941 * If more parameters were specified than were required to process
1942 * the format string, throw an error
1944 if (current_param != NULL)
1946 (errcode(ERRCODE_SYNTAX_ERROR),
1947 errmsg("too many parameters specified for RAISE")));
1950 * Throw the error (may or may not come back)
1952 estate->err_text = raise_skip_msg; /* suppress traceback of raise */
1954 ereport(stmt->elog_level,
1955 ((stmt->elog_level >= ERROR) ? errcode(ERRCODE_RAISE_EXCEPTION) : 0,
1956 errmsg_internal("%s", plpgsql_dstring_get(&ds))));
1958 estate->err_text = NULL; /* un-suppress... */
1960 plpgsql_dstring_free(&ds);
1962 return PLPGSQL_RC_OK;
1967 * Initialize a mostly empty execution state
1971 plpgsql_estate_setup(PLpgSQL_execstate *estate,
1972 PLpgSQL_function *func,
1975 estate->retval = (Datum) 0;
1976 estate->retisnull = true;
1977 estate->rettype = InvalidOid;
1979 estate->fn_rettype = func->fn_rettype;
1980 estate->retistuple = func->fn_retistuple;
1981 estate->retisset = func->fn_retset;
1983 estate->readonly_func = func->fn_readonly;
1985 estate->rettupdesc = NULL;
1986 estate->exitlabel = NULL;
1988 estate->tuple_store = NULL;
1989 estate->tuple_store_cxt = NULL;
1992 estate->trig_nargs = 0;
1993 estate->trig_argv = NULL;
1995 estate->found_varno = func->found_varno;
1996 estate->ndatums = func->ndatums;
1997 estate->datums = palloc(sizeof(PLpgSQL_datum *) * estate->ndatums);
1998 /* caller is expected to fill the datums array */
2000 estate->eval_tuptable = NULL;
2001 estate->eval_processed = 0;
2002 estate->eval_lastoid = InvalidOid;
2003 estate->eval_econtext = NULL;
2005 estate->err_func = func;
2006 estate->err_stmt = NULL;
2007 estate->err_text = NULL;
2011 * Release temporary memory used by expression/subselect evaluation
2013 * NB: the result of the evaluation is no longer valid after this is done,
2014 * unless it is a pass-by-value datatype.
2018 exec_eval_cleanup(PLpgSQL_execstate *estate)
2020 /* Clear result of a full SPI_execute */
2021 if (estate->eval_tuptable != NULL)
2022 SPI_freetuptable(estate->eval_tuptable);
2023 estate->eval_tuptable = NULL;
2025 /* Clear result of exec_eval_simple_expr (but keep the econtext) */
2026 if (estate->eval_econtext != NULL)
2027 ResetExprContext(estate->eval_econtext);
2032 * Generate a prepared plan
2036 exec_prepare_plan(PLpgSQL_execstate *estate,
2040 _SPI_plan *spi_plan;
2045 * We need a temporary argtypes array to load with data. (The finished
2046 * plan structure will contain a copy of it.)
2048 argtypes = (Oid *) palloc(expr->nparams * sizeof(Oid));
2050 for (i = 0; i < expr->nparams; i++)
2055 exec_eval_datum(estate, estate->datums[expr->params[i]],
2057 &argtypes[i], ¶mval, ¶misnull);
2061 * Generate and save the plan
2063 plan = SPI_prepare(expr->query, expr->nparams, argtypes);
2066 /* Some SPI errors deserve specific error messages */
2069 case SPI_ERROR_COPY:
2071 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2072 errmsg("cannot COPY to/from client in PL/pgSQL")));
2073 case SPI_ERROR_CURSOR:
2075 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2076 errmsg("cannot manipulate cursors directly in PL/pgSQL"),
2077 errhint("Use PL/pgSQL's cursor features instead.")));
2078 case SPI_ERROR_TRANSACTION:
2080 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2081 errmsg("cannot begin/end transactions in PL/pgSQL"),
2082 errhint("Use a BEGIN block with an EXCEPTION clause instead.")));
2084 elog(ERROR, "SPI_prepare failed for \"%s\": %s",
2085 expr->query, SPI_result_code_string(SPI_result));
2088 expr->plan = SPI_saveplan(plan);
2089 spi_plan = (_SPI_plan *) expr->plan;
2090 expr->plan_argtypes = spi_plan->argtypes;
2091 expr->expr_simple_expr = NULL;
2092 exec_simple_check_plan(expr);
2100 * exec_stmt_execsql Execute an SQL statement not
2101 * returning any data.
2105 exec_stmt_execsql(PLpgSQL_execstate *estate,
2106 PLpgSQL_stmt_execsql *stmt)
2112 PLpgSQL_expr *expr = stmt->sqlstmt;
2115 * On the first call for this expression generate the plan
2117 if (expr->plan == NULL)
2118 exec_prepare_plan(estate, expr);
2121 * Now build up the values and nulls arguments for SPI_execute_plan()
2123 values = (Datum *) palloc(expr->nparams * sizeof(Datum));
2124 nulls = (char *) palloc(expr->nparams * sizeof(char));
2126 for (i = 0; i < expr->nparams; i++)
2128 PLpgSQL_datum *datum = estate->datums[expr->params[i]];
2132 exec_eval_datum(estate, datum, expr->plan_argtypes[i],
2133 ¶mtypeid, &values[i], ¶misnull);
2143 rc = SPI_execute_plan(expr->plan, values, nulls,
2144 estate->readonly_func, 0);
2147 case SPI_OK_UTILITY:
2148 case SPI_OK_SELINTO:
2156 * If the INSERT, DELETE, or UPDATE query affected at least
2157 * one tuple, set the magic 'FOUND' variable to true. This
2158 * conforms with the behavior of PL/SQL.
2160 exec_set_found(estate, (SPI_processed != 0));
2165 (errcode(ERRCODE_SYNTAX_ERROR),
2166 errmsg("SELECT query has no destination for result data"),
2167 errhint("If you want to discard the results, use PERFORM instead.")));
2170 elog(ERROR, "SPI_execute_plan failed executing query \"%s\": %s",
2171 expr->query, SPI_result_code_string(rc));
2175 * Release any result tuples from SPI_execute_plan (probably shouldn't be
2178 SPI_freetuptable(SPI_tuptable);
2180 /* Save result info for GET DIAGNOSTICS */
2181 estate->eval_processed = SPI_processed;
2182 estate->eval_lastoid = SPI_lastoid;
2187 return PLPGSQL_RC_OK;
2192 * exec_stmt_dynexecute Execute a dynamic SQL query not
2193 * returning any data.
2197 exec_stmt_dynexecute(PLpgSQL_execstate *estate,
2198 PLpgSQL_stmt_dynexecute *stmt)
2201 bool isnull = false;
2207 * First we evaluate the string expression after the EXECUTE keyword.
2208 * It's result is the querystring we have to execute.
2210 query = exec_eval_expr(estate, stmt->query, &isnull, &restype);
2213 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2214 errmsg("cannot EXECUTE a null querystring")));
2216 /* Get the C-String representation */
2217 querystr = convert_value_to_string(query, restype);
2219 exec_eval_cleanup(estate);
2222 * Call SPI_execute() without preparing a saved plan. The returncode can
2223 * be any standard OK. Note that while a SELECT is allowed, its
2224 * results will be discarded.
2226 exec_res = SPI_execute(querystr, estate->readonly_func, 0);
2233 case SPI_OK_UTILITY:
2239 * Also allow a zero return, which implies the querystring
2240 * contained no commands.
2244 case SPI_OK_SELINTO:
2247 * We want to disallow SELECT INTO for now, because its
2248 * behavior is not consistent with SELECT INTO in a normal
2249 * plpgsql context. (We need to reimplement EXECUTE to parse
2250 * the string as a plpgsql command, not just feed it to
2251 * SPI_execute.) However, CREATE AS should be allowed ... and
2252 * since it produces the same parsetree as SELECT INTO,
2253 * there's no way to tell the difference except to look at the
2254 * source text. Wotta kluge!
2259 for (ptr = querystr; *ptr; ptr++)
2260 if (!isspace((unsigned char) *ptr))
2262 if (*ptr == 'S' || *ptr == 's')
2264 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2265 errmsg("EXECUTE of SELECT ... INTO is not implemented yet")));
2269 /* Some SPI errors deserve specific error messages */
2270 case SPI_ERROR_COPY:
2272 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2273 errmsg("cannot COPY to/from client in PL/pgSQL")));
2274 case SPI_ERROR_CURSOR:
2276 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2277 errmsg("cannot manipulate cursors directly in PL/pgSQL"),
2278 errhint("Use PL/pgSQL's cursor features instead.")));
2279 case SPI_ERROR_TRANSACTION:
2281 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2282 errmsg("cannot begin/end transactions in PL/pgSQL"),
2283 errhint("Use a BEGIN block with an EXCEPTION clause instead.")));
2286 elog(ERROR, "SPI_execute failed executing query \"%s\": %s",
2287 querystr, SPI_result_code_string(exec_res));
2291 /* Release any result from SPI_execute, as well as the querystring */
2292 SPI_freetuptable(SPI_tuptable);
2295 /* Save result info for GET DIAGNOSTICS */
2296 estate->eval_processed = SPI_processed;
2297 estate->eval_lastoid = SPI_lastoid;
2299 return PLPGSQL_RC_OK;
2304 * exec_stmt_dynfors Execute a dynamic query, assign each
2305 * tuple to a record or row and
2306 * execute a group of statements
2311 exec_stmt_dynfors(PLpgSQL_execstate *estate, PLpgSQL_stmt_dynfors *stmt)
2314 bool isnull = false;
2317 PLpgSQL_rec *rec = NULL;
2318 PLpgSQL_row *row = NULL;
2319 SPITupleTable *tuptab;
2320 int rc = PLPGSQL_RC_OK;
2328 * Determine if we assign to a record or a row
2330 if (stmt->rec != NULL)
2331 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
2332 else if (stmt->row != NULL)
2333 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
2335 elog(ERROR, "unsupported target");
2338 * Evaluate the string expression after the EXECUTE keyword. It's
2339 * result is the querystring we have to execute.
2341 query = exec_eval_expr(estate, stmt->query, &isnull, &restype);
2344 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2345 errmsg("cannot EXECUTE a null querystring")));
2347 /* Get the C-String representation */
2348 querystr = convert_value_to_string(query, restype);
2350 exec_eval_cleanup(estate);
2353 * Prepare a plan and open an implicit cursor for the query
2355 plan = SPI_prepare(querystr, 0, NULL);
2357 elog(ERROR, "SPI_prepare failed for \"%s\": %s",
2358 querystr, SPI_result_code_string(SPI_result));
2359 portal = SPI_cursor_open(NULL, plan, NULL, NULL,
2360 estate->readonly_func);
2362 elog(ERROR, "could not open implicit cursor for query \"%s\": %s",
2363 querystr, SPI_result_code_string(SPI_result));
2368 * Fetch the initial 10 tuples
2370 SPI_cursor_fetch(portal, true, 10);
2371 tuptab = SPI_tuptable;
2375 * If the query didn't return any rows, set the target to NULL and
2376 * return with FOUND = false.
2379 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
2381 found = true; /* processed at least one tuple */
2388 for (i = 0; i < n; i++)
2391 * Assign the tuple to the target
2393 exec_move_row(estate, rec, row, tuptab->vals[i], tuptab->tupdesc);
2396 * Execute the statements
2398 rc = exec_stmts(estate, stmt->body);
2400 if (rc != PLPGSQL_RC_OK)
2403 * We're aborting the loop, so cleanup and set FOUND.
2404 * (This code should match the code after the loop.)
2406 SPI_freetuptable(tuptab);
2407 SPI_cursor_close(portal);
2408 exec_set_found(estate, found);
2410 if (rc == PLPGSQL_RC_EXIT)
2412 if (estate->exitlabel == NULL)
2413 /* unlabelled exit, finish the current loop */
2415 else if (stmt->label != NULL &&
2416 strcmp(stmt->label, estate->exitlabel) == 0)
2418 /* labelled exit, matches the current stmt's label */
2419 estate->exitlabel = NULL;
2424 * otherwise, we processed a labelled exit that does
2425 * not match the current statement's label, if any:
2426 * return RC_EXIT so that the EXIT continues to
2435 SPI_freetuptable(tuptab);
2438 * Fetch the next 50 tuples
2440 SPI_cursor_fetch(portal, true, 50);
2442 tuptab = SPI_tuptable;
2446 * Release last group of tuples
2448 SPI_freetuptable(tuptab);
2451 * Close the implicit cursor
2453 SPI_cursor_close(portal);
2456 * Set the FOUND variable to indicate the result of executing the loop
2457 * (namely, whether we looped one or more times). This must be set
2458 * here so that it does not interfere with the value of the FOUND
2459 * variable inside the loop processing itself.
2461 exec_set_found(estate, found);
2463 return PLPGSQL_RC_OK;
2468 * exec_stmt_open Execute an OPEN cursor statement
2472 exec_stmt_open(PLpgSQL_execstate *estate, PLpgSQL_stmt_open *stmt)
2474 PLpgSQL_var *curvar = NULL;
2475 char *curname = NULL;
2476 PLpgSQL_expr *query = NULL;
2485 * Get the cursor variable and if it has an assigned name, check
2486 * that it's not in use currently.
2489 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
2490 if (!curvar->isnull)
2492 curname = DatumGetCString(DirectFunctionCall1(textout, curvar->value));
2493 if (SPI_cursor_find(curname) != NULL)
2495 (errcode(ERRCODE_DUPLICATE_CURSOR),
2496 errmsg("cursor \"%s\" already in use", curname)));
2500 * Process the OPEN according to it's type.
2503 if (stmt->query != NULL)
2506 * This is an OPEN refcursor FOR SELECT ...
2508 * We just make sure the query is planned. The real work is
2512 query = stmt->query;
2513 if (query->plan == NULL)
2514 exec_prepare_plan(estate, query);
2516 else if (stmt->dynquery != NULL)
2519 * This is an OPEN refcursor FOR EXECUTE ...
2528 * We evaluate the string expression after the
2529 * EXECUTE keyword. It's result is the querystring we have
2533 queryD = exec_eval_expr(estate, stmt->dynquery, &isnull, &restype);
2536 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2537 errmsg("cannot EXECUTE a null querystring")));
2539 /* Get the C-String representation */
2540 querystr = convert_value_to_string(queryD, restype);
2542 exec_eval_cleanup(estate);
2545 * Now we prepare a query plan for it and open a cursor
2548 curplan = SPI_prepare(querystr, 0, NULL);
2549 if (curplan == NULL)
2550 elog(ERROR, "SPI_prepare failed for \"%s\": %s",
2551 querystr, SPI_result_code_string(SPI_result));
2552 portal = SPI_cursor_open(curname, curplan, NULL, NULL,
2553 estate->readonly_func);
2555 elog(ERROR, "could not open cursor for query \"%s\": %s",
2556 querystr, SPI_result_code_string(SPI_result));
2558 SPI_freeplan(curplan);
2561 * Store the eventually assigned cursor name in the cursor variable
2564 if (curvar->freeval)
2565 pfree((void *) (curvar->value));
2567 curvar->value = DirectFunctionCall1(textin, CStringGetDatum(portal->name));
2568 curvar->isnull = false;
2569 curvar->freeval = true;
2571 return PLPGSQL_RC_OK;
2576 * This is an OPEN cursor
2578 * Note: parser should already have checked that statement supplies
2579 * args iff cursor needs them, but we check again to be safe.
2582 if (stmt->argquery != NULL)
2585 * Er - OPEN CURSOR (args). We fake a SELECT ... INTO ...
2586 * statement to evaluate the args and put 'em into the
2590 PLpgSQL_stmt_select set_args;
2592 if (curvar->cursor_explicit_argrow < 0)
2594 (errcode(ERRCODE_SYNTAX_ERROR),
2595 errmsg("arguments given for cursor without arguments")));
2597 memset(&set_args, 0, sizeof(set_args));
2598 set_args.cmd_type = PLPGSQL_STMT_SELECT;
2599 set_args.lineno = stmt->lineno;
2600 set_args.row = (PLpgSQL_row *)
2601 (estate->datums[curvar->cursor_explicit_argrow]);
2602 set_args.query = stmt->argquery;
2604 if (exec_stmt_select(estate, &set_args) != PLPGSQL_RC_OK)
2605 elog(ERROR, "open cursor failed during argument processing");
2609 if (curvar->cursor_explicit_argrow >= 0)
2611 (errcode(ERRCODE_SYNTAX_ERROR),
2612 errmsg("arguments required for cursor")));
2615 query = curvar->cursor_explicit_expr;
2616 if (query->plan == NULL)
2617 exec_prepare_plan(estate, query);
2621 * Here we go if we have a saved plan where we have to put
2622 * values into, either from an explicit cursor or from a
2623 * refcursor opened with OPEN ... FOR SELECT ...;
2626 values = (Datum *) palloc(query->nparams * sizeof(Datum));
2627 nulls = (char *) palloc(query->nparams * sizeof(char));
2629 for (i = 0; i < query->nparams; i++)
2631 PLpgSQL_datum *datum = estate->datums[query->params[i]];
2635 exec_eval_datum(estate, datum, query->plan_argtypes[i],
2636 ¶mtypeid, &values[i], ¶misnull);
2647 portal = SPI_cursor_open(curname, query->plan, values, nulls,
2648 estate->readonly_func);
2650 elog(ERROR, "could not open cursor: %s",
2651 SPI_result_code_string(SPI_result));
2659 * Store the eventually assigned portal name in the cursor variable
2662 if (curvar->freeval)
2663 pfree((void *) (curvar->value));
2665 curvar->value = DirectFunctionCall1(textin, CStringGetDatum(portal->name));
2666 curvar->isnull = false;
2667 curvar->freeval = true;
2669 return PLPGSQL_RC_OK;
2674 * exec_stmt_fetch Fetch from a cursor into a target
2678 exec_stmt_fetch(PLpgSQL_execstate *estate, PLpgSQL_stmt_fetch *stmt)
2680 PLpgSQL_var *curvar = NULL;
2681 PLpgSQL_rec *rec = NULL;
2682 PLpgSQL_row *row = NULL;
2683 SPITupleTable *tuptab;
2689 * Get the portal of the cursor by name
2692 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
2695 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2696 errmsg("cursor variable \"%s\" is NULL", curvar->refname)));
2697 curname = DatumGetCString(DirectFunctionCall1(textout, curvar->value));
2699 portal = SPI_cursor_find(curname);
2702 (errcode(ERRCODE_UNDEFINED_CURSOR),
2703 errmsg("cursor \"%s\" does not exist", curname)));
2707 * Determine if we fetch into a record or a row
2710 if (stmt->rec != NULL)
2711 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
2712 else if (stmt->row != NULL)
2713 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
2715 elog(ERROR, "unsupported target");
2718 * Fetch 1 tuple from the cursor
2721 SPI_cursor_fetch(portal, true, 1);
2722 tuptab = SPI_tuptable;
2726 * Set the target and the global FOUND variable appropriately.
2731 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
2732 exec_set_found(estate, false);
2736 exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
2737 exec_set_found(estate, true);
2740 SPI_freetuptable(tuptab);
2742 return PLPGSQL_RC_OK;
2747 * exec_stmt_close Close a cursor
2751 exec_stmt_close(PLpgSQL_execstate *estate, PLpgSQL_stmt_close *stmt)
2753 PLpgSQL_var *curvar = NULL;
2758 * Get the portal of the cursor by name
2761 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
2764 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2765 errmsg("cursor variable \"%s\" is NULL", curvar->refname)));
2766 curname = DatumGetCString(DirectFunctionCall1(textout, curvar->value));
2768 portal = SPI_cursor_find(curname);
2771 (errcode(ERRCODE_UNDEFINED_CURSOR),
2772 errmsg("cursor \"%s\" does not exist", curname)));
2779 SPI_cursor_close(portal);
2781 return PLPGSQL_RC_OK;
2786 * exec_assign_expr Put an expression's result into
2791 exec_assign_expr(PLpgSQL_execstate *estate, PLpgSQL_datum *target,
2796 bool isnull = false;
2798 value = exec_eval_expr(estate, expr, &isnull, &valtype);
2799 exec_assign_value(estate, target, value, valtype, &isnull);
2800 exec_eval_cleanup(estate);
2805 * exec_assign_value Put a value into a target field
2809 exec_assign_value(PLpgSQL_execstate *estate,
2810 PLpgSQL_datum *target,
2811 Datum value, Oid valtype, bool *isNull)
2813 switch (target->dtype)
2815 case PLPGSQL_DTYPE_VAR:
2818 * Target is a variable
2820 PLpgSQL_var *var = (PLpgSQL_var *) target;
2823 newvalue = exec_cast_value(value, valtype, var->datatype->typoid,
2824 &(var->datatype->typinput),
2825 var->datatype->typioparam,
2826 var->datatype->atttypmod,
2829 if (*isNull && var->notnull)
2831 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2832 errmsg("NULL cannot be assigned to variable \"%s\" declared NOT NULL",
2837 pfree(DatumGetPointer(var->value));
2838 var->freeval = false;
2842 * If type is by-reference, make sure we have a freshly
2843 * palloc'd copy; the originally passed value may not live
2844 * as long as the variable! But we don't need to re-copy
2845 * if exec_cast_value performed a conversion; its output
2846 * must already be palloc'd.
2848 if (!var->datatype->typbyval && !*isNull)
2850 if (newvalue == value)
2851 var->value = datumCopy(newvalue,
2853 var->datatype->typlen);
2855 var->value = newvalue;
2856 var->freeval = true;
2859 var->value = newvalue;
2860 var->isnull = *isNull;
2864 case PLPGSQL_DTYPE_ROW:
2867 * Target is a row variable
2869 PLpgSQL_row *row = (PLpgSQL_row *) target;
2871 /* Source must be of RECORD or composite type */
2872 if (!(valtype == RECORDOID ||
2873 get_typtype(valtype) == 'c'))
2875 (errcode(ERRCODE_DATATYPE_MISMATCH),
2876 errmsg("cannot assign non-composite value to a row variable")));
2879 /* If source is null, just assign nulls to the row */
2880 exec_move_row(estate, NULL, row, NULL, NULL);
2888 HeapTupleData tmptup;
2890 /* Else source is a tuple Datum, safe to do this: */
2891 td = DatumGetHeapTupleHeader(value);
2892 /* Extract rowtype info and find a tupdesc */
2893 tupType = HeapTupleHeaderGetTypeId(td);
2894 tupTypmod = HeapTupleHeaderGetTypMod(td);
2895 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
2896 /* Build a temporary HeapTuple control structure */
2897 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
2898 ItemPointerSetInvalid(&(tmptup.t_self));
2899 tmptup.t_tableOid = InvalidOid;
2901 exec_move_row(estate, NULL, row, &tmptup, tupdesc);
2906 case PLPGSQL_DTYPE_REC:
2909 * Target is a record variable
2911 PLpgSQL_rec *rec = (PLpgSQL_rec *) target;
2913 /* Source must be of RECORD or composite type */
2914 if (!(valtype == RECORDOID ||
2915 get_typtype(valtype) == 'c'))
2917 (errcode(ERRCODE_DATATYPE_MISMATCH),
2918 errmsg("cannot assign non-composite value to a record variable")));
2921 /* If source is null, just assign nulls to the record */
2922 exec_move_row(estate, rec, NULL, NULL, NULL);
2930 HeapTupleData tmptup;
2932 /* Else source is a tuple Datum, safe to do this: */
2933 td = DatumGetHeapTupleHeader(value);
2934 /* Extract rowtype info and find a tupdesc */
2935 tupType = HeapTupleHeaderGetTypeId(td);
2936 tupTypmod = HeapTupleHeaderGetTypMod(td);
2937 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
2938 /* Build a temporary HeapTuple control structure */
2939 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
2940 ItemPointerSetInvalid(&(tmptup.t_self));
2941 tmptup.t_tableOid = InvalidOid;
2943 exec_move_row(estate, rec, NULL, &tmptup, tupdesc);
2948 case PLPGSQL_DTYPE_RECFIELD:
2951 * Target is a field of a record
2953 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) target;
2966 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
2969 * Check that there is already a tuple in the record. We
2970 * need that because records don't have any predefined
2973 if (!HeapTupleIsValid(rec->tup))
2975 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2976 errmsg("record \"%s\" is not assigned yet",
2978 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
2981 * Get the number of the records field to change and the
2982 * number of attributes in the tuple.
2984 fno = SPI_fnumber(rec->tupdesc, recfield->fieldname);
2985 if (fno == SPI_ERROR_NOATTRIBUTE)
2987 (errcode(ERRCODE_UNDEFINED_COLUMN),
2988 errmsg("record \"%s\" has no field \"%s\"",
2989 rec->refname, recfield->fieldname)));
2991 natts = rec->tupdesc->natts;
2994 * Set up values/datums arrays for heap_formtuple. For
2995 * all the attributes except the one we want to replace,
2996 * use the value that's in the old tuple.
2998 values = palloc(sizeof(Datum) * natts);
2999 nulls = palloc(natts);
3001 for (i = 0; i < natts; i++)
3005 values[i] = SPI_getbinval(rec->tup, rec->tupdesc,
3014 * Now insert the new value, being careful to cast it to
3017 atttype = SPI_gettypeid(rec->tupdesc, fno + 1);
3018 atttypmod = rec->tupdesc->attrs[fno]->atttypmod;
3019 attisnull = *isNull;
3020 values[fno] = exec_simple_cast_value(value,
3031 * Avoid leaking the result of exec_simple_cast_value, if
3032 * it performed a conversion to a pass-by-ref type.
3034 if (!attisnull && values[fno] != value && !get_typbyval(atttype))
3035 mustfree = DatumGetPointer(values[fno]);
3040 * Now call heap_formtuple() to create a new tuple that
3041 * replaces the old one in the record.
3043 newtup = heap_formtuple(rec->tupdesc, values, nulls);
3046 heap_freetuple(rec->tup);
3049 rec->freetup = true;
3059 case PLPGSQL_DTYPE_ARRAYELEM:
3063 PLpgSQL_expr *subscripts[MAXDIM];
3064 int subscriptvals[MAXDIM];
3065 bool havenullsubscript,
3073 Datum oldarraydatum,
3075 ArrayType *oldarrayval;
3076 ArrayType *newarrayval;
3079 * Target is an element of an array
3081 * To handle constructs like x[1][2] := something, we have to
3082 * be prepared to deal with a chain of arrayelem datums.
3083 * Chase back to find the base array datum, and save the
3084 * subscript expressions as we go. (We are scanning right
3085 * to left here, but want to evaluate the subscripts
3086 * left-to-right to minimize surprises.)
3091 PLpgSQL_arrayelem *arrayelem = (PLpgSQL_arrayelem *) target;
3093 if (nsubscripts >= MAXDIM)
3095 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
3096 errmsg("number of array dimensions exceeds the maximum allowed, %d",
3098 subscripts[nsubscripts++] = arrayelem->subscript;
3099 target = estate->datums[arrayelem->arrayparentno];
3100 } while (target->dtype == PLPGSQL_DTYPE_ARRAYELEM);
3102 /* Fetch current value of array datum */
3103 exec_eval_datum(estate, target, InvalidOid,
3104 &arraytypeid, &oldarraydatum, &oldarrayisnull);
3106 arrayelemtypeid = get_element_type(arraytypeid);
3107 if (!OidIsValid(arrayelemtypeid))
3109 (errcode(ERRCODE_DATATYPE_MISMATCH),
3110 errmsg("subscripted object is not an array")));
3112 get_typlenbyvalalign(arrayelemtypeid,
3116 arraytyplen = get_typlen(arraytypeid);
3119 * Evaluate the subscripts, switch into left-to-right
3122 havenullsubscript = false;
3123 for (i = 0; i < nsubscripts; i++)
3128 exec_eval_integer(estate,
3129 subscripts[nsubscripts - 1 - i],
3131 havenullsubscript |= subisnull;
3135 * Skip the assignment if we have any nulls in the subscripts
3136 * or the righthand side. This is pretty bogus but it
3137 * corresponds to the current behavior of ExecEvalArrayRef().
3139 if (havenullsubscript || *isNull)
3143 * If the original array is null, cons up an empty array
3144 * so that the assignment can proceed; we'll end with a
3145 * one-element array containing just the assigned-to
3146 * subscript. This only works for varlena arrays, though;
3147 * for fixed-length array types we skip the assignment.
3148 * Again, this corresponds to the current behavior of
3149 * ExecEvalArrayRef().
3153 if (arraytyplen > 0) /* fixed-length array? */
3156 oldarrayval = construct_md_array(NULL, 0, NULL, NULL,
3163 oldarrayval = (ArrayType *) DatumGetPointer(oldarraydatum);
3165 /* Coerce source value to match array element type. */
3166 coerced_value = exec_simple_cast_value(value,
3173 * Build the modified array value.
3175 newarrayval = array_set(oldarrayval,
3186 * Assign it to the base variable.
3188 exec_assign_value(estate, target,
3189 PointerGetDatum(newarrayval),
3190 arraytypeid, isNull);
3193 * Avoid leaking the result of exec_simple_cast_value, if
3194 * it performed a conversion to a pass-by-ref type.
3196 if (!*isNull && coerced_value != value && !elemtypbyval)
3197 pfree(DatumGetPointer(coerced_value));
3200 * Avoid leaking the modified array value, too.
3207 elog(ERROR, "unrecognized dtype: %d", target->dtype);
3212 * exec_eval_datum Get current value of a PLpgSQL_datum
3214 * The type oid, value in Datum format, and null flag are returned.
3216 * If expectedtypeid isn't InvalidOid, it is checked against the actual type.
3218 * This obviously only handles scalar datums (not whole records or rows);
3219 * at present it doesn't need to handle PLpgSQL_expr datums, either.
3221 * NOTE: caller must not modify the returned value, since it points right
3222 * at the stored value in the case of pass-by-reference datatypes.
3225 exec_eval_datum(PLpgSQL_execstate *estate,
3226 PLpgSQL_datum *datum,
3232 switch (datum->dtype)
3234 case PLPGSQL_DTYPE_VAR:
3236 PLpgSQL_var *var = (PLpgSQL_var *) datum;
3238 *typeid = var->datatype->typoid;
3239 *value = var->value;
3240 *isnull = var->isnull;
3241 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3243 (errcode(ERRCODE_DATATYPE_MISMATCH),
3244 errmsg("type of \"%s\" does not match that when preparing the plan",
3249 case PLPGSQL_DTYPE_ROW:
3251 PLpgSQL_row *row = (PLpgSQL_row *) datum;
3254 if (!row->rowtupdesc) /* should not happen */
3255 elog(ERROR, "row variable has no tupdesc");
3256 /* Make sure we have a valid type/typmod setting */
3257 BlessTupleDesc(row->rowtupdesc);
3258 tup = make_tuple_from_row(estate, row, row->rowtupdesc);
3259 if (tup == NULL) /* should not happen */
3260 elog(ERROR, "row not compatible with its own tupdesc");
3261 *typeid = row->rowtupdesc->tdtypeid;
3262 *value = HeapTupleGetDatum(tup);
3264 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3266 (errcode(ERRCODE_DATATYPE_MISMATCH),
3267 errmsg("type of \"%s\" does not match that when preparing the plan",
3272 case PLPGSQL_DTYPE_REC:
3274 PLpgSQL_rec *rec = (PLpgSQL_rec *) datum;
3275 HeapTupleData worktup;
3277 if (!HeapTupleIsValid(rec->tup))
3279 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3280 errmsg("record \"%s\" is not assigned yet",
3282 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
3283 Assert(rec->tupdesc != NULL);
3284 /* Make sure we have a valid type/typmod setting */
3285 BlessTupleDesc(rec->tupdesc);
3288 * In a trigger, the NEW and OLD parameters are likely to
3289 * be on-disk tuples that don't have the desired Datum
3290 * fields. Copy the tuple body and insert the right
3293 heap_copytuple_with_tuple(rec->tup, &worktup);
3294 HeapTupleHeaderSetDatumLength(worktup.t_data, worktup.t_len);
3295 HeapTupleHeaderSetTypeId(worktup.t_data, rec->tupdesc->tdtypeid);
3296 HeapTupleHeaderSetTypMod(worktup.t_data, rec->tupdesc->tdtypmod);
3297 *typeid = rec->tupdesc->tdtypeid;
3298 *value = HeapTupleGetDatum(&worktup);
3300 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3302 (errcode(ERRCODE_DATATYPE_MISMATCH),
3303 errmsg("type of \"%s\" does not match that when preparing the plan",
3308 case PLPGSQL_DTYPE_RECFIELD:
3310 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) datum;
3314 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
3315 if (!HeapTupleIsValid(rec->tup))
3317 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3318 errmsg("record \"%s\" is not assigned yet",
3320 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
3321 fno = SPI_fnumber(rec->tupdesc, recfield->fieldname);
3322 if (fno == SPI_ERROR_NOATTRIBUTE)
3324 (errcode(ERRCODE_UNDEFINED_COLUMN),
3325 errmsg("record \"%s\" has no field \"%s\"",
3326 rec->refname, recfield->fieldname)));
3327 *typeid = SPI_gettypeid(rec->tupdesc, fno);
3328 *value = SPI_getbinval(rec->tup, rec->tupdesc, fno, isnull);
3329 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3331 (errcode(ERRCODE_DATATYPE_MISMATCH),
3332 errmsg("type of \"%s.%s\" does not match that when preparing the plan",
3333 rec->refname, recfield->fieldname)));
3337 case PLPGSQL_DTYPE_TRIGARG:
3339 PLpgSQL_trigarg *trigarg = (PLpgSQL_trigarg *) datum;
3343 tgargno = exec_eval_integer(estate, trigarg->argnum, isnull);
3344 if (*isnull || tgargno < 0 || tgargno >= estate->trig_nargs)
3351 *value = estate->trig_argv[tgargno];
3354 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3356 (errcode(ERRCODE_DATATYPE_MISMATCH),
3357 errmsg("type of tgargv[%d] does not match that when preparing the plan",
3363 elog(ERROR, "unrecognized dtype: %d", datum->dtype);
3368 * exec_eval_integer Evaluate an expression, coerce result to int4
3370 * Note we do not do exec_eval_cleanup here; the caller must do it at
3371 * some later point. (We do this because the caller may be holding the
3372 * results of other, pass-by-reference, expression evaluations, such as
3373 * an array value to be subscripted. Also see notes in exec_eval_simple_expr
3374 * about allocation of the parameter array.)
3378 exec_eval_integer(PLpgSQL_execstate *estate,
3385 exprdatum = exec_eval_expr(estate, expr, isNull, &exprtypeid);
3386 exprdatum = exec_simple_cast_value(exprdatum, exprtypeid,
3389 return DatumGetInt32(exprdatum);
3393 * exec_eval_boolean Evaluate an expression, coerce result to bool
3395 * Note we do not do exec_eval_cleanup here; the caller must do it at
3400 exec_eval_boolean(PLpgSQL_execstate *estate,
3407 exprdatum = exec_eval_expr(estate, expr, isNull, &exprtypeid);
3408 exprdatum = exec_simple_cast_value(exprdatum, exprtypeid,
3411 return DatumGetBool(exprdatum);
3415 * exec_eval_expr Evaluate an expression and return
3418 * NOTE: caller must do exec_eval_cleanup when done with the Datum.
3422 exec_eval_expr(PLpgSQL_execstate *estate,
3430 * If not already done create a plan for this expression
3432 if (expr->plan == NULL)
3433 exec_prepare_plan(estate, expr);
3436 * If this is a simple expression, bypass SPI and use the executor
3439 if (expr->expr_simple_expr != NULL)
3440 return exec_eval_simple_expr(estate, expr, isNull, rettype);
3442 rc = exec_run_select(estate, expr, 2, NULL);
3443 if (rc != SPI_OK_SELECT)
3445 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3446 errmsg("query \"%s\" did not return data", expr->query)));
3449 * If there are no rows selected, the result is NULL.
3451 if (estate->eval_processed == 0)
3458 * Check that the expression returned one single Datum
3460 if (estate->eval_processed > 1)
3462 (errcode(ERRCODE_CARDINALITY_VIOLATION),
3463 errmsg("query \"%s\" returned more than one row",
3465 if (estate->eval_tuptable->tupdesc->natts != 1)
3467 (errcode(ERRCODE_SYNTAX_ERROR),
3468 errmsg("query \"%s\" returned %d columns", expr->query,
3469 estate->eval_tuptable->tupdesc->natts)));
3472 * Return the result and its type
3474 *rettype = SPI_gettypeid(estate->eval_tuptable->tupdesc, 1);
3475 return SPI_getbinval(estate->eval_tuptable->vals[0],
3476 estate->eval_tuptable->tupdesc, 1, isNull);
3481 * exec_run_select Execute a select query
3485 exec_run_select(PLpgSQL_execstate *estate,
3486 PLpgSQL_expr *expr, long maxtuples, Portal *portalP)
3494 * On the first call for this expression generate the plan
3496 if (expr->plan == NULL)
3497 exec_prepare_plan(estate, expr);
3500 * Now build up the values and nulls arguments for SPI_execute_plan()
3502 values = (Datum *) palloc(expr->nparams * sizeof(Datum));
3503 nulls = (char *) palloc(expr->nparams * sizeof(char));
3505 for (i = 0; i < expr->nparams; i++)
3507 PLpgSQL_datum *datum = estate->datums[expr->params[i]];
3511 exec_eval_datum(estate, datum, expr->plan_argtypes[i],
3512 ¶mtypeid, &values[i], ¶misnull);
3520 * If a portal was requested, put the query into the portal
3522 if (portalP != NULL)
3524 *portalP = SPI_cursor_open(NULL, expr->plan, values, nulls,
3525 estate->readonly_func);
3526 if (*portalP == NULL)
3527 elog(ERROR, "could not open implicit cursor for query \"%s\": %s",
3528 expr->query, SPI_result_code_string(SPI_result));
3531 return SPI_OK_CURSOR;
3537 rc = SPI_execute_plan(expr->plan, values, nulls,
3538 estate->readonly_func, maxtuples);
3539 if (rc != SPI_OK_SELECT)
3541 (errcode(ERRCODE_SYNTAX_ERROR),
3542 errmsg("query \"%s\" is not a SELECT", expr->query)));
3544 /* Save query results for eventual cleanup */
3545 Assert(estate->eval_tuptable == NULL);
3546 estate->eval_tuptable = SPI_tuptable;
3547 estate->eval_processed = SPI_processed;
3548 estate->eval_lastoid = SPI_lastoid;
3558 * exec_eval_simple_expr - Evaluate a simple expression returning
3559 * a Datum by directly calling ExecEvalExpr().
3561 * Note: if pass-by-reference, the result is in the eval_econtext's
3562 * temporary memory context. It will be freed when exec_eval_cleanup
3567 exec_eval_simple_expr(PLpgSQL_execstate *estate,
3573 ExprContext * volatile econtext;
3574 ParamListInfo paramLI;
3576 Snapshot saveActiveSnapshot;
3579 * Pass back previously-determined result type.
3581 *rettype = expr->expr_simple_type;
3584 * Create an EState for evaluation of simple expressions, if there's
3585 * not one already in the current transaction. The EState is made a
3586 * child of TopTransactionContext so it will have the right lifespan.
3588 if (simple_eval_estate == NULL)
3590 MemoryContext oldcontext;
3592 oldcontext = MemoryContextSwitchTo(TopTransactionContext);
3593 simple_eval_estate = CreateExecutorState();
3594 MemoryContextSwitchTo(oldcontext);
3598 * Prepare the expression for execution, if it's not been done already
3599 * in the current transaction.
3601 if (expr->expr_simple_state == NULL)
3603 expr->expr_simple_state = ExecPrepareExpr(expr->expr_simple_expr,
3604 simple_eval_estate);
3605 /* Add it to list for cleanup */
3606 expr->expr_simple_next = active_simple_exprs;
3607 active_simple_exprs = expr;
3611 * Create an expression context for simple expressions, if there's not
3612 * one already in the current function call. This must be a child of
3613 * simple_eval_estate.
3615 econtext = estate->eval_econtext;
3616 if (econtext == NULL)
3618 econtext = CreateExprContext(simple_eval_estate);
3619 estate->eval_econtext = econtext;
3623 * Param list can live in econtext's temporary memory context.
3625 * XXX think about avoiding repeated palloc's for param lists? Beware
3626 * however that this routine is re-entrant: exec_eval_datum() can call
3627 * it back for subscript evaluation, and so there can be a need to
3628 * have more than one active param list.
3630 paramLI = (ParamListInfo)
3631 MemoryContextAlloc(econtext->ecxt_per_tuple_memory,
3632 (expr->nparams + 1) * sizeof(ParamListInfoData));
3635 * Put the parameter values into the parameter list entries.
3637 for (i = 0; i < expr->nparams; i++)
3639 PLpgSQL_datum *datum = estate->datums[expr->params[i]];
3641 paramLI[i].kind = PARAM_NUM;
3642 paramLI[i].id = i + 1;
3643 exec_eval_datum(estate, datum, expr->plan_argtypes[i],
3645 ¶mLI[i].value, ¶mLI[i].isnull);
3647 paramLI[i].kind = PARAM_INVALID;
3650 * Now we can safely make the econtext point to the param list.
3652 econtext->ecxt_param_list_info = paramLI;
3655 * We have to do some of the things SPI_execute_plan would do,
3656 * in particular advance the snapshot if we are in a non-read-only
3657 * function. Without this, stable functions within the expression
3658 * would fail to see updates made so far by our own function.
3661 saveActiveSnapshot = ActiveSnapshot;
3665 MemoryContext oldcontext;
3667 oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
3668 if (!estate->readonly_func)
3670 CommandCounterIncrement();
3671 ActiveSnapshot = CopySnapshot(GetTransactionSnapshot());
3675 * Finally we can call the executor to evaluate the expression
3677 retval = ExecEvalExpr(expr->expr_simple_state,
3681 MemoryContextSwitchTo(oldcontext);
3685 /* Restore global vars and propagate error */
3686 ActiveSnapshot = saveActiveSnapshot;
3691 ActiveSnapshot = saveActiveSnapshot;
3702 * exec_move_row Move one tuple's values into a record or row
3706 exec_move_row(PLpgSQL_execstate *estate,
3709 HeapTuple tup, TupleDesc tupdesc)
3712 * Record is simple - just copy the tuple and its descriptor into the
3719 heap_freetuple(rec->tup);
3720 rec->freetup = false;
3722 if (rec->freetupdesc)
3724 FreeTupleDesc(rec->tupdesc);
3725 rec->freetupdesc = false;
3728 if (HeapTupleIsValid(tup))
3730 rec->tup = heap_copytuple(tup);
3731 rec->freetup = true;
3735 /* If we have a tupdesc but no data, form an all-nulls tuple */
3738 nulls = (char *) palloc(tupdesc->natts * sizeof(char));
3739 memset(nulls, 'n', tupdesc->natts * sizeof(char));
3741 rec->tup = heap_formtuple(tupdesc, NULL, nulls);
3742 rec->freetup = true;
3751 rec->tupdesc = CreateTupleDescCopy(tupdesc);
3752 rec->freetupdesc = true;
3755 rec->tupdesc = NULL;
3761 * Row is a bit more complicated in that we assign the individual
3762 * attributes of the tuple to the variables the row points to.
3764 * NOTE: this code used to demand row->nfields == tup->t_data->t_natts,
3765 * but that's wrong. The tuple might have more fields than we
3766 * expected if it's from an inheritance-child table of the current
3767 * table, or it might have fewer if the table has had columns added by
3768 * ALTER TABLE. Ignore extra columns and assume NULL for missing
3769 * columns, the same as heap_getattr would do. We also have to skip
3770 * over dropped columns in either the source or destination.
3772 * If we have no tuple data at all, we'll assign NULL to all columns of
3781 if (HeapTupleIsValid(tup))
3782 t_natts = tup->t_data->t_natts;
3787 for (fnum = 0; fnum < row->nfields; fnum++)
3794 if (row->varnos[fnum] < 0)
3795 continue; /* skip dropped column in row struct */
3797 var = (PLpgSQL_var *) (estate->datums[row->varnos[fnum]]);
3799 while (anum < t_natts && tupdesc->attrs[anum]->attisdropped)
3800 anum++; /* skip dropped column in tuple */
3804 value = SPI_getbinval(tup, tupdesc, anum + 1, &isnull);
3805 valtype = SPI_gettypeid(tupdesc, anum + 1);
3812 valtype = InvalidOid;
3815 exec_assign_value(estate, (PLpgSQL_datum *) var,
3816 value, valtype, &isnull);
3822 elog(ERROR, "unsupported target");
3826 * make_tuple_from_row Make a tuple from the values of a row object
3828 * A NULL return indicates rowtype mismatch; caller must raise suitable error
3832 make_tuple_from_row(PLpgSQL_execstate *estate,
3836 int natts = tupdesc->natts;
3842 if (natts != row->nfields)
3845 dvalues = (Datum *) palloc0(natts * sizeof(Datum));
3846 nulls = (char *) palloc(natts * sizeof(char));
3847 MemSet(nulls, 'n', natts);
3849 for (i = 0; i < natts; i++)
3853 if (tupdesc->attrs[i]->attisdropped)
3854 continue; /* leave the column as null */
3855 if (row->varnos[i] < 0) /* should not happen */
3856 elog(ERROR, "dropped rowtype entry for non-dropped column");
3858 var = (PLpgSQL_var *) (estate->datums[row->varnos[i]]);
3859 if (var->datatype->typoid != tupdesc->attrs[i]->atttypid)
3861 dvalues[i] = var->value;
3866 tuple = heap_formtuple(tupdesc, dvalues, nulls);
3875 * convert_value_to_string Convert a non-null Datum to C string
3877 * Note: callers generally assume that the result is a palloc'd string and
3878 * should be pfree'd. This is not all that safe an assumption ...
3882 convert_value_to_string(Datum value, Oid valtype)
3887 getTypeOutputInfo(valtype, &typoutput, &typIsVarlena);
3889 return DatumGetCString(OidFunctionCall1(typoutput, value));
3893 * exec_cast_value Cast a value if required
3897 exec_cast_value(Datum value, Oid valtype,
3907 * If the type of the queries return value isn't that of the
3908 * variable, convert it.
3910 if (valtype != reqtype || reqtypmod != -1)
3914 extval = convert_value_to_string(value, valtype);
3915 value = FunctionCall3(reqinput,
3916 CStringGetDatum(extval),
3917 ObjectIdGetDatum(reqtypioparam),
3918 Int32GetDatum(reqtypmod));
3927 * exec_simple_cast_value Cast a value if required
3929 * As above, but need not supply details about target type. Note that this
3930 * is slower than exec_cast_value with cached type info, and so should be
3931 * avoided in heavily used code paths.
3935 exec_simple_cast_value(Datum value, Oid valtype,
3936 Oid reqtype, int32 reqtypmod,
3941 if (valtype != reqtype || reqtypmod != -1)
3945 FmgrInfo finfo_input;
3947 getTypeInputInfo(reqtype, &typinput, &typioparam);
3949 fmgr_info(typinput, &finfo_input);
3951 value = exec_cast_value(value,
3966 * exec_simple_check_node - Recursively check if an expression
3967 * is made only of simple things we can
3968 * hand out directly to ExecEvalExpr()
3969 * instead of calling SPI.
3973 exec_simple_check_node(Node *node)
3978 switch (nodeTag(node))
3988 ArrayRef *expr = (ArrayRef *) node;
3990 if (!exec_simple_check_node((Node *) expr->refupperindexpr))
3992 if (!exec_simple_check_node((Node *) expr->reflowerindexpr))
3994 if (!exec_simple_check_node((Node *) expr->refexpr))
3996 if (!exec_simple_check_node((Node *) expr->refassgnexpr))
4004 FuncExpr *expr = (FuncExpr *) node;
4006 if (expr->funcretset)
4008 if (!exec_simple_check_node((Node *) expr->args))
4016 OpExpr *expr = (OpExpr *) node;
4020 if (!exec_simple_check_node((Node *) expr->args))
4026 case T_DistinctExpr:
4028 DistinctExpr *expr = (DistinctExpr *) node;
4032 if (!exec_simple_check_node((Node *) expr->args))
4038 case T_ScalarArrayOpExpr:
4040 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
4042 if (!exec_simple_check_node((Node *) expr->args))
4050 BoolExpr *expr = (BoolExpr *) node;
4052 if (!exec_simple_check_node((Node *) expr->args))
4059 return exec_simple_check_node((Node *) ((FieldSelect *) node)->arg);
4063 FieldStore *expr = (FieldStore *) node;
4065 if (!exec_simple_check_node((Node *) expr->arg))
4067 if (!exec_simple_check_node((Node *) expr->newvals))
4074 return exec_simple_check_node((Node *) ((RelabelType *) node)->arg);
4076 case T_ConvertRowtypeExpr:
4077 return exec_simple_check_node((Node *) ((ConvertRowtypeExpr *) node)->arg);
4081 CaseExpr *expr = (CaseExpr *) node;
4083 if (!exec_simple_check_node((Node *) expr->arg))
4085 if (!exec_simple_check_node((Node *) expr->args))
4087 if (!exec_simple_check_node((Node *) expr->defresult))
4095 CaseWhen *when = (CaseWhen *) node;
4097 if (!exec_simple_check_node((Node *) when->expr))
4099 if (!exec_simple_check_node((Node *) when->result))
4105 case T_CaseTestExpr:
4110 ArrayExpr *expr = (ArrayExpr *) node;
4112 if (!exec_simple_check_node((Node *) expr->elements))
4120 RowExpr *expr = (RowExpr *) node;
4122 if (!exec_simple_check_node((Node *) expr->args))
4128 case T_CoalesceExpr:
4130 CoalesceExpr *expr = (CoalesceExpr *) node;
4132 if (!exec_simple_check_node((Node *) expr->args))
4140 NullIfExpr *expr = (NullIfExpr *) node;
4144 if (!exec_simple_check_node((Node *) expr->args))
4151 return exec_simple_check_node((Node *) ((NullTest *) node)->arg);
4154 return exec_simple_check_node((Node *) ((BooleanTest *) node)->arg);
4156 case T_CoerceToDomain:
4157 return exec_simple_check_node((Node *) ((CoerceToDomain *) node)->arg);
4159 case T_CoerceToDomainValue:
4164 List *expr = (List *) node;
4169 if (!exec_simple_check_node(lfirst(l)))
4183 * exec_simple_check_plan - Check if a plan is simple enough to
4184 * be evaluated by ExecEvalExpr() instead
4189 exec_simple_check_plan(PLpgSQL_expr *expr)
4191 _SPI_plan *spi_plan = (_SPI_plan *) expr->plan;
4195 expr->expr_simple_expr = NULL;
4198 * 1. We can only evaluate queries that resulted in one single
4201 if (list_length(spi_plan->ptlist) != 1)
4204 plan = (Plan *) linitial(spi_plan->ptlist);
4207 * 2. It must be a RESULT plan --> no scan's required
4209 if (plan == NULL) /* utility statement produces this */
4212 if (!IsA(plan, Result))
4216 * 3. Can't have any subplan or qual clause, either
4218 if (plan->lefttree != NULL ||
4219 plan->righttree != NULL ||
4220 plan->initPlan != NULL ||
4221 plan->qual != NULL ||
4222 ((Result *) plan)->resconstantqual != NULL)
4226 * 4. The plan must have a single attribute as result
4228 if (list_length(plan->targetlist) != 1)
4231 tle = (TargetEntry *) linitial(plan->targetlist);
4234 * 5. Check that all the nodes in the expression are non-scary.
4236 if (!exec_simple_check_node((Node *) tle->expr))
4240 * Yes - this is a simple expression. Mark it as such, and initialize
4241 * state to "not executing".
4243 expr->expr_simple_expr = tle->expr;
4244 expr->expr_simple_state = NULL;
4245 expr->expr_simple_next = NULL;
4246 /* Also stash away the expression result type */
4247 expr->expr_simple_type = exprType((Node *) tle->expr);
4251 * Check two tupledescs have matching number and types of attributes
4254 compatible_tupdesc(TupleDesc td1, TupleDesc td2)
4258 if (td1->natts != td2->natts)
4261 for (i = 0; i < td1->natts; i++)
4263 if (td1->attrs[i]->atttypid != td2->attrs[i]->atttypid)
4271 * exec_set_found Set the global found variable
4276 exec_set_found(PLpgSQL_execstate *estate, bool state)
4280 var = (PLpgSQL_var *) (estate->datums[estate->found_varno]);
4281 var->value = (Datum) state;
4282 var->isnull = false;
4286 * plpgsql_xact_cb --- post-transaction-commit-or-abort cleanup
4288 * If a simple_eval_estate was created in the current transaction,
4289 * it has to be cleaned up, and we have to mark all active PLpgSQL_expr
4290 * structs that are using it as no longer active.
4292 * XXX Do we need to do anything at subtransaction events?
4293 * Maybe subtransactions need to have their own simple_eval_estate?
4294 * It would get a lot messier, so for now let's assume we don't need that.
4297 plpgsql_xact_cb(XactEvent event, void *arg)
4300 PLpgSQL_expr *enext;
4302 /* Mark all active exprs as inactive */
4303 for (expr = active_simple_exprs; expr; expr = enext)
4305 enext = expr->expr_simple_next;
4306 expr->expr_simple_state = NULL;
4307 expr->expr_simple_next = NULL;
4309 active_simple_exprs = NULL;
4312 * If we are doing a clean transaction shutdown, free the
4313 * EState (so that any remaining resources will be released
4314 * correctly). In an abort, we expect the regular abort
4315 * recovery procedures to release everything of interest.
4317 if (event == XACT_EVENT_COMMIT && simple_eval_estate)
4318 FreeExecutorState(simple_eval_estate);
4319 simple_eval_estate = NULL;