1 /*-------------------------------------------------------------------------
3 * pl_exec.c - Executor for the PL/pgSQL
6 * Portions Copyright (c) 1996-2006, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $PostgreSQL: pgsql/src/pl/plpgsql/src/pl_exec.c,v 1.164 2006/04/22 01:26:01 tgl Exp $
13 *-------------------------------------------------------------------------
21 #include "access/heapam.h"
22 #include "catalog/pg_proc.h"
23 #include "catalog/pg_type.h"
24 #include "executor/spi_priv.h"
26 #include "optimizer/clauses.h"
27 #include "parser/parse_expr.h"
28 #include "tcop/tcopprot.h"
29 #include "utils/array.h"
30 #include "utils/builtins.h"
31 #include "utils/lsyscache.h"
32 #include "utils/memutils.h"
33 #include "utils/typcache.h"
36 static const char *const raise_skip_msg = "RAISE";
40 * All plpgsql function executions within a single transaction share
41 * the same executor EState for evaluating "simple" expressions. Each
42 * function call creates its own "eval_econtext" ExprContext within this
43 * estate. We destroy the estate at transaction shutdown to ensure there
44 * is no permanent leakage of memory (especially for xact abort case).
46 static EState *simple_eval_estate = NULL;
48 /************************************************************
49 * Local function forward declarations
50 ************************************************************/
51 static void plpgsql_exec_error_callback(void *arg);
52 static PLpgSQL_datum *copy_plpgsql_datum(PLpgSQL_datum *datum);
54 static int exec_stmt_block(PLpgSQL_execstate *estate,
55 PLpgSQL_stmt_block *block);
56 static int exec_stmts(PLpgSQL_execstate *estate,
58 static int exec_stmt(PLpgSQL_execstate *estate,
60 static int exec_stmt_assign(PLpgSQL_execstate *estate,
61 PLpgSQL_stmt_assign *stmt);
62 static int exec_stmt_perform(PLpgSQL_execstate *estate,
63 PLpgSQL_stmt_perform *stmt);
64 static int exec_stmt_getdiag(PLpgSQL_execstate *estate,
65 PLpgSQL_stmt_getdiag *stmt);
66 static int exec_stmt_if(PLpgSQL_execstate *estate,
67 PLpgSQL_stmt_if *stmt);
68 static int exec_stmt_loop(PLpgSQL_execstate *estate,
69 PLpgSQL_stmt_loop *stmt);
70 static int exec_stmt_while(PLpgSQL_execstate *estate,
71 PLpgSQL_stmt_while *stmt);
72 static int exec_stmt_fori(PLpgSQL_execstate *estate,
73 PLpgSQL_stmt_fori *stmt);
74 static int exec_stmt_fors(PLpgSQL_execstate *estate,
75 PLpgSQL_stmt_fors *stmt);
76 static int exec_stmt_select(PLpgSQL_execstate *estate,
77 PLpgSQL_stmt_select *stmt);
78 static int exec_stmt_open(PLpgSQL_execstate *estate,
79 PLpgSQL_stmt_open *stmt);
80 static int exec_stmt_fetch(PLpgSQL_execstate *estate,
81 PLpgSQL_stmt_fetch *stmt);
82 static int exec_stmt_close(PLpgSQL_execstate *estate,
83 PLpgSQL_stmt_close *stmt);
84 static int exec_stmt_exit(PLpgSQL_execstate *estate,
85 PLpgSQL_stmt_exit *stmt);
86 static int exec_stmt_return(PLpgSQL_execstate *estate,
87 PLpgSQL_stmt_return *stmt);
88 static int exec_stmt_return_next(PLpgSQL_execstate *estate,
89 PLpgSQL_stmt_return_next *stmt);
90 static int exec_stmt_raise(PLpgSQL_execstate *estate,
91 PLpgSQL_stmt_raise *stmt);
92 static int exec_stmt_execsql(PLpgSQL_execstate *estate,
93 PLpgSQL_stmt_execsql *stmt);
94 static int exec_stmt_dynexecute(PLpgSQL_execstate *estate,
95 PLpgSQL_stmt_dynexecute *stmt);
96 static int exec_stmt_dynfors(PLpgSQL_execstate *estate,
97 PLpgSQL_stmt_dynfors *stmt);
99 static void plpgsql_estate_setup(PLpgSQL_execstate *estate,
100 PLpgSQL_function *func,
102 static void exec_eval_cleanup(PLpgSQL_execstate *estate);
104 static void exec_prepare_plan(PLpgSQL_execstate *estate,
106 static bool exec_simple_check_node(Node *node);
107 static void exec_simple_check_plan(PLpgSQL_expr *expr);
108 static Datum exec_eval_simple_expr(PLpgSQL_execstate *estate,
113 static void exec_assign_expr(PLpgSQL_execstate *estate,
114 PLpgSQL_datum *target,
116 static void exec_assign_value(PLpgSQL_execstate *estate,
117 PLpgSQL_datum *target,
118 Datum value, Oid valtype, bool *isNull);
119 static void exec_eval_datum(PLpgSQL_execstate *estate,
120 PLpgSQL_datum *datum,
125 static int exec_eval_integer(PLpgSQL_execstate *estate,
128 static bool exec_eval_boolean(PLpgSQL_execstate *estate,
131 static Datum exec_eval_expr(PLpgSQL_execstate *estate,
135 static int exec_run_select(PLpgSQL_execstate *estate,
136 PLpgSQL_expr *expr, long maxtuples, Portal *portalP);
137 static void exec_move_row(PLpgSQL_execstate *estate,
140 HeapTuple tup, TupleDesc tupdesc);
141 static HeapTuple make_tuple_from_row(PLpgSQL_execstate *estate,
144 static char *convert_value_to_string(Datum value, Oid valtype);
145 static Datum exec_cast_value(Datum value, Oid valtype,
151 static Datum exec_simple_cast_value(Datum value, Oid valtype,
152 Oid reqtype, int32 reqtypmod,
154 static void exec_init_tuple_store(PLpgSQL_execstate *estate);
155 static bool compatible_tupdesc(TupleDesc td1, TupleDesc td2);
156 static void exec_set_found(PLpgSQL_execstate *estate, bool state);
157 static void free_var(PLpgSQL_var *var);
161 * plpgsql_exec_function Called by the call handler for
162 * function execution.
166 plpgsql_exec_function(PLpgSQL_function *func, FunctionCallInfo fcinfo)
168 PLpgSQL_execstate estate;
169 ErrorContextCallback plerrcontext;
174 * Setup the execution state
176 plpgsql_estate_setup(&estate, func, (ReturnSetInfo *) fcinfo->resultinfo);
179 * Setup error traceback support for ereport()
181 plerrcontext.callback = plpgsql_exec_error_callback;
182 plerrcontext.arg = &estate;
183 plerrcontext.previous = error_context_stack;
184 error_context_stack = &plerrcontext;
187 * Make local execution copies of all the datums
189 estate.err_text = gettext_noop("during initialization of execution state");
190 for (i = 0; i < estate.ndatums; i++)
191 estate.datums[i] = copy_plpgsql_datum(func->datums[i]);
194 * Store the actual call argument values into the appropriate variables
196 estate.err_text = gettext_noop("while storing call arguments into local variables");
197 for (i = 0; i < func->fn_nargs; i++)
199 int n = func->fn_argvarnos[i];
201 switch (estate.datums[n]->dtype)
203 case PLPGSQL_DTYPE_VAR:
205 PLpgSQL_var *var = (PLpgSQL_var *) estate.datums[n];
207 var->value = fcinfo->arg[i];
208 var->isnull = fcinfo->argnull[i];
209 var->freeval = false;
213 case PLPGSQL_DTYPE_ROW:
215 PLpgSQL_row *row = (PLpgSQL_row *) estate.datums[n];
217 if (!fcinfo->argnull[i])
223 HeapTupleData tmptup;
225 td = DatumGetHeapTupleHeader(fcinfo->arg[i]);
226 /* Extract rowtype info and find a tupdesc */
227 tupType = HeapTupleHeaderGetTypeId(td);
228 tupTypmod = HeapTupleHeaderGetTypMod(td);
229 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
230 /* Build a temporary HeapTuple control structure */
231 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
232 ItemPointerSetInvalid(&(tmptup.t_self));
233 tmptup.t_tableOid = InvalidOid;
235 exec_move_row(&estate, NULL, row, &tmptup, tupdesc);
239 /* If arg is null, treat it as an empty row */
240 exec_move_row(&estate, NULL, row, NULL, NULL);
246 elog(ERROR, "unrecognized dtype: %d", func->datums[i]->dtype);
251 * Set the magic variable FOUND to false
253 exec_set_found(&estate, false);
256 * Now call the toplevel block of statements
258 estate.err_text = NULL;
259 estate.err_stmt = (PLpgSQL_stmt *) (func->action);
260 rc = exec_stmt_block(&estate, func->action);
261 if (rc != PLPGSQL_RC_RETURN)
263 estate.err_stmt = NULL;
264 estate.err_text = NULL;
267 * Provide a more helpful message if a CONTINUE has been used outside
270 if (rc == PLPGSQL_RC_CONTINUE)
272 (errcode(ERRCODE_SYNTAX_ERROR),
273 errmsg("CONTINUE cannot be used outside a loop")));
276 (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
277 errmsg("control reached end of function without RETURN")));
281 * We got a return value - process it
283 estate.err_stmt = NULL;
284 estate.err_text = gettext_noop("while casting return value to function's return type");
286 fcinfo->isnull = estate.retisnull;
290 ReturnSetInfo *rsi = estate.rsi;
292 /* Check caller can handle a set result */
293 if (!rsi || !IsA(rsi, ReturnSetInfo) ||
294 (rsi->allowedModes & SFRM_Materialize) == 0)
296 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
297 errmsg("set-valued function called in context that cannot accept a set")));
298 rsi->returnMode = SFRM_Materialize;
300 /* If we produced any tuples, send back the result */
301 if (estate.tuple_store)
303 rsi->setResult = estate.tuple_store;
304 if (estate.rettupdesc)
306 MemoryContext oldcxt;
308 oldcxt = MemoryContextSwitchTo(estate.tuple_store_cxt);
309 rsi->setDesc = CreateTupleDescCopy(estate.rettupdesc);
310 MemoryContextSwitchTo(oldcxt);
313 estate.retval = (Datum) 0;
314 fcinfo->isnull = true;
316 else if (!estate.retisnull)
318 if (estate.retistuple)
321 * We have to check that the returned tuple actually matches
322 * the expected result type. XXX would be better to cache the
323 * tupdesc instead of repeating get_call_result_type()
327 switch (get_call_result_type(fcinfo, NULL, &tupdesc))
329 case TYPEFUNC_COMPOSITE:
330 /* got the expected result rowtype, now check it */
331 if (estate.rettupdesc == NULL ||
332 !compatible_tupdesc(estate.rettupdesc, tupdesc))
334 (errcode(ERRCODE_DATATYPE_MISMATCH),
335 errmsg("returned record type does not match expected record type")));
337 case TYPEFUNC_RECORD:
339 * Failed to determine actual type of RECORD. We could
340 * raise an error here, but what this means in practice
341 * is that the caller is expecting any old generic
342 * rowtype, so we don't really need to be restrictive.
343 * Pass back the generated result type, instead.
345 tupdesc = estate.rettupdesc;
346 if (tupdesc == NULL) /* shouldn't happen */
347 elog(ERROR, "return type must be a row type");
350 /* shouldn't get here if retistuple is true ... */
351 elog(ERROR, "return type must be a row type");
356 * Copy tuple to upper executor memory, as a tuple Datum.
357 * Make sure it is labeled with the caller-supplied tuple type.
360 PointerGetDatum(SPI_returntuple((HeapTuple) (estate.retval),
365 /* Cast value to proper type */
366 estate.retval = exec_cast_value(estate.retval, estate.rettype,
368 &(func->fn_retinput),
369 func->fn_rettypioparam,
374 * If the function's return type isn't by value, copy the value
375 * into upper executor memory context.
377 if (!fcinfo->isnull && !func->fn_retbyval)
382 len = datumGetSize(estate.retval, false, func->fn_rettyplen);
383 tmp = (void *) SPI_palloc(len);
384 memcpy(tmp, DatumGetPointer(estate.retval), len);
385 estate.retval = PointerGetDatum(tmp);
390 /* Clean up any leftover temporary memory */
391 FreeExprContext(estate.eval_econtext);
392 estate.eval_econtext = NULL;
393 exec_eval_cleanup(&estate);
396 * Pop the error context stack
398 error_context_stack = plerrcontext.previous;
401 * Return the function's result
403 return estate.retval;
408 * plpgsql_exec_trigger Called by the call handler for
413 plpgsql_exec_trigger(PLpgSQL_function *func,
414 TriggerData *trigdata)
416 PLpgSQL_execstate estate;
417 ErrorContextCallback plerrcontext;
421 PLpgSQL_rec *rec_new,
426 * Setup the execution state
428 plpgsql_estate_setup(&estate, func, NULL);
431 * Setup error traceback support for ereport()
433 plerrcontext.callback = plpgsql_exec_error_callback;
434 plerrcontext.arg = &estate;
435 plerrcontext.previous = error_context_stack;
436 error_context_stack = &plerrcontext;
439 * Make local execution copies of all the datums
441 estate.err_text = gettext_noop("during initialization of execution state");
442 for (i = 0; i < estate.ndatums; i++)
443 estate.datums[i] = copy_plpgsql_datum(func->datums[i]);
446 * Put the OLD and NEW tuples into record variables
448 rec_new = (PLpgSQL_rec *) (estate.datums[func->new_varno]);
449 rec_new->freetup = false;
450 rec_new->freetupdesc = false;
451 rec_old = (PLpgSQL_rec *) (estate.datums[func->old_varno]);
452 rec_old->freetup = false;
453 rec_old->freetupdesc = false;
455 if (TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
458 * Per-statement triggers don't use OLD/NEW variables
461 rec_new->tupdesc = NULL;
463 rec_old->tupdesc = NULL;
465 else if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
467 rec_new->tup = trigdata->tg_trigtuple;
468 rec_new->tupdesc = trigdata->tg_relation->rd_att;
470 rec_old->tupdesc = NULL;
472 else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
474 rec_new->tup = trigdata->tg_newtuple;
475 rec_new->tupdesc = trigdata->tg_relation->rd_att;
476 rec_old->tup = trigdata->tg_trigtuple;
477 rec_old->tupdesc = trigdata->tg_relation->rd_att;
479 else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
482 rec_new->tupdesc = NULL;
483 rec_old->tup = trigdata->tg_trigtuple;
484 rec_old->tupdesc = trigdata->tg_relation->rd_att;
487 elog(ERROR, "unrecognized trigger action: not INSERT, DELETE, or UPDATE");
490 * Assign the special tg_ variables
493 var = (PLpgSQL_var *) (estate.datums[func->tg_op_varno]);
494 if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
495 var->value = DirectFunctionCall1(textin, CStringGetDatum("INSERT"));
496 else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
497 var->value = DirectFunctionCall1(textin, CStringGetDatum("UPDATE"));
498 else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
499 var->value = DirectFunctionCall1(textin, CStringGetDatum("DELETE"));
501 elog(ERROR, "unrecognized trigger action: not INSERT, DELETE, or UPDATE");
505 var = (PLpgSQL_var *) (estate.datums[func->tg_name_varno]);
506 var->value = DirectFunctionCall1(namein,
507 CStringGetDatum(trigdata->tg_trigger->tgname));
511 var = (PLpgSQL_var *) (estate.datums[func->tg_when_varno]);
512 if (TRIGGER_FIRED_BEFORE(trigdata->tg_event))
513 var->value = DirectFunctionCall1(textin, CStringGetDatum("BEFORE"));
514 else if (TRIGGER_FIRED_AFTER(trigdata->tg_event))
515 var->value = DirectFunctionCall1(textin, CStringGetDatum("AFTER"));
517 elog(ERROR, "unrecognized trigger execution time: not BEFORE or AFTER");
521 var = (PLpgSQL_var *) (estate.datums[func->tg_level_varno]);
522 if (TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
523 var->value = DirectFunctionCall1(textin, CStringGetDatum("ROW"));
524 else if (TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
525 var->value = DirectFunctionCall1(textin, CStringGetDatum("STATEMENT"));
527 elog(ERROR, "unrecognized trigger event type: not ROW or STATEMENT");
531 var = (PLpgSQL_var *) (estate.datums[func->tg_relid_varno]);
532 var->value = ObjectIdGetDatum(trigdata->tg_relation->rd_id);
534 var->freeval = false;
536 var = (PLpgSQL_var *) (estate.datums[func->tg_relname_varno]);
537 var->value = DirectFunctionCall1(namein,
538 CStringGetDatum(RelationGetRelationName(trigdata->tg_relation)));
542 var = (PLpgSQL_var *) (estate.datums[func->tg_nargs_varno]);
543 var->value = Int16GetDatum(trigdata->tg_trigger->tgnargs);
545 var->freeval = false;
548 * Store the trigger argument values into the special execution state
551 estate.err_text = gettext_noop("while storing call arguments into local variables");
552 estate.trig_nargs = trigdata->tg_trigger->tgnargs;
553 if (estate.trig_nargs == 0)
554 estate.trig_argv = NULL;
557 estate.trig_argv = palloc(sizeof(Datum) * estate.trig_nargs);
558 for (i = 0; i < trigdata->tg_trigger->tgnargs; i++)
559 estate.trig_argv[i] = DirectFunctionCall1(textin,
560 CStringGetDatum(trigdata->tg_trigger->tgargs[i]));
564 * Set the magic variable FOUND to false
566 exec_set_found(&estate, false);
569 * Now call the toplevel block of statements
571 estate.err_text = NULL;
572 estate.err_stmt = (PLpgSQL_stmt *) (func->action);
573 rc = exec_stmt_block(&estate, func->action);
574 if (rc != PLPGSQL_RC_RETURN)
576 estate.err_stmt = NULL;
577 estate.err_text = NULL;
580 * Provide a more helpful message if a CONTINUE has been used outside
583 if (rc == PLPGSQL_RC_CONTINUE)
585 (errcode(ERRCODE_SYNTAX_ERROR),
586 errmsg("CONTINUE cannot be used outside a loop")));
589 (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
590 errmsg("control reached end of trigger procedure without RETURN")));
595 (errcode(ERRCODE_DATATYPE_MISMATCH),
596 errmsg("trigger procedure cannot return a set")));
599 * Check that the returned tuple structure has the same attributes, the
600 * relation that fired the trigger has. A per-statement trigger always
601 * needs to return NULL, so we ignore any return value the function itself
602 * produces (XXX: is this a good idea?)
604 * XXX This way it is possible, that the trigger returns a tuple where
605 * attributes don't have the correct atttypmod's length. It's up to the
606 * trigger's programmer to ensure that this doesn't happen. Jan
608 if (estate.retisnull || TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
612 if (!compatible_tupdesc(estate.rettupdesc,
613 trigdata->tg_relation->rd_att))
615 (errcode(ERRCODE_DATATYPE_MISMATCH),
616 errmsg("returned tuple structure does not match table of trigger event")));
617 /* Copy tuple to upper executor memory */
618 rettup = SPI_copytuple((HeapTuple) (estate.retval));
621 /* Clean up any leftover temporary memory */
622 FreeExprContext(estate.eval_econtext);
623 estate.eval_econtext = NULL;
624 exec_eval_cleanup(&estate);
627 * Pop the error context stack
629 error_context_stack = plerrcontext.previous;
632 * Return the trigger's result
639 * error context callback to let us supply a call-stack traceback
642 plpgsql_exec_error_callback(void *arg)
644 PLpgSQL_execstate *estate = (PLpgSQL_execstate *) arg;
646 /* safety check, shouldn't happen */
647 if (estate->err_func == NULL)
650 /* if we are doing RAISE, don't report its location */
651 if (estate->err_text == raise_skip_msg)
654 if (estate->err_stmt != NULL)
656 /* translator: last %s is a plpgsql statement type name */
657 errcontext("PL/pgSQL function \"%s\" line %d at %s",
658 estate->err_func->fn_name,
659 estate->err_stmt->lineno,
660 plpgsql_stmt_typename(estate->err_stmt));
662 else if (estate->err_text != NULL)
665 * We don't expend the cycles to run gettext() on err_text unless we
666 * actually need it. Therefore, places that set up err_text should
667 * use gettext_noop() to ensure the strings get recorded in the
668 * message dictionary.
672 * translator: last %s is a phrase such as "while storing call
673 * arguments into local variables"
675 errcontext("PL/pgSQL function \"%s\" %s",
676 estate->err_func->fn_name,
677 gettext(estate->err_text));
680 errcontext("PL/pgSQL function \"%s\"",
681 estate->err_func->fn_name);
686 * Support function for initializing local execution variables
689 static PLpgSQL_datum *
690 copy_plpgsql_datum(PLpgSQL_datum *datum)
692 PLpgSQL_datum *result;
694 switch (datum->dtype)
696 case PLPGSQL_DTYPE_VAR:
698 PLpgSQL_var *new = palloc(sizeof(PLpgSQL_var));
700 memcpy(new, datum, sizeof(PLpgSQL_var));
701 /* Ensure the value is null (possibly not needed?) */
704 new->freeval = false;
706 result = (PLpgSQL_datum *) new;
710 case PLPGSQL_DTYPE_REC:
712 PLpgSQL_rec *new = palloc(sizeof(PLpgSQL_rec));
714 memcpy(new, datum, sizeof(PLpgSQL_rec));
715 /* Ensure the value is null (possibly not needed?) */
718 new->freetup = false;
719 new->freetupdesc = false;
721 result = (PLpgSQL_datum *) new;
725 case PLPGSQL_DTYPE_ROW:
726 case PLPGSQL_DTYPE_RECFIELD:
727 case PLPGSQL_DTYPE_ARRAYELEM:
728 case PLPGSQL_DTYPE_TRIGARG:
731 * These datum records are read-only at runtime, so no need to
738 elog(ERROR, "unrecognized dtype: %d", datum->dtype);
739 result = NULL; /* keep compiler quiet */
748 exception_matches_conditions(ErrorData *edata, PLpgSQL_condition *cond)
750 for (; cond != NULL; cond = cond->next)
752 int sqlerrstate = cond->sqlerrstate;
755 * OTHERS matches everything *except* query-canceled; if you're
756 * foolish enough, you can match that explicitly.
758 if (sqlerrstate == 0)
760 if (edata->sqlerrcode != ERRCODE_QUERY_CANCELED)
764 else if (edata->sqlerrcode == sqlerrstate)
766 /* Category match? */
767 else if (ERRCODE_IS_CATEGORY(sqlerrstate) &&
768 ERRCODE_TO_CATEGORY(edata->sqlerrcode) == sqlerrstate)
776 * exec_stmt_block Execute a block of statements
780 exec_stmt_block(PLpgSQL_execstate *estate, PLpgSQL_stmt_block *block)
782 volatile int rc = -1;
787 * First initialize all variables declared in this block
789 for (i = 0; i < block->n_initvars; i++)
791 n = block->initvarnos[i];
793 switch (estate->datums[n]->dtype)
795 case PLPGSQL_DTYPE_VAR:
797 PLpgSQL_var *var = (PLpgSQL_var *) (estate->datums[n]);
800 if (!var->isconst || var->isnull)
802 if (var->default_val == NULL)
804 var->value = (Datum) 0;
808 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
809 errmsg("variable \"%s\" declared NOT NULL cannot default to NULL",
814 exec_assign_expr(estate, (PLpgSQL_datum *) var,
821 case PLPGSQL_DTYPE_REC:
823 PLpgSQL_rec *rec = (PLpgSQL_rec *) (estate->datums[n]);
827 heap_freetuple(rec->tup);
828 FreeTupleDesc(rec->tupdesc);
829 rec->freetup = false;
837 case PLPGSQL_DTYPE_RECFIELD:
838 case PLPGSQL_DTYPE_ARRAYELEM:
842 elog(ERROR, "unrecognized dtype: %d",
843 estate->datums[n]->dtype);
847 if (block->exceptions)
850 * Execute the statements in the block's body inside a sub-transaction
852 MemoryContext oldcontext = CurrentMemoryContext;
853 ResourceOwner oldowner = CurrentResourceOwner;
855 BeginInternalSubTransaction(NULL);
856 /* Want to run statements inside function's memory context */
857 MemoryContextSwitchTo(oldcontext);
861 rc = exec_stmts(estate, block->body);
863 /* Commit the inner transaction, return to outer xact context */
864 ReleaseCurrentSubTransaction();
865 MemoryContextSwitchTo(oldcontext);
866 CurrentResourceOwner = oldowner;
869 * AtEOSubXact_SPI() should not have popped any SPI context, but
870 * just in case it did, make sure we remain connected.
872 SPI_restore_connection();
879 /* Save error info */
880 MemoryContextSwitchTo(oldcontext);
881 edata = CopyErrorData();
884 /* Abort the inner transaction */
885 RollbackAndReleaseCurrentSubTransaction();
886 MemoryContextSwitchTo(oldcontext);
887 CurrentResourceOwner = oldowner;
890 * If AtEOSubXact_SPI() popped any SPI context of the subxact, it
891 * will have left us in a disconnected state. We need this hack
892 * to return to connected state.
894 SPI_restore_connection();
896 /* Look for a matching exception handler */
897 foreach(e, block->exceptions->exc_list)
899 PLpgSQL_exception *exception = (PLpgSQL_exception *) lfirst(e);
901 if (exception_matches_conditions(edata, exception->conditions))
904 * Initialize the magic SQLSTATE and SQLERRM variables for
905 * the exception block. We needn't do this until we have
906 * found a matching exception.
908 PLpgSQL_var *state_var;
909 PLpgSQL_var *errm_var;
911 state_var = (PLpgSQL_var *)
912 estate->datums[block->exceptions->sqlstate_varno];
913 state_var->value = DirectFunctionCall1(textin,
914 CStringGetDatum(unpack_sql_state(edata->sqlerrcode)));
915 state_var->freeval = true;
916 state_var->isnull = false;
918 errm_var = (PLpgSQL_var *)
919 estate->datums[block->exceptions->sqlerrm_varno];
920 errm_var->value = DirectFunctionCall1(textin,
921 CStringGetDatum(edata->message));
922 errm_var->freeval = true;
923 errm_var->isnull = false;
925 rc = exec_stmts(estate, exception->action);
933 /* If no match found, re-throw the error */
937 FreeErrorData(edata);
944 * Just execute the statements in the block's body
946 rc = exec_stmts(estate, block->body);
950 * Handle the return code.
955 case PLPGSQL_RC_CONTINUE:
956 case PLPGSQL_RC_RETURN:
959 case PLPGSQL_RC_EXIT:
960 if (estate->exitlabel == NULL)
961 return PLPGSQL_RC_OK;
962 if (block->label == NULL)
963 return PLPGSQL_RC_EXIT;
964 if (strcmp(block->label, estate->exitlabel))
965 return PLPGSQL_RC_EXIT;
966 estate->exitlabel = NULL;
967 return PLPGSQL_RC_OK;
970 elog(ERROR, "unrecognized rc: %d", rc);
973 return PLPGSQL_RC_OK;
978 * exec_stmts Iterate over a list of statements
979 * as long as their return code is OK
983 exec_stmts(PLpgSQL_execstate *estate, List *stmts)
990 * Ensure we do a CHECK_FOR_INTERRUPTS() even though there is no
991 * statement. This prevents hangup in a tight loop if, for instance,
992 * there is a LOOP construct with an empty body.
994 CHECK_FOR_INTERRUPTS();
995 return PLPGSQL_RC_OK;
1000 PLpgSQL_stmt *stmt = (PLpgSQL_stmt *) lfirst(s);
1001 int rc = exec_stmt(estate, stmt);
1003 if (rc != PLPGSQL_RC_OK)
1007 return PLPGSQL_RC_OK;
1012 * exec_stmt Distribute one statement to the statements
1013 * type specific execution function.
1017 exec_stmt(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
1019 PLpgSQL_stmt *save_estmt;
1022 save_estmt = estate->err_stmt;
1023 estate->err_stmt = stmt;
1025 CHECK_FOR_INTERRUPTS();
1027 switch (stmt->cmd_type)
1029 case PLPGSQL_STMT_BLOCK:
1030 rc = exec_stmt_block(estate, (PLpgSQL_stmt_block *) stmt);
1033 case PLPGSQL_STMT_ASSIGN:
1034 rc = exec_stmt_assign(estate, (PLpgSQL_stmt_assign *) stmt);
1037 case PLPGSQL_STMT_PERFORM:
1038 rc = exec_stmt_perform(estate, (PLpgSQL_stmt_perform *) stmt);
1041 case PLPGSQL_STMT_GETDIAG:
1042 rc = exec_stmt_getdiag(estate, (PLpgSQL_stmt_getdiag *) stmt);
1045 case PLPGSQL_STMT_IF:
1046 rc = exec_stmt_if(estate, (PLpgSQL_stmt_if *) stmt);
1049 case PLPGSQL_STMT_LOOP:
1050 rc = exec_stmt_loop(estate, (PLpgSQL_stmt_loop *) stmt);
1053 case PLPGSQL_STMT_WHILE:
1054 rc = exec_stmt_while(estate, (PLpgSQL_stmt_while *) stmt);
1057 case PLPGSQL_STMT_FORI:
1058 rc = exec_stmt_fori(estate, (PLpgSQL_stmt_fori *) stmt);
1061 case PLPGSQL_STMT_FORS:
1062 rc = exec_stmt_fors(estate, (PLpgSQL_stmt_fors *) stmt);
1065 case PLPGSQL_STMT_SELECT:
1066 rc = exec_stmt_select(estate, (PLpgSQL_stmt_select *) stmt);
1069 case PLPGSQL_STMT_EXIT:
1070 rc = exec_stmt_exit(estate, (PLpgSQL_stmt_exit *) stmt);
1073 case PLPGSQL_STMT_RETURN:
1074 rc = exec_stmt_return(estate, (PLpgSQL_stmt_return *) stmt);
1077 case PLPGSQL_STMT_RETURN_NEXT:
1078 rc = exec_stmt_return_next(estate, (PLpgSQL_stmt_return_next *) stmt);
1081 case PLPGSQL_STMT_RAISE:
1082 rc = exec_stmt_raise(estate, (PLpgSQL_stmt_raise *) stmt);
1085 case PLPGSQL_STMT_EXECSQL:
1086 rc = exec_stmt_execsql(estate, (PLpgSQL_stmt_execsql *) stmt);
1089 case PLPGSQL_STMT_DYNEXECUTE:
1090 rc = exec_stmt_dynexecute(estate, (PLpgSQL_stmt_dynexecute *) stmt);
1093 case PLPGSQL_STMT_DYNFORS:
1094 rc = exec_stmt_dynfors(estate, (PLpgSQL_stmt_dynfors *) stmt);
1097 case PLPGSQL_STMT_OPEN:
1098 rc = exec_stmt_open(estate, (PLpgSQL_stmt_open *) stmt);
1101 case PLPGSQL_STMT_FETCH:
1102 rc = exec_stmt_fetch(estate, (PLpgSQL_stmt_fetch *) stmt);
1105 case PLPGSQL_STMT_CLOSE:
1106 rc = exec_stmt_close(estate, (PLpgSQL_stmt_close *) stmt);
1110 estate->err_stmt = save_estmt;
1111 elog(ERROR, "unrecognized cmdtype: %d", stmt->cmd_type);
1114 estate->err_stmt = save_estmt;
1121 * exec_stmt_assign Evaluate an expression and
1122 * put the result into a variable.
1126 exec_stmt_assign(PLpgSQL_execstate *estate, PLpgSQL_stmt_assign *stmt)
1128 Assert(stmt->varno >= 0);
1130 exec_assign_expr(estate, estate->datums[stmt->varno], stmt->expr);
1132 return PLPGSQL_RC_OK;
1136 * exec_stmt_perform Evaluate query and discard result (but set
1137 * FOUND depending on whether at least one row
1142 exec_stmt_perform(PLpgSQL_execstate *estate, PLpgSQL_stmt_perform *stmt)
1144 PLpgSQL_expr *expr = stmt->expr;
1146 (void) exec_run_select(estate, expr, 0, NULL);
1147 exec_set_found(estate, (estate->eval_processed != 0));
1148 exec_eval_cleanup(estate);
1150 return PLPGSQL_RC_OK;
1154 * exec_stmt_getdiag Put internal PG information into
1155 * specified variables.
1159 exec_stmt_getdiag(PLpgSQL_execstate *estate, PLpgSQL_stmt_getdiag *stmt)
1163 foreach(lc, stmt->diag_items)
1165 PLpgSQL_diag_item *diag_item = (PLpgSQL_diag_item *) lfirst(lc);
1167 bool isnull = false;
1169 if (diag_item->target <= 0)
1172 var = estate->datums[diag_item->target];
1177 switch (diag_item->kind)
1179 case PLPGSQL_GETDIAG_ROW_COUNT:
1181 exec_assign_value(estate, var,
1182 UInt32GetDatum(estate->eval_processed),
1186 case PLPGSQL_GETDIAG_RESULT_OID:
1188 exec_assign_value(estate, var,
1189 ObjectIdGetDatum(estate->eval_lastoid),
1194 elog(ERROR, "unrecognized attribute request: %d",
1199 return PLPGSQL_RC_OK;
1203 * exec_stmt_if Evaluate a bool expression and
1204 * execute the true or false body
1209 exec_stmt_if(PLpgSQL_execstate *estate, PLpgSQL_stmt_if *stmt)
1214 value = exec_eval_boolean(estate, stmt->cond, &isnull);
1215 exec_eval_cleanup(estate);
1217 if (!isnull && value)
1219 if (stmt->true_body != NIL)
1220 return exec_stmts(estate, stmt->true_body);
1224 if (stmt->false_body != NIL)
1225 return exec_stmts(estate, stmt->false_body);
1228 return PLPGSQL_RC_OK;
1233 * exec_stmt_loop Loop over statements until
1238 exec_stmt_loop(PLpgSQL_execstate *estate, PLpgSQL_stmt_loop *stmt)
1242 int rc = exec_stmts(estate, stmt->body);
1249 case PLPGSQL_RC_EXIT:
1250 if (estate->exitlabel == NULL)
1251 return PLPGSQL_RC_OK;
1252 if (stmt->label == NULL)
1253 return PLPGSQL_RC_EXIT;
1254 if (strcmp(stmt->label, estate->exitlabel) != 0)
1255 return PLPGSQL_RC_EXIT;
1256 estate->exitlabel = NULL;
1257 return PLPGSQL_RC_OK;
1259 case PLPGSQL_RC_CONTINUE:
1260 if (estate->exitlabel == NULL)
1261 /* anonymous continue, so re-run the loop */
1263 else if (stmt->label != NULL &&
1264 strcmp(stmt->label, estate->exitlabel) == 0)
1265 /* label matches named continue, so re-run loop */
1266 estate->exitlabel = NULL;
1268 /* label doesn't match named continue, so propagate upward */
1269 return PLPGSQL_RC_CONTINUE;
1272 case PLPGSQL_RC_RETURN:
1273 return PLPGSQL_RC_RETURN;
1276 elog(ERROR, "unrecognized rc: %d", rc);
1280 return PLPGSQL_RC_OK;
1285 * exec_stmt_while Loop over statements as long
1286 * as an expression evaluates to
1287 * true or an exit occurs.
1291 exec_stmt_while(PLpgSQL_execstate *estate, PLpgSQL_stmt_while *stmt)
1299 value = exec_eval_boolean(estate, stmt->cond, &isnull);
1300 exec_eval_cleanup(estate);
1302 if (isnull || !value)
1305 rc = exec_stmts(estate, stmt->body);
1312 case PLPGSQL_RC_EXIT:
1313 if (estate->exitlabel == NULL)
1314 return PLPGSQL_RC_OK;
1315 if (stmt->label == NULL)
1316 return PLPGSQL_RC_EXIT;
1317 if (strcmp(stmt->label, estate->exitlabel))
1318 return PLPGSQL_RC_EXIT;
1319 estate->exitlabel = NULL;
1320 return PLPGSQL_RC_OK;
1322 case PLPGSQL_RC_CONTINUE:
1323 if (estate->exitlabel == NULL)
1324 /* anonymous continue, so re-run loop */
1326 else if (stmt->label != NULL &&
1327 strcmp(stmt->label, estate->exitlabel) == 0)
1328 /* label matches named continue, so re-run loop */
1329 estate->exitlabel = NULL;
1331 /* label doesn't match named continue, propagate upward */
1332 return PLPGSQL_RC_CONTINUE;
1335 case PLPGSQL_RC_RETURN:
1336 return PLPGSQL_RC_RETURN;
1339 elog(ERROR, "unrecognized rc: %d", rc);
1343 return PLPGSQL_RC_OK;
1348 * exec_stmt_fori Iterate an integer variable
1349 * from a lower to an upper value.
1350 * Loop can be left with exit.
1354 exec_stmt_fori(PLpgSQL_execstate *estate, PLpgSQL_stmt_fori *stmt)
1361 int rc = PLPGSQL_RC_OK;
1363 var = (PLpgSQL_var *) (estate->datums[stmt->var->varno]);
1366 * Get the value of the lower bound into the loop var
1368 value = exec_eval_expr(estate, stmt->lower, &isnull, &valtype);
1369 value = exec_cast_value(value, valtype, var->datatype->typoid,
1370 &(var->datatype->typinput),
1371 var->datatype->typioparam,
1372 var->datatype->atttypmod, isnull);
1375 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1376 errmsg("lower bound of FOR loop cannot be NULL")));
1378 var->isnull = false;
1379 exec_eval_cleanup(estate);
1382 * Get the value of the upper bound
1384 value = exec_eval_expr(estate, stmt->upper, &isnull, &valtype);
1385 value = exec_cast_value(value, valtype, var->datatype->typoid,
1386 &(var->datatype->typinput),
1387 var->datatype->typioparam,
1388 var->datatype->atttypmod, isnull);
1391 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1392 errmsg("upper bound of FOR loop cannot be NULL")));
1393 exec_eval_cleanup(estate);
1405 if ((int4) (var->value) < (int4) value)
1410 if ((int4) (var->value) > (int4) value)
1414 found = true; /* looped at least once */
1417 * Execute the statements
1419 rc = exec_stmts(estate, stmt->body);
1421 if (rc == PLPGSQL_RC_RETURN)
1422 break; /* return from function */
1423 else if (rc == PLPGSQL_RC_EXIT)
1425 if (estate->exitlabel == NULL)
1426 /* unlabelled exit, finish the current loop */
1428 else if (stmt->label != NULL &&
1429 strcmp(stmt->label, estate->exitlabel) == 0)
1431 /* labelled exit, matches the current stmt's label */
1432 estate->exitlabel = NULL;
1437 * otherwise, this is a labelled exit that does not match the
1438 * current statement's label, if any: return RC_EXIT so that the
1439 * EXIT continues to propagate up the stack.
1444 else if (rc == PLPGSQL_RC_CONTINUE)
1446 if (estate->exitlabel == NULL)
1447 /* anonymous continue, so re-run the current loop */
1449 else if (stmt->label != NULL &&
1450 strcmp(stmt->label, estate->exitlabel) == 0)
1452 /* label matches named continue, so re-run loop */
1453 estate->exitlabel = NULL;
1459 * otherwise, this is a named continue that does not match the
1460 * current statement's label, if any: return RC_CONTINUE so
1461 * that the CONTINUE will propagate up the stack.
1468 * Increase/decrease loop var
1477 * Set the FOUND variable to indicate the result of executing the loop
1478 * (namely, whether we looped one or more times). This must be set here so
1479 * that it does not interfere with the value of the FOUND variable inside
1480 * the loop processing itself.
1482 exec_set_found(estate, found);
1489 * exec_stmt_fors Execute a query, assign each
1490 * tuple to a record or row and
1491 * execute a group of statements
1496 exec_stmt_fors(PLpgSQL_execstate *estate, PLpgSQL_stmt_fors *stmt)
1498 PLpgSQL_rec *rec = NULL;
1499 PLpgSQL_row *row = NULL;
1500 SPITupleTable *tuptab;
1503 int rc = PLPGSQL_RC_OK;
1508 * Determine if we assign to a record or a row
1510 if (stmt->rec != NULL)
1511 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
1512 else if (stmt->row != NULL)
1513 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
1515 elog(ERROR, "unsupported target");
1518 * Open the implicit cursor for the statement and fetch the initial 10
1521 exec_run_select(estate, stmt->query, 0, &portal);
1523 SPI_cursor_fetch(portal, true, 10);
1524 tuptab = SPI_tuptable;
1528 * If the query didn't return any rows, set the target to NULL and return
1529 * with FOUND = false.
1532 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
1534 found = true; /* processed at least one tuple */
1541 for (i = 0; i < n; i++)
1544 * Assign the tuple to the target
1546 exec_move_row(estate, rec, row, tuptab->vals[i], tuptab->tupdesc);
1549 * Execute the statements
1551 rc = exec_stmts(estate, stmt->body);
1552 if (rc != PLPGSQL_RC_OK)
1554 if (rc == PLPGSQL_RC_EXIT)
1556 if (estate->exitlabel == NULL)
1557 /* unlabelled exit, finish the current loop */
1559 else if (stmt->label != NULL &&
1560 strcmp(stmt->label, estate->exitlabel) == 0)
1562 /* labelled exit, matches the current stmt's label */
1563 estate->exitlabel = NULL;
1568 * otherwise, we processed a labelled exit that does not
1569 * match the current statement's label, if any: return
1570 * RC_EXIT so that the EXIT continues to recurse upward.
1573 else if (rc == PLPGSQL_RC_CONTINUE)
1575 if (estate->exitlabel == NULL)
1577 /* anonymous continue, so re-run the current loop */
1581 else if (stmt->label != NULL &&
1582 strcmp(stmt->label, estate->exitlabel) == 0)
1584 /* label matches named continue, so re-run loop */
1586 estate->exitlabel = NULL;
1591 * otherwise, we processed a named continue that does not
1592 * match the current statement's label, if any: return
1593 * RC_CONTINUE so that the CONTINUE will propagate up the
1599 * We're aborting the loop, so cleanup and set FOUND. (This
1600 * code should match the code after the loop.)
1602 SPI_freetuptable(tuptab);
1603 SPI_cursor_close(portal);
1604 exec_set_found(estate, found);
1610 SPI_freetuptable(tuptab);
1613 * Fetch the next 50 tuples
1615 SPI_cursor_fetch(portal, true, 50);
1617 tuptab = SPI_tuptable;
1621 * Release last group of tuples
1623 SPI_freetuptable(tuptab);
1626 * Close the implicit cursor
1628 SPI_cursor_close(portal);
1631 * Set the FOUND variable to indicate the result of executing the loop
1632 * (namely, whether we looped one or more times). This must be set here so
1633 * that it does not interfere with the value of the FOUND variable inside
1634 * the loop processing itself.
1636 exec_set_found(estate, found);
1643 * exec_stmt_select Run a query and assign the first
1644 * row to a record or rowtype.
1648 exec_stmt_select(PLpgSQL_execstate *estate, PLpgSQL_stmt_select *stmt)
1650 PLpgSQL_rec *rec = NULL;
1651 PLpgSQL_row *row = NULL;
1652 SPITupleTable *tuptab;
1656 * Initialize the global found variable to false
1658 exec_set_found(estate, false);
1661 * Determine if we assign to a record or a row
1663 if (stmt->rec != NULL)
1664 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
1665 else if (stmt->row != NULL)
1666 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
1668 elog(ERROR, "unsupported target");
1673 exec_run_select(estate, stmt->query, 1, NULL);
1674 tuptab = estate->eval_tuptable;
1675 n = estate->eval_processed;
1678 * If the query didn't return any rows, set the target to NULL and return.
1682 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
1683 exec_eval_cleanup(estate);
1684 return PLPGSQL_RC_OK;
1688 * Put the result into the target and set found to true
1690 exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
1691 exec_set_found(estate, true);
1693 exec_eval_cleanup(estate);
1695 return PLPGSQL_RC_OK;
1700 * exec_stmt_exit Implements EXIT and CONTINUE
1702 * This begins the process of exiting / restarting a loop.
1706 exec_stmt_exit(PLpgSQL_execstate *estate, PLpgSQL_stmt_exit *stmt)
1709 * If the exit / continue has a condition, evaluate it
1711 if (stmt->cond != NULL)
1716 value = exec_eval_boolean(estate, stmt->cond, &isnull);
1717 exec_eval_cleanup(estate);
1718 if (isnull || value == false)
1719 return PLPGSQL_RC_OK;
1722 estate->exitlabel = stmt->label;
1724 return PLPGSQL_RC_EXIT;
1726 return PLPGSQL_RC_CONTINUE;
1731 * exec_stmt_return Evaluate an expression and start
1732 * returning from the function.
1736 exec_stmt_return(PLpgSQL_execstate *estate, PLpgSQL_stmt_return *stmt)
1739 * If processing a set-returning PL/PgSQL function, the final RETURN
1740 * indicates that the function is finished producing tuples. The rest of
1741 * the work will be done at the top level.
1743 if (estate->retisset)
1744 return PLPGSQL_RC_RETURN;
1746 /* initialize for null result (possibly a tuple) */
1747 estate->retval = (Datum) 0;
1748 estate->rettupdesc = NULL;
1749 estate->retisnull = true;
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;
1761 estate->retval = var->value;
1762 estate->retisnull = var->isnull;
1763 estate->rettype = var->datatype->typoid;
1767 case PLPGSQL_DTYPE_REC:
1769 PLpgSQL_rec *rec = (PLpgSQL_rec *) retvar;
1771 if (HeapTupleIsValid(rec->tup))
1773 estate->retval = (Datum) rec->tup;
1774 estate->rettupdesc = rec->tupdesc;
1775 estate->retisnull = false;
1780 case PLPGSQL_DTYPE_ROW:
1782 PLpgSQL_row *row = (PLpgSQL_row *) retvar;
1784 Assert(row->rowtupdesc);
1785 estate->retval = (Datum) make_tuple_from_row(estate, row,
1787 if (estate->retval == (Datum) NULL) /* should not happen */
1788 elog(ERROR, "row not compatible with its own tupdesc");
1789 estate->rettupdesc = row->rowtupdesc;
1790 estate->retisnull = false;
1795 elog(ERROR, "unrecognized dtype: %d", retvar->dtype);
1798 return PLPGSQL_RC_RETURN;
1801 if (stmt->expr != NULL)
1803 if (estate->retistuple)
1805 exec_run_select(estate, stmt->expr, 1, NULL);
1806 if (estate->eval_processed > 0)
1808 estate->retval = (Datum) estate->eval_tuptable->vals[0];
1809 estate->rettupdesc = estate->eval_tuptable->tupdesc;
1810 estate->retisnull = false;
1815 /* Normal case for scalar results */
1816 estate->retval = exec_eval_expr(estate, stmt->expr,
1817 &(estate->retisnull),
1818 &(estate->rettype));
1821 return PLPGSQL_RC_RETURN;
1825 * Special hack for function returning VOID: instead of NULL, return a
1826 * non-null VOID value. This is of dubious importance but is kept for
1827 * backwards compatibility. Note that the only other way to get here is
1828 * to have written "RETURN NULL" in a function returning tuple.
1830 if (estate->fn_rettype == VOIDOID)
1832 estate->retval = (Datum) 0;
1833 estate->retisnull = false;
1834 estate->rettype = VOIDOID;
1837 return PLPGSQL_RC_RETURN;
1841 * exec_stmt_return_next Evaluate an expression and add it to the
1842 * list of tuples returned by the current
1847 exec_stmt_return_next(PLpgSQL_execstate *estate,
1848 PLpgSQL_stmt_return_next *stmt)
1853 bool free_tuple = false;
1855 if (!estate->retisset)
1857 (errcode(ERRCODE_SYNTAX_ERROR),
1858 errmsg("cannot use RETURN NEXT in a non-SETOF function")));
1860 if (estate->tuple_store == NULL)
1861 exec_init_tuple_store(estate);
1863 /* rettupdesc will be filled by exec_init_tuple_store */
1864 tupdesc = estate->rettupdesc;
1865 natts = tupdesc->natts;
1867 if (stmt->retvarno >= 0)
1869 PLpgSQL_datum *retvar = estate->datums[stmt->retvarno];
1871 switch (retvar->dtype)
1873 case PLPGSQL_DTYPE_VAR:
1875 PLpgSQL_var *var = (PLpgSQL_var *) retvar;
1876 Datum retval = var->value;
1877 bool isNull = var->isnull;
1881 (errcode(ERRCODE_DATATYPE_MISMATCH),
1882 errmsg("wrong result type supplied in RETURN NEXT")));
1884 /* coerce type if needed */
1885 retval = exec_simple_cast_value(retval,
1886 var->datatype->typoid,
1887 tupdesc->attrs[0]->atttypid,
1888 tupdesc->attrs[0]->atttypmod,
1891 tuple = heap_form_tuple(tupdesc, &retval, &isNull);
1897 case PLPGSQL_DTYPE_REC:
1899 PLpgSQL_rec *rec = (PLpgSQL_rec *) retvar;
1901 if (!HeapTupleIsValid(rec->tup))
1903 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1904 errmsg("record \"%s\" is not assigned yet",
1906 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
1907 if (!compatible_tupdesc(tupdesc, rec->tupdesc))
1909 (errcode(ERRCODE_DATATYPE_MISMATCH),
1910 errmsg("wrong record type supplied in RETURN NEXT")));
1915 case PLPGSQL_DTYPE_ROW:
1917 PLpgSQL_row *row = (PLpgSQL_row *) retvar;
1919 tuple = make_tuple_from_row(estate, row, tupdesc);
1922 (errcode(ERRCODE_DATATYPE_MISMATCH),
1923 errmsg("wrong record type supplied in RETURN NEXT")));
1929 elog(ERROR, "unrecognized dtype: %d", retvar->dtype);
1930 tuple = NULL; /* keep compiler quiet */
1934 else if (stmt->expr)
1942 (errcode(ERRCODE_DATATYPE_MISMATCH),
1943 errmsg("wrong result type supplied in RETURN NEXT")));
1945 retval = exec_eval_expr(estate,
1950 /* coerce type if needed */
1951 retval = exec_simple_cast_value(retval,
1953 tupdesc->attrs[0]->atttypid,
1954 tupdesc->attrs[0]->atttypmod,
1957 tuple = heap_form_tuple(tupdesc, &retval, &isNull);
1961 exec_eval_cleanup(estate);
1966 (errcode(ERRCODE_SYNTAX_ERROR),
1967 errmsg("RETURN NEXT must have a parameter")));
1968 tuple = NULL; /* keep compiler quiet */
1971 if (HeapTupleIsValid(tuple))
1973 MemoryContext oldcxt;
1975 oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
1976 tuplestore_puttuple(estate->tuple_store, tuple);
1977 MemoryContextSwitchTo(oldcxt);
1980 heap_freetuple(tuple);
1983 return PLPGSQL_RC_OK;
1987 exec_init_tuple_store(PLpgSQL_execstate *estate)
1989 ReturnSetInfo *rsi = estate->rsi;
1990 MemoryContext oldcxt;
1993 * Check caller can handle a set result in the way we want
1995 if (!rsi || !IsA(rsi, ReturnSetInfo) ||
1996 (rsi->allowedModes & SFRM_Materialize) == 0 ||
1997 rsi->expectedDesc == NULL)
1999 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2000 errmsg("set-valued function called in context that cannot accept a set")));
2002 estate->tuple_store_cxt = rsi->econtext->ecxt_per_query_memory;
2004 oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
2005 estate->tuple_store = tuplestore_begin_heap(true, false, work_mem);
2006 MemoryContextSwitchTo(oldcxt);
2008 estate->rettupdesc = rsi->expectedDesc;
2012 * exec_stmt_raise Build a message and throw it with elog()
2016 exec_stmt_raise(PLpgSQL_execstate *estate, PLpgSQL_stmt_raise *stmt)
2020 ListCell *current_param;
2022 plpgsql_dstring_init(&ds);
2023 current_param = list_head(stmt->params);
2025 for (cp = stmt->message; *cp; cp++)
2028 * Occurrences of a single % are replaced by the next parameter's
2029 * external representation. Double %'s are converted to one %.
2040 plpgsql_dstring_append_char(&ds, cp[1]);
2045 if (current_param == NULL)
2047 (errcode(ERRCODE_SYNTAX_ERROR),
2048 errmsg("too few parameters specified for RAISE")));
2050 paramvalue = exec_eval_expr(estate,
2051 (PLpgSQL_expr *) lfirst(current_param),
2058 extval = convert_value_to_string(paramvalue, paramtypeid);
2059 plpgsql_dstring_append(&ds, extval);
2060 current_param = lnext(current_param);
2061 exec_eval_cleanup(estate);
2065 plpgsql_dstring_append_char(&ds, cp[0]);
2069 * If more parameters were specified than were required to process the
2070 * format string, throw an error
2072 if (current_param != NULL)
2074 (errcode(ERRCODE_SYNTAX_ERROR),
2075 errmsg("too many parameters specified for RAISE")));
2078 * Throw the error (may or may not come back)
2080 estate->err_text = raise_skip_msg; /* suppress traceback of raise */
2082 ereport(stmt->elog_level,
2083 ((stmt->elog_level >= ERROR) ? errcode(ERRCODE_RAISE_EXCEPTION) : 0,
2084 errmsg_internal("%s", plpgsql_dstring_get(&ds))));
2086 estate->err_text = NULL; /* un-suppress... */
2088 plpgsql_dstring_free(&ds);
2090 return PLPGSQL_RC_OK;
2095 * Initialize a mostly empty execution state
2099 plpgsql_estate_setup(PLpgSQL_execstate *estate,
2100 PLpgSQL_function *func,
2103 estate->retval = (Datum) 0;
2104 estate->retisnull = true;
2105 estate->rettype = InvalidOid;
2107 estate->fn_rettype = func->fn_rettype;
2108 estate->retistuple = func->fn_retistuple;
2109 estate->retisset = func->fn_retset;
2111 estate->readonly_func = func->fn_readonly;
2113 estate->rettupdesc = NULL;
2114 estate->exitlabel = NULL;
2116 estate->tuple_store = NULL;
2117 estate->tuple_store_cxt = NULL;
2120 estate->trig_nargs = 0;
2121 estate->trig_argv = NULL;
2123 estate->found_varno = func->found_varno;
2124 estate->ndatums = func->ndatums;
2125 estate->datums = palloc(sizeof(PLpgSQL_datum *) * estate->ndatums);
2126 /* caller is expected to fill the datums array */
2128 estate->eval_tuptable = NULL;
2129 estate->eval_processed = 0;
2130 estate->eval_lastoid = InvalidOid;
2132 estate->err_func = func;
2133 estate->err_stmt = NULL;
2134 estate->err_text = NULL;
2137 * Create an EState for evaluation of simple expressions, if there's not
2138 * one already in the current transaction. The EState is made a child of
2139 * TopTransactionContext so it will have the right lifespan.
2141 if (simple_eval_estate == NULL)
2143 MemoryContext oldcontext;
2145 oldcontext = MemoryContextSwitchTo(TopTransactionContext);
2146 simple_eval_estate = CreateExecutorState();
2147 MemoryContextSwitchTo(oldcontext);
2151 * Create an expression context for simple expressions. This must be a
2152 * child of simple_eval_estate.
2154 estate->eval_econtext = CreateExprContext(simple_eval_estate);
2158 * Release temporary memory used by expression/subselect evaluation
2160 * NB: the result of the evaluation is no longer valid after this is done,
2161 * unless it is a pass-by-value datatype.
2165 exec_eval_cleanup(PLpgSQL_execstate *estate)
2167 /* Clear result of a full SPI_execute */
2168 if (estate->eval_tuptable != NULL)
2169 SPI_freetuptable(estate->eval_tuptable);
2170 estate->eval_tuptable = NULL;
2172 /* Clear result of exec_eval_simple_expr (but keep the econtext) */
2173 if (estate->eval_econtext != NULL)
2174 ResetExprContext(estate->eval_econtext);
2179 * Generate a prepared plan
2183 exec_prepare_plan(PLpgSQL_execstate *estate,
2187 _SPI_plan *spi_plan;
2192 * We need a temporary argtypes array to load with data. (The finished
2193 * plan structure will contain a copy of it.)
2195 argtypes = (Oid *) palloc(expr->nparams * sizeof(Oid));
2197 for (i = 0; i < expr->nparams; i++)
2202 exec_eval_datum(estate, estate->datums[expr->params[i]],
2204 &argtypes[i], ¶mval, ¶misnull);
2208 * Generate and save the plan
2210 plan = SPI_prepare(expr->query, expr->nparams, argtypes);
2213 /* Some SPI errors deserve specific error messages */
2216 case SPI_ERROR_COPY:
2218 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2219 errmsg("cannot COPY to/from client in PL/pgSQL")));
2220 case SPI_ERROR_CURSOR:
2222 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2223 errmsg("cannot manipulate cursors directly in PL/pgSQL"),
2224 errhint("Use PL/pgSQL's cursor features instead.")));
2225 case SPI_ERROR_TRANSACTION:
2227 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2228 errmsg("cannot begin/end transactions in PL/pgSQL"),
2229 errhint("Use a BEGIN block with an EXCEPTION clause instead.")));
2231 elog(ERROR, "SPI_prepare failed for \"%s\": %s",
2232 expr->query, SPI_result_code_string(SPI_result));
2235 expr->plan = SPI_saveplan(plan);
2236 spi_plan = (_SPI_plan *) expr->plan;
2237 expr->plan_argtypes = spi_plan->argtypes;
2238 expr->expr_simple_expr = NULL;
2239 exec_simple_check_plan(expr);
2247 * exec_stmt_execsql Execute an SQL statement not
2248 * returning any data.
2252 exec_stmt_execsql(PLpgSQL_execstate *estate,
2253 PLpgSQL_stmt_execsql *stmt)
2259 PLpgSQL_expr *expr = stmt->sqlstmt;
2262 * On the first call for this expression generate the plan
2264 if (expr->plan == NULL)
2265 exec_prepare_plan(estate, expr);
2268 * Now build up the values and nulls arguments for SPI_execute_plan()
2270 values = (Datum *) palloc(expr->nparams * sizeof(Datum));
2271 nulls = (char *) palloc(expr->nparams * sizeof(char));
2273 for (i = 0; i < expr->nparams; i++)
2275 PLpgSQL_datum *datum = estate->datums[expr->params[i]];
2279 exec_eval_datum(estate, datum, expr->plan_argtypes[i],
2280 ¶mtypeid, &values[i], ¶misnull);
2290 rc = SPI_execute_plan(expr->plan, values, nulls,
2291 estate->readonly_func, 0);
2294 case SPI_OK_UTILITY:
2295 case SPI_OK_SELINTO:
2303 * If the INSERT, DELETE, or UPDATE query affected at least one
2304 * tuple, set the magic 'FOUND' variable to true. This conforms
2305 * with the behavior of PL/SQL.
2307 exec_set_found(estate, (SPI_processed != 0));
2312 (errcode(ERRCODE_SYNTAX_ERROR),
2313 errmsg("SELECT query has no destination for result data"),
2314 errhint("If you want to discard the results, use PERFORM instead.")));
2317 elog(ERROR, "SPI_execute_plan failed executing query \"%s\": %s",
2318 expr->query, SPI_result_code_string(rc));
2322 * Release any result tuples from SPI_execute_plan (probably shouldn't be
2325 SPI_freetuptable(SPI_tuptable);
2327 /* Save result info for GET DIAGNOSTICS */
2328 estate->eval_processed = SPI_processed;
2329 estate->eval_lastoid = SPI_lastoid;
2334 return PLPGSQL_RC_OK;
2339 * exec_stmt_dynexecute Execute a dynamic SQL query not
2340 * returning any data.
2344 exec_stmt_dynexecute(PLpgSQL_execstate *estate,
2345 PLpgSQL_stmt_dynexecute *stmt)
2348 bool isnull = false;
2352 PLpgSQL_rec *rec = NULL;
2353 PLpgSQL_row *row = NULL;
2355 if (stmt->rec != NULL)
2356 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
2357 else if (stmt->row != NULL)
2358 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
2361 * First we evaluate the string expression after the EXECUTE keyword. It's
2362 * result is the querystring we have to execute.
2364 query = exec_eval_expr(estate, stmt->query, &isnull, &restype);
2367 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2368 errmsg("cannot EXECUTE a null querystring")));
2370 /* Get the C-String representation */
2371 querystr = convert_value_to_string(query, restype);
2373 exec_eval_cleanup(estate);
2376 * Call SPI_execute() without preparing a saved plan. The returncode can
2377 * be any standard OK. Note that while a SELECT is allowed, its results
2378 * will be discarded unless an INTO clause is specified.
2380 exec_res = SPI_execute(querystr, estate->readonly_func, 0);
2382 /* Assign to INTO variable */
2385 if (exec_res != SPI_OK_SELECT)
2387 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2388 errmsg("EXECUTE ... INTO is only for SELECT")));
2391 if (SPI_processed == 0)
2392 exec_move_row(estate, rec, row, NULL, SPI_tuptable->tupdesc);
2394 exec_move_row(estate, rec, row,
2395 SPI_tuptable->vals[0], SPI_tuptable->tupdesc);
2405 case SPI_OK_UTILITY:
2411 * Also allow a zero return, which implies the querystring
2412 * contained no commands.
2416 case SPI_OK_SELINTO:
2419 * We want to disallow SELECT INTO for now, because its behavior
2420 * is not consistent with SELECT INTO in a normal plpgsql context.
2421 * (We need to reimplement EXECUTE to parse the string as a
2422 * plpgsql command, not just feed it to SPI_execute.) However,
2423 * CREATE AS should be allowed ... and since it produces the same
2424 * parsetree as SELECT INTO, there's no way to tell the difference
2425 * except to look at the source text. Wotta kluge!
2430 for (ptr = querystr; *ptr; ptr++)
2431 if (!isspace((unsigned char) *ptr))
2433 if (*ptr == 'S' || *ptr == 's')
2435 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2436 errmsg("EXECUTE of SELECT ... INTO is not implemented yet")));
2440 /* Some SPI errors deserve specific error messages */
2441 case SPI_ERROR_COPY:
2443 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2444 errmsg("cannot COPY to/from client in PL/pgSQL")));
2445 case SPI_ERROR_CURSOR:
2447 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2448 errmsg("cannot manipulate cursors directly in PL/pgSQL"),
2449 errhint("Use PL/pgSQL's cursor features instead.")));
2450 case SPI_ERROR_TRANSACTION:
2452 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2453 errmsg("cannot begin/end transactions in PL/pgSQL"),
2454 errhint("Use a BEGIN block with an EXCEPTION clause instead.")));
2457 elog(ERROR, "SPI_execute failed executing query \"%s\": %s",
2458 querystr, SPI_result_code_string(exec_res));
2462 /* Release any result from SPI_execute, as well as the querystring */
2463 SPI_freetuptable(SPI_tuptable);
2466 /* Save result info for GET DIAGNOSTICS */
2467 estate->eval_processed = SPI_processed;
2468 estate->eval_lastoid = SPI_lastoid;
2470 return PLPGSQL_RC_OK;
2475 * exec_stmt_dynfors Execute a dynamic query, assign each
2476 * tuple to a record or row and
2477 * execute a group of statements
2482 exec_stmt_dynfors(PLpgSQL_execstate *estate, PLpgSQL_stmt_dynfors *stmt)
2488 PLpgSQL_rec *rec = NULL;
2489 PLpgSQL_row *row = NULL;
2490 SPITupleTable *tuptab;
2497 * Determine if we assign to a record or a row
2499 if (stmt->rec != NULL)
2500 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
2501 else if (stmt->row != NULL)
2502 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
2504 elog(ERROR, "unsupported target");
2507 * Evaluate the string expression after the EXECUTE keyword. It's result
2508 * is the querystring we have to execute.
2510 query = exec_eval_expr(estate, stmt->query, &isnull, &restype);
2513 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2514 errmsg("cannot EXECUTE a null querystring")));
2516 /* Get the C-String representation */
2517 querystr = convert_value_to_string(query, restype);
2519 exec_eval_cleanup(estate);
2522 * Prepare a plan and open an implicit cursor for the query
2524 plan = SPI_prepare(querystr, 0, NULL);
2526 elog(ERROR, "SPI_prepare failed for \"%s\": %s",
2527 querystr, SPI_result_code_string(SPI_result));
2528 portal = SPI_cursor_open(NULL, plan, NULL, NULL,
2529 estate->readonly_func);
2531 elog(ERROR, "could not open implicit cursor for query \"%s\": %s",
2532 querystr, SPI_result_code_string(SPI_result));
2537 * Fetch the initial 10 tuples
2539 SPI_cursor_fetch(portal, true, 10);
2540 tuptab = SPI_tuptable;
2544 * If the query didn't return any rows, set the target to NULL and return
2545 * with FOUND = false.
2548 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
2550 found = true; /* processed at least one tuple */
2559 for (i = 0; i < n; i++)
2564 * Assign the tuple to the target
2566 exec_move_row(estate, rec, row, tuptab->vals[i], tuptab->tupdesc);
2569 * Execute the statements
2571 rc = exec_stmts(estate, stmt->body);
2573 if (rc != PLPGSQL_RC_OK)
2575 if (rc == PLPGSQL_RC_EXIT)
2577 if (estate->exitlabel == NULL)
2578 /* unlabelled exit, finish the current loop */
2580 else if (stmt->label != NULL &&
2581 strcmp(stmt->label, estate->exitlabel) == 0)
2583 /* labelled exit, matches the current stmt's label */
2584 estate->exitlabel = NULL;
2589 * otherwise, we processed a labelled exit that does not
2590 * match the current statement's label, if any: return
2591 * RC_EXIT so that the EXIT continues to recurse upward.
2594 else if (rc == PLPGSQL_RC_CONTINUE)
2596 if (estate->exitlabel == NULL)
2597 /* unlabelled continue, continue the current loop */
2599 else if (stmt->label != NULL &&
2600 strcmp(stmt->label, estate->exitlabel) == 0)
2602 /* labelled continue, matches the current stmt's label */
2603 estate->exitlabel = NULL;
2608 * otherwise, we process a labelled continue that does not
2609 * match the current statement's label, so propagate
2610 * RC_CONTINUE upward in the stack.
2615 * We're aborting the loop, so cleanup and set FOUND. (This
2616 * code should match the code after the loop.)
2618 SPI_freetuptable(tuptab);
2619 SPI_cursor_close(portal);
2620 exec_set_found(estate, found);
2626 SPI_freetuptable(tuptab);
2629 * Fetch the next 50 tuples
2631 SPI_cursor_fetch(portal, true, 50);
2633 tuptab = SPI_tuptable;
2637 * Release last group of tuples
2639 SPI_freetuptable(tuptab);
2642 * Close the implicit cursor
2644 SPI_cursor_close(portal);
2647 * Set the FOUND variable to indicate the result of executing the loop
2648 * (namely, whether we looped one or more times). This must be set here so
2649 * that it does not interfere with the value of the FOUND variable inside
2650 * the loop processing itself.
2652 exec_set_found(estate, found);
2654 return PLPGSQL_RC_OK;
2659 * exec_stmt_open Execute an OPEN cursor statement
2663 exec_stmt_open(PLpgSQL_execstate *estate, PLpgSQL_stmt_open *stmt)
2665 PLpgSQL_var *curvar = NULL;
2666 char *curname = NULL;
2667 PLpgSQL_expr *query = NULL;
2676 * Get the cursor variable and if it has an assigned name, check
2677 * that it's not in use currently.
2680 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
2681 if (!curvar->isnull)
2683 curname = DatumGetCString(DirectFunctionCall1(textout, curvar->value));
2684 if (SPI_cursor_find(curname) != NULL)
2686 (errcode(ERRCODE_DUPLICATE_CURSOR),
2687 errmsg("cursor \"%s\" already in use", curname)));
2691 * Process the OPEN according to it's type.
2694 if (stmt->query != NULL)
2697 * This is an OPEN refcursor FOR SELECT ...
2699 * We just make sure the query is planned. The real work is
2703 query = stmt->query;
2704 if (query->plan == NULL)
2705 exec_prepare_plan(estate, query);
2707 else if (stmt->dynquery != NULL)
2710 * This is an OPEN refcursor FOR EXECUTE ...
2719 * We evaluate the string expression after the
2720 * EXECUTE keyword. It's result is the querystring we have
2724 queryD = exec_eval_expr(estate, stmt->dynquery, &isnull, &restype);
2727 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2728 errmsg("cannot EXECUTE a null querystring")));
2730 /* Get the C-String representation */
2731 querystr = convert_value_to_string(queryD, restype);
2733 exec_eval_cleanup(estate);
2736 * Now we prepare a query plan for it and open a cursor
2739 curplan = SPI_prepare(querystr, 0, NULL);
2740 if (curplan == NULL)
2741 elog(ERROR, "SPI_prepare failed for \"%s\": %s",
2742 querystr, SPI_result_code_string(SPI_result));
2743 portal = SPI_cursor_open(curname, curplan, NULL, NULL,
2744 estate->readonly_func);
2746 elog(ERROR, "could not open cursor for query \"%s\": %s",
2747 querystr, SPI_result_code_string(SPI_result));
2749 SPI_freeplan(curplan);
2752 * Store the eventually assigned cursor name in the cursor variable
2756 curvar->value = DirectFunctionCall1(textin, CStringGetDatum(portal->name));
2757 curvar->isnull = false;
2758 curvar->freeval = true;
2760 return PLPGSQL_RC_OK;
2765 * This is an OPEN cursor
2767 * Note: parser should already have checked that statement supplies
2768 * args iff cursor needs them, but we check again to be safe.
2771 if (stmt->argquery != NULL)
2774 * Er - OPEN CURSOR (args). We fake a SELECT ... INTO ...
2775 * statement to evaluate the args and put 'em into the
2779 PLpgSQL_stmt_select set_args;
2781 if (curvar->cursor_explicit_argrow < 0)
2783 (errcode(ERRCODE_SYNTAX_ERROR),
2784 errmsg("arguments given for cursor without arguments")));
2786 memset(&set_args, 0, sizeof(set_args));
2787 set_args.cmd_type = PLPGSQL_STMT_SELECT;
2788 set_args.lineno = stmt->lineno;
2789 set_args.row = (PLpgSQL_row *)
2790 (estate->datums[curvar->cursor_explicit_argrow]);
2791 set_args.query = stmt->argquery;
2793 if (exec_stmt_select(estate, &set_args) != PLPGSQL_RC_OK)
2794 elog(ERROR, "open cursor failed during argument processing");
2798 if (curvar->cursor_explicit_argrow >= 0)
2800 (errcode(ERRCODE_SYNTAX_ERROR),
2801 errmsg("arguments required for cursor")));
2804 query = curvar->cursor_explicit_expr;
2805 if (query->plan == NULL)
2806 exec_prepare_plan(estate, query);
2810 * Here we go if we have a saved plan where we have to put
2811 * values into, either from an explicit cursor or from a
2812 * refcursor opened with OPEN ... FOR SELECT ...;
2815 values = (Datum *) palloc(query->nparams * sizeof(Datum));
2816 nulls = (char *) palloc(query->nparams * sizeof(char));
2818 for (i = 0; i < query->nparams; i++)
2820 PLpgSQL_datum *datum = estate->datums[query->params[i]];
2824 exec_eval_datum(estate, datum, query->plan_argtypes[i],
2825 ¶mtypeid, &values[i], ¶misnull);
2836 portal = SPI_cursor_open(curname, query->plan, values, nulls,
2837 estate->readonly_func);
2839 elog(ERROR, "could not open cursor: %s",
2840 SPI_result_code_string(SPI_result));
2848 * Store the eventually assigned portal name in the cursor variable
2852 curvar->value = DirectFunctionCall1(textin, CStringGetDatum(portal->name));
2853 curvar->isnull = false;
2854 curvar->freeval = true;
2856 return PLPGSQL_RC_OK;
2861 * exec_stmt_fetch Fetch from a cursor into a target
2865 exec_stmt_fetch(PLpgSQL_execstate *estate, PLpgSQL_stmt_fetch *stmt)
2867 PLpgSQL_var *curvar = NULL;
2868 PLpgSQL_rec *rec = NULL;
2869 PLpgSQL_row *row = NULL;
2870 SPITupleTable *tuptab;
2876 * Get the portal of the cursor by name
2879 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
2882 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2883 errmsg("cursor variable \"%s\" is NULL", curvar->refname)));
2884 curname = DatumGetCString(DirectFunctionCall1(textout, curvar->value));
2886 portal = SPI_cursor_find(curname);
2889 (errcode(ERRCODE_UNDEFINED_CURSOR),
2890 errmsg("cursor \"%s\" does not exist", curname)));
2894 * Determine if we fetch into a record or a row
2897 if (stmt->rec != NULL)
2898 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
2899 else if (stmt->row != NULL)
2900 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
2902 elog(ERROR, "unsupported target");
2905 * Fetch 1 tuple from the cursor
2908 SPI_cursor_fetch(portal, true, 1);
2909 tuptab = SPI_tuptable;
2913 * Set the target and the global FOUND variable appropriately.
2918 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
2919 exec_set_found(estate, false);
2923 exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
2924 exec_set_found(estate, true);
2927 SPI_freetuptable(tuptab);
2929 return PLPGSQL_RC_OK;
2934 * exec_stmt_close Close a cursor
2938 exec_stmt_close(PLpgSQL_execstate *estate, PLpgSQL_stmt_close *stmt)
2940 PLpgSQL_var *curvar = NULL;
2945 * Get the portal of the cursor by name
2948 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
2951 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2952 errmsg("cursor variable \"%s\" is NULL", curvar->refname)));
2953 curname = DatumGetCString(DirectFunctionCall1(textout, curvar->value));
2955 portal = SPI_cursor_find(curname);
2958 (errcode(ERRCODE_UNDEFINED_CURSOR),
2959 errmsg("cursor \"%s\" does not exist", curname)));
2966 SPI_cursor_close(portal);
2968 return PLPGSQL_RC_OK;
2973 * exec_assign_expr Put an expression's result into
2978 exec_assign_expr(PLpgSQL_execstate *estate, PLpgSQL_datum *target,
2983 bool isnull = false;
2985 value = exec_eval_expr(estate, expr, &isnull, &valtype);
2986 exec_assign_value(estate, target, value, valtype, &isnull);
2987 exec_eval_cleanup(estate);
2992 * exec_assign_value Put a value into a target field
2996 exec_assign_value(PLpgSQL_execstate *estate,
2997 PLpgSQL_datum *target,
2998 Datum value, Oid valtype, bool *isNull)
3000 switch (target->dtype)
3002 case PLPGSQL_DTYPE_VAR:
3005 * Target is a variable
3007 PLpgSQL_var *var = (PLpgSQL_var *) target;
3010 newvalue = exec_cast_value(value, valtype, var->datatype->typoid,
3011 &(var->datatype->typinput),
3012 var->datatype->typioparam,
3013 var->datatype->atttypmod,
3016 if (*isNull && var->notnull)
3018 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3019 errmsg("NULL cannot be assigned to variable \"%s\" declared NOT NULL",
3023 * If type is by-reference, make sure we have a freshly
3024 * palloc'd copy; the originally passed value may not live as
3025 * long as the variable! But we don't need to re-copy if
3026 * exec_cast_value performed a conversion; its output must
3027 * already be palloc'd.
3029 if (!var->datatype->typbyval && !*isNull)
3031 if (newvalue == value)
3032 newvalue = datumCopy(newvalue,
3034 var->datatype->typlen);
3038 * Now free the old value. (We can't do this any earlier
3039 * because of the possibility that we are assigning the var's
3040 * old value to it, eg "foo := foo". We could optimize out
3041 * the assignment altogether in such cases, but it's too
3042 * infrequent to be worth testing for.)
3046 var->value = newvalue;
3047 var->isnull = *isNull;
3048 if (!var->datatype->typbyval && !*isNull)
3049 var->freeval = true;
3053 case PLPGSQL_DTYPE_ROW:
3056 * Target is a row variable
3058 PLpgSQL_row *row = (PLpgSQL_row *) target;
3060 /* Source must be of RECORD or composite type */
3061 if (!(valtype == RECORDOID ||
3062 get_typtype(valtype) == 'c'))
3064 (errcode(ERRCODE_DATATYPE_MISMATCH),
3065 errmsg("cannot assign non-composite value to a row variable")));
3068 /* If source is null, just assign nulls to the row */
3069 exec_move_row(estate, NULL, row, NULL, NULL);
3077 HeapTupleData tmptup;
3079 /* Else source is a tuple Datum, safe to do this: */
3080 td = DatumGetHeapTupleHeader(value);
3081 /* Extract rowtype info and find a tupdesc */
3082 tupType = HeapTupleHeaderGetTypeId(td);
3083 tupTypmod = HeapTupleHeaderGetTypMod(td);
3084 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
3085 /* Build a temporary HeapTuple control structure */
3086 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
3087 ItemPointerSetInvalid(&(tmptup.t_self));
3088 tmptup.t_tableOid = InvalidOid;
3090 exec_move_row(estate, NULL, row, &tmptup, tupdesc);
3095 case PLPGSQL_DTYPE_REC:
3098 * Target is a record variable
3100 PLpgSQL_rec *rec = (PLpgSQL_rec *) target;
3102 /* Source must be of RECORD or composite type */
3103 if (!(valtype == RECORDOID ||
3104 get_typtype(valtype) == 'c'))
3106 (errcode(ERRCODE_DATATYPE_MISMATCH),
3107 errmsg("cannot assign non-composite value to a record variable")));
3110 /* If source is null, just assign nulls to the record */
3111 exec_move_row(estate, rec, NULL, NULL, NULL);
3119 HeapTupleData tmptup;
3121 /* Else source is a tuple Datum, safe to do this: */
3122 td = DatumGetHeapTupleHeader(value);
3123 /* Extract rowtype info and find a tupdesc */
3124 tupType = HeapTupleHeaderGetTypeId(td);
3125 tupTypmod = HeapTupleHeaderGetTypMod(td);
3126 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
3127 /* Build a temporary HeapTuple control structure */
3128 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
3129 ItemPointerSetInvalid(&(tmptup.t_self));
3130 tmptup.t_tableOid = InvalidOid;
3132 exec_move_row(estate, rec, NULL, &tmptup, tupdesc);
3137 case PLPGSQL_DTYPE_RECFIELD:
3140 * Target is a field of a record
3142 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) target;
3155 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
3158 * Check that there is already a tuple in the record. We need
3159 * that because records don't have any predefined field
3162 if (!HeapTupleIsValid(rec->tup))
3164 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3165 errmsg("record \"%s\" is not assigned yet",
3167 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
3170 * Get the number of the records field to change and the
3171 * number of attributes in the tuple.
3173 fno = SPI_fnumber(rec->tupdesc, recfield->fieldname);
3174 if (fno == SPI_ERROR_NOATTRIBUTE)
3176 (errcode(ERRCODE_UNDEFINED_COLUMN),
3177 errmsg("record \"%s\" has no field \"%s\"",
3178 rec->refname, recfield->fieldname)));
3180 natts = rec->tupdesc->natts;
3183 * Set up values/datums arrays for heap_formtuple. For all
3184 * the attributes except the one we want to replace, use the
3185 * value that's in the old tuple.
3187 values = palloc(sizeof(Datum) * natts);
3188 nulls = palloc(natts);
3190 for (i = 0; i < natts; i++)
3194 values[i] = SPI_getbinval(rec->tup, rec->tupdesc,
3203 * Now insert the new value, being careful to cast it to the
3206 atttype = SPI_gettypeid(rec->tupdesc, fno + 1);
3207 atttypmod = rec->tupdesc->attrs[fno]->atttypmod;
3208 attisnull = *isNull;
3209 values[fno] = exec_simple_cast_value(value,
3220 * Avoid leaking the result of exec_simple_cast_value, if it
3221 * performed a conversion to a pass-by-ref type.
3223 if (!attisnull && values[fno] != value && !get_typbyval(atttype))
3224 mustfree = DatumGetPointer(values[fno]);
3229 * Now call heap_formtuple() to create a new tuple that
3230 * replaces the old one in the record.
3232 newtup = heap_formtuple(rec->tupdesc, values, nulls);
3235 heap_freetuple(rec->tup);
3238 rec->freetup = true;
3248 case PLPGSQL_DTYPE_ARRAYELEM:
3252 PLpgSQL_expr *subscripts[MAXDIM];
3253 int subscriptvals[MAXDIM];
3254 bool oldarrayisnull;
3261 Datum oldarraydatum,
3263 ArrayType *oldarrayval;
3264 ArrayType *newarrayval;
3267 * Target is an element of an array
3269 * To handle constructs like x[1][2] := something, we have to
3270 * be prepared to deal with a chain of arrayelem datums. Chase
3271 * back to find the base array datum, and save the subscript
3272 * expressions as we go. (We are scanning right to left here,
3273 * but want to evaluate the subscripts left-to-right to
3274 * minimize surprises.)
3279 PLpgSQL_arrayelem *arrayelem = (PLpgSQL_arrayelem *) target;
3281 if (nsubscripts >= MAXDIM)
3283 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
3284 errmsg("number of array dimensions exceeds the maximum allowed, %d",
3286 subscripts[nsubscripts++] = arrayelem->subscript;
3287 target = estate->datums[arrayelem->arrayparentno];
3288 } while (target->dtype == PLPGSQL_DTYPE_ARRAYELEM);
3290 /* Fetch current value of array datum */
3291 exec_eval_datum(estate, target, InvalidOid,
3292 &arraytypeid, &oldarraydatum, &oldarrayisnull);
3294 arrayelemtypeid = get_element_type(arraytypeid);
3295 if (!OidIsValid(arrayelemtypeid))
3297 (errcode(ERRCODE_DATATYPE_MISMATCH),
3298 errmsg("subscripted object is not an array")));
3300 get_typlenbyvalalign(arrayelemtypeid,
3304 arraytyplen = get_typlen(arraytypeid);
3307 * Evaluate the subscripts, switch into left-to-right order.
3308 * Like ExecEvalArrayRef(), complain if any subscript is null.
3310 for (i = 0; i < nsubscripts; i++)
3315 exec_eval_integer(estate,
3316 subscripts[nsubscripts - 1 - i],
3320 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3321 errmsg("array subscript in assignment must not be NULL")));
3324 /* Coerce source value to match array element type. */
3325 coerced_value = exec_simple_cast_value(value,
3332 * If the original array is null, cons up an empty array so
3333 * that the assignment can proceed; we'll end with a
3334 * one-element array containing just the assigned-to
3335 * subscript. This only works for varlena arrays, though; for
3336 * fixed-length array types we skip the assignment. We can't
3337 * support assignment of a null entry into a fixed-length
3338 * array, either, so that's a no-op too. This is all ugly but
3339 * corresponds to the current behavior of ExecEvalArrayRef().
3341 if (arraytyplen > 0 && /* fixed-length array? */
3342 (oldarrayisnull || *isNull))
3346 oldarrayval = construct_empty_array(arrayelemtypeid);
3348 oldarrayval = (ArrayType *) DatumGetPointer(oldarraydatum);
3351 * Build the modified array value.
3353 newarrayval = array_set(oldarrayval,
3364 * Avoid leaking the result of exec_simple_cast_value, if it
3365 * performed a conversion to a pass-by-ref type.
3367 if (!*isNull && coerced_value != value && !elemtypbyval)
3368 pfree(DatumGetPointer(coerced_value));
3371 * Assign the new array to the base variable. It's never NULL
3375 exec_assign_value(estate, target,
3376 PointerGetDatum(newarrayval),
3377 arraytypeid, isNull);
3380 * Avoid leaking the modified array value, too.
3387 elog(ERROR, "unrecognized dtype: %d", target->dtype);
3392 * exec_eval_datum Get current value of a PLpgSQL_datum
3394 * The type oid, value in Datum format, and null flag are returned.
3396 * If expectedtypeid isn't InvalidOid, it is checked against the actual type.
3398 * At present this doesn't handle PLpgSQL_expr or PLpgSQL_arrayelem datums.
3400 * NOTE: caller must not modify the returned value, since it points right
3401 * at the stored value in the case of pass-by-reference datatypes. In some
3402 * cases we have to palloc a return value, and in such cases we put it into
3403 * the estate's short-term memory context.
3406 exec_eval_datum(PLpgSQL_execstate *estate,
3407 PLpgSQL_datum *datum,
3413 MemoryContext oldcontext;
3415 switch (datum->dtype)
3417 case PLPGSQL_DTYPE_VAR:
3419 PLpgSQL_var *var = (PLpgSQL_var *) datum;
3421 *typeid = var->datatype->typoid;
3422 *value = var->value;
3423 *isnull = var->isnull;
3424 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3426 (errcode(ERRCODE_DATATYPE_MISMATCH),
3427 errmsg("type of \"%s\" does not match that when preparing the plan",
3432 case PLPGSQL_DTYPE_ROW:
3434 PLpgSQL_row *row = (PLpgSQL_row *) datum;
3437 if (!row->rowtupdesc) /* should not happen */
3438 elog(ERROR, "row variable has no tupdesc");
3439 /* Make sure we have a valid type/typmod setting */
3440 BlessTupleDesc(row->rowtupdesc);
3441 oldcontext = MemoryContextSwitchTo(estate->eval_econtext->ecxt_per_tuple_memory);
3442 tup = make_tuple_from_row(estate, row, row->rowtupdesc);
3443 if (tup == NULL) /* should not happen */
3444 elog(ERROR, "row not compatible with its own tupdesc");
3445 MemoryContextSwitchTo(oldcontext);
3446 *typeid = row->rowtupdesc->tdtypeid;
3447 *value = HeapTupleGetDatum(tup);
3449 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3451 (errcode(ERRCODE_DATATYPE_MISMATCH),
3452 errmsg("type of \"%s\" does not match that when preparing the plan",
3457 case PLPGSQL_DTYPE_REC:
3459 PLpgSQL_rec *rec = (PLpgSQL_rec *) datum;
3460 HeapTupleData worktup;
3462 if (!HeapTupleIsValid(rec->tup))
3464 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3465 errmsg("record \"%s\" is not assigned yet",
3467 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
3468 Assert(rec->tupdesc != NULL);
3469 /* Make sure we have a valid type/typmod setting */
3470 BlessTupleDesc(rec->tupdesc);
3473 * In a trigger, the NEW and OLD parameters are likely to be
3474 * on-disk tuples that don't have the desired Datum fields.
3475 * Copy the tuple body and insert the right values.
3477 oldcontext = MemoryContextSwitchTo(estate->eval_econtext->ecxt_per_tuple_memory);
3478 heap_copytuple_with_tuple(rec->tup, &worktup);
3479 HeapTupleHeaderSetDatumLength(worktup.t_data, worktup.t_len);
3480 HeapTupleHeaderSetTypeId(worktup.t_data, rec->tupdesc->tdtypeid);
3481 HeapTupleHeaderSetTypMod(worktup.t_data, rec->tupdesc->tdtypmod);
3482 MemoryContextSwitchTo(oldcontext);
3483 *typeid = rec->tupdesc->tdtypeid;
3484 *value = HeapTupleGetDatum(&worktup);
3486 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3488 (errcode(ERRCODE_DATATYPE_MISMATCH),
3489 errmsg("type of \"%s\" does not match that when preparing the plan",
3494 case PLPGSQL_DTYPE_RECFIELD:
3496 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) datum;
3500 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
3501 if (!HeapTupleIsValid(rec->tup))
3503 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3504 errmsg("record \"%s\" is not assigned yet",
3506 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
3507 fno = SPI_fnumber(rec->tupdesc, recfield->fieldname);
3508 if (fno == SPI_ERROR_NOATTRIBUTE)
3510 (errcode(ERRCODE_UNDEFINED_COLUMN),
3511 errmsg("record \"%s\" has no field \"%s\"",
3512 rec->refname, recfield->fieldname)));
3513 *typeid = SPI_gettypeid(rec->tupdesc, fno);
3514 *value = SPI_getbinval(rec->tup, rec->tupdesc, fno, isnull);
3515 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3517 (errcode(ERRCODE_DATATYPE_MISMATCH),
3518 errmsg("type of \"%s.%s\" does not match that when preparing the plan",
3519 rec->refname, recfield->fieldname)));
3523 case PLPGSQL_DTYPE_TRIGARG:
3525 PLpgSQL_trigarg *trigarg = (PLpgSQL_trigarg *) datum;
3529 tgargno = exec_eval_integer(estate, trigarg->argnum, isnull);
3530 if (*isnull || tgargno < 0 || tgargno >= estate->trig_nargs)
3537 *value = estate->trig_argv[tgargno];
3540 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3542 (errcode(ERRCODE_DATATYPE_MISMATCH),
3543 errmsg("type of tgargv[%d] does not match that when preparing the plan",
3549 elog(ERROR, "unrecognized dtype: %d", datum->dtype);
3554 * exec_eval_integer Evaluate an expression, coerce result to int4
3556 * Note we do not do exec_eval_cleanup here; the caller must do it at
3557 * some later point. (We do this because the caller may be holding the
3558 * results of other, pass-by-reference, expression evaluations, such as
3559 * an array value to be subscripted. Also see notes in exec_eval_simple_expr
3560 * about allocation of the parameter array.)
3564 exec_eval_integer(PLpgSQL_execstate *estate,
3571 exprdatum = exec_eval_expr(estate, expr, isNull, &exprtypeid);
3572 exprdatum = exec_simple_cast_value(exprdatum, exprtypeid,
3575 return DatumGetInt32(exprdatum);
3579 * exec_eval_boolean Evaluate an expression, coerce result to bool
3581 * Note we do not do exec_eval_cleanup here; the caller must do it at
3586 exec_eval_boolean(PLpgSQL_execstate *estate,
3593 exprdatum = exec_eval_expr(estate, expr, isNull, &exprtypeid);
3594 exprdatum = exec_simple_cast_value(exprdatum, exprtypeid,
3597 return DatumGetBool(exprdatum);
3601 * exec_eval_expr Evaluate an expression and return
3604 * NOTE: caller must do exec_eval_cleanup when done with the Datum.
3608 exec_eval_expr(PLpgSQL_execstate *estate,
3616 * If not already done create a plan for this expression
3618 if (expr->plan == NULL)
3619 exec_prepare_plan(estate, expr);
3622 * If this is a simple expression, bypass SPI and use the executor
3625 if (expr->expr_simple_expr != NULL)
3626 return exec_eval_simple_expr(estate, expr, isNull, rettype);
3628 rc = exec_run_select(estate, expr, 2, NULL);
3629 if (rc != SPI_OK_SELECT)
3631 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3632 errmsg("query \"%s\" did not return data", expr->query)));
3635 * If there are no rows selected, the result is NULL.
3637 if (estate->eval_processed == 0)
3644 * Check that the expression returned one single Datum
3646 if (estate->eval_processed > 1)
3648 (errcode(ERRCODE_CARDINALITY_VIOLATION),
3649 errmsg("query \"%s\" returned more than one row",
3651 if (estate->eval_tuptable->tupdesc->natts != 1)
3653 (errcode(ERRCODE_SYNTAX_ERROR),
3654 errmsg("query \"%s\" returned %d columns", expr->query,
3655 estate->eval_tuptable->tupdesc->natts)));
3658 * Return the result and its type
3660 *rettype = SPI_gettypeid(estate->eval_tuptable->tupdesc, 1);
3661 return SPI_getbinval(estate->eval_tuptable->vals[0],
3662 estate->eval_tuptable->tupdesc, 1, isNull);
3667 * exec_run_select Execute a select query
3671 exec_run_select(PLpgSQL_execstate *estate,
3672 PLpgSQL_expr *expr, long maxtuples, Portal *portalP)
3680 * On the first call for this expression generate the plan
3682 if (expr->plan == NULL)
3683 exec_prepare_plan(estate, expr);
3686 * Now build up the values and nulls arguments for SPI_execute_plan()
3688 values = (Datum *) palloc(expr->nparams * sizeof(Datum));
3689 nulls = (char *) palloc(expr->nparams * sizeof(char));
3691 for (i = 0; i < expr->nparams; i++)
3693 PLpgSQL_datum *datum = estate->datums[expr->params[i]];
3697 exec_eval_datum(estate, datum, expr->plan_argtypes[i],
3698 ¶mtypeid, &values[i], ¶misnull);
3706 * If a portal was requested, put the query into the portal
3708 if (portalP != NULL)
3710 *portalP = SPI_cursor_open(NULL, expr->plan, values, nulls,
3711 estate->readonly_func);
3712 if (*portalP == NULL)
3713 elog(ERROR, "could not open implicit cursor for query \"%s\": %s",
3714 expr->query, SPI_result_code_string(SPI_result));
3717 return SPI_OK_CURSOR;
3723 rc = SPI_execute_plan(expr->plan, values, nulls,
3724 estate->readonly_func, maxtuples);
3725 if (rc != SPI_OK_SELECT)
3727 (errcode(ERRCODE_SYNTAX_ERROR),
3728 errmsg("query \"%s\" is not a SELECT", expr->query)));
3730 /* Save query results for eventual cleanup */
3731 Assert(estate->eval_tuptable == NULL);
3732 estate->eval_tuptable = SPI_tuptable;
3733 estate->eval_processed = SPI_processed;
3734 estate->eval_lastoid = SPI_lastoid;
3744 * exec_eval_simple_expr - Evaluate a simple expression returning
3745 * a Datum by directly calling ExecEvalExpr().
3747 * Note: if pass-by-reference, the result is in the eval_econtext's
3748 * temporary memory context. It will be freed when exec_eval_cleanup
3753 exec_eval_simple_expr(PLpgSQL_execstate *estate,
3759 ExprContext *econtext = estate->eval_econtext;
3760 TransactionId curxid = GetTopTransactionId();
3761 ParamListInfo paramLI;
3763 Snapshot saveActiveSnapshot;
3766 * Pass back previously-determined result type.
3768 *rettype = expr->expr_simple_type;
3771 * Prepare the expression for execution, if it's not been done already in
3772 * the current transaction.
3774 if (expr->expr_simple_xid != curxid)
3776 expr->expr_simple_state = ExecPrepareExpr(expr->expr_simple_expr,
3777 simple_eval_estate);
3778 expr->expr_simple_xid = curxid;
3782 * Param list can live in econtext's temporary memory context.
3784 * XXX think about avoiding repeated palloc's for param lists? Beware
3785 * however that this routine is re-entrant: exec_eval_datum() can call it
3786 * back for subscript evaluation, and so there can be a need to have more
3787 * than one active param list.
3789 if (expr->nparams > 0)
3791 /* sizeof(ParamListInfoData) includes the first array element */
3792 paramLI = (ParamListInfo)
3793 MemoryContextAlloc(econtext->ecxt_per_tuple_memory,
3794 sizeof(ParamListInfoData) +
3795 (expr->nparams - 1) * sizeof(ParamExternData));
3796 paramLI->numParams = expr->nparams;
3798 for (i = 0; i < expr->nparams; i++)
3800 ParamExternData *prm = ¶mLI->params[i];
3801 PLpgSQL_datum *datum = estate->datums[expr->params[i]];
3803 exec_eval_datum(estate, datum, expr->plan_argtypes[i],
3805 &prm->value, &prm->isnull);
3812 * Now we can safely make the econtext point to the param list.
3814 econtext->ecxt_param_list_info = paramLI;
3817 * We have to do some of the things SPI_execute_plan would do, in
3818 * particular advance the snapshot if we are in a non-read-only function.
3819 * Without this, stable functions within the expression would fail to see
3820 * updates made so far by our own function.
3823 saveActiveSnapshot = ActiveSnapshot;
3827 MemoryContext oldcontext;
3829 oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
3830 if (!estate->readonly_func)
3832 CommandCounterIncrement();
3833 ActiveSnapshot = CopySnapshot(GetTransactionSnapshot());
3837 * Finally we can call the executor to evaluate the expression
3839 retval = ExecEvalExpr(expr->expr_simple_state,
3843 MemoryContextSwitchTo(oldcontext);
3847 /* Restore global vars and propagate error */
3848 ActiveSnapshot = saveActiveSnapshot;
3853 ActiveSnapshot = saveActiveSnapshot;
3864 * exec_move_row Move one tuple's values into a record or row
3868 exec_move_row(PLpgSQL_execstate *estate,
3871 HeapTuple tup, TupleDesc tupdesc)
3874 * Record is simple - just copy the tuple and its descriptor into the
3880 * copy input first, just in case it is pointing at variable's value
3882 if (HeapTupleIsValid(tup))
3883 tup = heap_copytuple(tup);
3885 tupdesc = CreateTupleDescCopy(tupdesc);
3889 heap_freetuple(rec->tup);
3890 rec->freetup = false;
3892 if (rec->freetupdesc)
3894 FreeTupleDesc(rec->tupdesc);
3895 rec->freetupdesc = false;
3898 if (HeapTupleIsValid(tup))
3901 rec->freetup = true;
3905 /* If we have a tupdesc but no data, form an all-nulls tuple */
3908 nulls = (char *) palloc(tupdesc->natts * sizeof(char));
3909 memset(nulls, 'n', tupdesc->natts * sizeof(char));
3911 rec->tup = heap_formtuple(tupdesc, NULL, nulls);
3912 rec->freetup = true;
3921 rec->tupdesc = tupdesc;
3922 rec->freetupdesc = true;
3925 rec->tupdesc = NULL;
3931 * Row is a bit more complicated in that we assign the individual
3932 * attributes of the tuple to the variables the row points to.
3934 * NOTE: this code used to demand row->nfields == tup->t_data->t_natts,
3935 * but that's wrong. The tuple might have more fields than we expected if
3936 * it's from an inheritance-child table of the current table, or it might
3937 * have fewer if the table has had columns added by ALTER TABLE. Ignore
3938 * extra columns and assume NULL for missing columns, the same as
3939 * heap_getattr would do. We also have to skip over dropped columns in
3940 * either the source or destination.
3942 * If we have no tuple data at all, we'll assign NULL to all columns of
3951 if (HeapTupleIsValid(tup))
3952 t_natts = tup->t_data->t_natts;
3957 for (fnum = 0; fnum < row->nfields; fnum++)
3964 if (row->varnos[fnum] < 0)
3965 continue; /* skip dropped column in row struct */
3967 var = (PLpgSQL_var *) (estate->datums[row->varnos[fnum]]);
3969 while (anum < t_natts && tupdesc->attrs[anum]->attisdropped)
3970 anum++; /* skip dropped column in tuple */
3974 value = SPI_getbinval(tup, tupdesc, anum + 1, &isnull);
3975 valtype = SPI_gettypeid(tupdesc, anum + 1);
3982 valtype = InvalidOid;
3985 exec_assign_value(estate, (PLpgSQL_datum *) var,
3986 value, valtype, &isnull);
3992 elog(ERROR, "unsupported target");
3996 * make_tuple_from_row Make a tuple from the values of a row object
3998 * A NULL return indicates rowtype mismatch; caller must raise suitable error
4002 make_tuple_from_row(PLpgSQL_execstate *estate,
4006 int natts = tupdesc->natts;
4012 if (natts != row->nfields)
4015 dvalues = (Datum *) palloc0(natts * sizeof(Datum));
4016 nulls = (bool *) palloc(natts * sizeof(bool));
4018 for (i = 0; i < natts; i++)
4022 if (tupdesc->attrs[i]->attisdropped)
4024 nulls[i] = true; /* leave the column as null */
4027 if (row->varnos[i] < 0) /* should not happen */
4028 elog(ERROR, "dropped rowtype entry for non-dropped column");
4030 exec_eval_datum(estate, estate->datums[row->varnos[i]],
4031 InvalidOid, &fieldtypeid, &dvalues[i], &nulls[i]);
4032 if (fieldtypeid != tupdesc->attrs[i]->atttypid)
4036 tuple = heap_form_tuple(tupdesc, dvalues, nulls);
4045 * convert_value_to_string Convert a non-null Datum to C string
4047 * Note: callers generally assume that the result is a palloc'd string and
4048 * should be pfree'd. This is not all that safe an assumption ...
4050 * Note: not caching the conversion function lookup is bad for performance.
4054 convert_value_to_string(Datum value, Oid valtype)
4059 getTypeOutputInfo(valtype, &typoutput, &typIsVarlena);
4061 return OidOutputFunctionCall(typoutput, value);
4065 * exec_cast_value Cast a value if required
4069 exec_cast_value(Datum value, Oid valtype,
4077 * If the type of the queries return value isn't that of the variable,
4080 if (valtype != reqtype || reqtypmod != -1)
4086 extval = convert_value_to_string(value, valtype);
4087 value = InputFunctionCall(reqinput, extval,
4088 reqtypioparam, reqtypmod);
4093 value = InputFunctionCall(reqinput, NULL,
4094 reqtypioparam, reqtypmod);
4102 * exec_simple_cast_value Cast a value if required
4104 * As above, but need not supply details about target type. Note that this
4105 * is slower than exec_cast_value with cached type info, and so should be
4106 * avoided in heavily used code paths.
4110 exec_simple_cast_value(Datum value, Oid valtype,
4111 Oid reqtype, int32 reqtypmod,
4116 if (valtype != reqtype || reqtypmod != -1)
4120 FmgrInfo finfo_input;
4122 getTypeInputInfo(reqtype, &typinput, &typioparam);
4124 fmgr_info(typinput, &finfo_input);
4126 value = exec_cast_value(value,
4141 * exec_simple_check_node - Recursively check if an expression
4142 * is made only of simple things we can
4143 * hand out directly to ExecEvalExpr()
4144 * instead of calling SPI.
4148 exec_simple_check_node(Node *node)
4153 switch (nodeTag(node))
4163 ArrayRef *expr = (ArrayRef *) node;
4165 if (!exec_simple_check_node((Node *) expr->refupperindexpr))
4167 if (!exec_simple_check_node((Node *) expr->reflowerindexpr))
4169 if (!exec_simple_check_node((Node *) expr->refexpr))
4171 if (!exec_simple_check_node((Node *) expr->refassgnexpr))
4179 FuncExpr *expr = (FuncExpr *) node;
4181 if (expr->funcretset)
4183 if (!exec_simple_check_node((Node *) expr->args))
4191 OpExpr *expr = (OpExpr *) node;
4195 if (!exec_simple_check_node((Node *) expr->args))
4201 case T_DistinctExpr:
4203 DistinctExpr *expr = (DistinctExpr *) node;
4207 if (!exec_simple_check_node((Node *) expr->args))
4213 case T_ScalarArrayOpExpr:
4215 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
4217 if (!exec_simple_check_node((Node *) expr->args))
4225 BoolExpr *expr = (BoolExpr *) node;
4227 if (!exec_simple_check_node((Node *) expr->args))
4234 return exec_simple_check_node((Node *) ((FieldSelect *) node)->arg);
4238 FieldStore *expr = (FieldStore *) node;
4240 if (!exec_simple_check_node((Node *) expr->arg))
4242 if (!exec_simple_check_node((Node *) expr->newvals))
4249 return exec_simple_check_node((Node *) ((RelabelType *) node)->arg);
4251 case T_ConvertRowtypeExpr:
4252 return exec_simple_check_node((Node *) ((ConvertRowtypeExpr *) node)->arg);
4256 CaseExpr *expr = (CaseExpr *) node;
4258 if (!exec_simple_check_node((Node *) expr->arg))
4260 if (!exec_simple_check_node((Node *) expr->args))
4262 if (!exec_simple_check_node((Node *) expr->defresult))
4270 CaseWhen *when = (CaseWhen *) node;
4272 if (!exec_simple_check_node((Node *) when->expr))
4274 if (!exec_simple_check_node((Node *) when->result))
4280 case T_CaseTestExpr:
4285 ArrayExpr *expr = (ArrayExpr *) node;
4287 if (!exec_simple_check_node((Node *) expr->elements))
4295 RowExpr *expr = (RowExpr *) node;
4297 if (!exec_simple_check_node((Node *) expr->args))
4303 case T_RowCompareExpr:
4305 RowCompareExpr *expr = (RowCompareExpr *) node;
4307 if (!exec_simple_check_node((Node *) expr->largs))
4309 if (!exec_simple_check_node((Node *) expr->rargs))
4315 case T_CoalesceExpr:
4317 CoalesceExpr *expr = (CoalesceExpr *) node;
4319 if (!exec_simple_check_node((Node *) expr->args))
4327 MinMaxExpr *expr = (MinMaxExpr *) node;
4329 if (!exec_simple_check_node((Node *) expr->args))
4337 NullIfExpr *expr = (NullIfExpr *) node;
4341 if (!exec_simple_check_node((Node *) expr->args))
4348 return exec_simple_check_node((Node *) ((NullTest *) node)->arg);
4351 return exec_simple_check_node((Node *) ((BooleanTest *) node)->arg);
4353 case T_CoerceToDomain:
4354 return exec_simple_check_node((Node *) ((CoerceToDomain *) node)->arg);
4356 case T_CoerceToDomainValue:
4361 List *expr = (List *) node;
4366 if (!exec_simple_check_node(lfirst(l)))
4380 * exec_simple_check_plan - Check if a plan is simple enough to
4381 * be evaluated by ExecEvalExpr() instead
4386 exec_simple_check_plan(PLpgSQL_expr *expr)
4388 _SPI_plan *spi_plan = (_SPI_plan *) expr->plan;
4392 expr->expr_simple_expr = NULL;
4395 * 1. We can only evaluate queries that resulted in one single execution
4398 if (list_length(spi_plan->ptlist) != 1)
4401 plan = (Plan *) linitial(spi_plan->ptlist);
4404 * 2. It must be a RESULT plan --> no scan's required
4406 if (plan == NULL) /* utility statement produces this */
4409 if (!IsA(plan, Result))
4413 * 3. Can't have any subplan or qual clause, either
4415 if (plan->lefttree != NULL ||
4416 plan->righttree != NULL ||
4417 plan->initPlan != NULL ||
4418 plan->qual != NULL ||
4419 ((Result *) plan)->resconstantqual != NULL)
4423 * 4. The plan must have a single attribute as result
4425 if (list_length(plan->targetlist) != 1)
4428 tle = (TargetEntry *) linitial(plan->targetlist);
4431 * 5. Check that all the nodes in the expression are non-scary.
4433 if (!exec_simple_check_node((Node *) tle->expr))
4437 * Yes - this is a simple expression. Mark it as such, and initialize
4438 * state to "not valid in current transaction".
4440 expr->expr_simple_expr = tle->expr;
4441 expr->expr_simple_state = NULL;
4442 expr->expr_simple_xid = InvalidTransactionId;
4443 /* Also stash away the expression result type */
4444 expr->expr_simple_type = exprType((Node *) tle->expr);
4448 * Check two tupledescs have matching number and types of attributes
4451 compatible_tupdesc(TupleDesc td1, TupleDesc td2)
4455 if (td1->natts != td2->natts)
4458 for (i = 0; i < td1->natts; i++)
4460 if (td1->attrs[i]->atttypid != td2->attrs[i]->atttypid)
4468 * exec_set_found Set the global found variable
4473 exec_set_found(PLpgSQL_execstate *estate, bool state)
4477 var = (PLpgSQL_var *) (estate->datums[estate->found_varno]);
4478 var->value = (Datum) state;
4479 var->isnull = false;
4483 * plpgsql_xact_cb --- post-transaction-commit-or-abort cleanup
4485 * If a simple_eval_estate was created in the current transaction,
4486 * it has to be cleaned up.
4488 * XXX Do we need to do anything at subtransaction events?
4489 * Maybe subtransactions need to have their own simple_eval_estate?
4490 * It would get a lot messier, so for now let's assume we don't need that.
4493 plpgsql_xact_cb(XactEvent event, void *arg)
4496 * If we are doing a clean transaction shutdown, free the EState (so that
4497 * any remaining resources will be released correctly). In an abort, we
4498 * expect the regular abort recovery procedures to release everything of
4501 if (event == XACT_EVENT_COMMIT && simple_eval_estate)
4502 FreeExecutorState(simple_eval_estate);
4503 simple_eval_estate = NULL;
4507 free_var(PLpgSQL_var *var)
4511 pfree(DatumGetPointer(var->value));
4512 var->freeval = false;