1 /*-------------------------------------------------------------------------
3 * pl_exec.c - Executor for the PL/pgSQL
6 * Portions Copyright (c) 1996-2007, 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.198 2007/07/15 02:15:04 tgl Exp $
13 *-------------------------------------------------------------------------
21 #include "access/heapam.h"
22 #include "access/transam.h"
23 #include "catalog/pg_proc.h"
24 #include "catalog/pg_type.h"
25 #include "executor/spi_priv.h"
27 #include "optimizer/clauses.h"
28 #include "parser/parse_expr.h"
29 #include "parser/scansup.h"
30 #include "tcop/tcopprot.h"
31 #include "utils/array.h"
32 #include "utils/builtins.h"
33 #include "utils/lsyscache.h"
34 #include "utils/memutils.h"
35 #include "utils/typcache.h"
38 static const char *const raise_skip_msg = "RAISE";
41 * All plpgsql function executions within a single transaction share the same
42 * executor EState for evaluating "simple" expressions. Each function call
43 * creates its own "eval_econtext" ExprContext within this estate for
44 * per-evaluation workspace. eval_econtext is freed at normal function exit,
45 * and the EState is freed at transaction end (in case of error, we assume
46 * that the abort mechanisms clean it all up). In order to be sure
47 * ExprContext callbacks are handled properly, each subtransaction has to have
48 * its own such EState; hence we need a stack. We use a simple counter to
49 * distinguish different instantiations of the EState, so that we can tell
50 * whether we have a current copy of a prepared expression.
52 * This arrangement is a bit tedious to maintain, but it's worth the trouble
53 * so that we don't have to re-prepare simple expressions on each trip through
54 * a function. (We assume the case to optimize is many repetitions of a
55 * function within a transaction.)
57 typedef struct SimpleEstateStackEntry
59 EState *xact_eval_estate; /* EState for current xact level */
60 long int xact_estate_simple_id; /* ID for xact_eval_estate */
61 SubTransactionId xact_subxid; /* ID for current subxact */
62 struct SimpleEstateStackEntry *next; /* next stack entry up */
63 } SimpleEstateStackEntry;
65 static SimpleEstateStackEntry *simple_estate_stack = NULL;
66 static long int simple_estate_id_counter = 0;
68 /************************************************************
69 * Local function forward declarations
70 ************************************************************/
71 static void plpgsql_exec_error_callback(void *arg);
72 static PLpgSQL_datum *copy_plpgsql_datum(PLpgSQL_datum *datum);
74 static int exec_stmt_block(PLpgSQL_execstate *estate,
75 PLpgSQL_stmt_block *block);
76 static int exec_stmts(PLpgSQL_execstate *estate,
78 static int exec_stmt(PLpgSQL_execstate *estate,
80 static int exec_stmt_assign(PLpgSQL_execstate *estate,
81 PLpgSQL_stmt_assign *stmt);
82 static int exec_stmt_perform(PLpgSQL_execstate *estate,
83 PLpgSQL_stmt_perform *stmt);
84 static int exec_stmt_getdiag(PLpgSQL_execstate *estate,
85 PLpgSQL_stmt_getdiag *stmt);
86 static int exec_stmt_if(PLpgSQL_execstate *estate,
87 PLpgSQL_stmt_if *stmt);
88 static int exec_stmt_loop(PLpgSQL_execstate *estate,
89 PLpgSQL_stmt_loop *stmt);
90 static int exec_stmt_while(PLpgSQL_execstate *estate,
91 PLpgSQL_stmt_while *stmt);
92 static int exec_stmt_fori(PLpgSQL_execstate *estate,
93 PLpgSQL_stmt_fori *stmt);
94 static int exec_stmt_fors(PLpgSQL_execstate *estate,
95 PLpgSQL_stmt_fors *stmt);
96 static int exec_stmt_open(PLpgSQL_execstate *estate,
97 PLpgSQL_stmt_open *stmt);
98 static int exec_stmt_fetch(PLpgSQL_execstate *estate,
99 PLpgSQL_stmt_fetch *stmt);
100 static int exec_stmt_close(PLpgSQL_execstate *estate,
101 PLpgSQL_stmt_close *stmt);
102 static int exec_stmt_exit(PLpgSQL_execstate *estate,
103 PLpgSQL_stmt_exit *stmt);
104 static int exec_stmt_return(PLpgSQL_execstate *estate,
105 PLpgSQL_stmt_return *stmt);
106 static int exec_stmt_return_next(PLpgSQL_execstate *estate,
107 PLpgSQL_stmt_return_next *stmt);
108 static int exec_stmt_raise(PLpgSQL_execstate *estate,
109 PLpgSQL_stmt_raise *stmt);
110 static int exec_stmt_execsql(PLpgSQL_execstate *estate,
111 PLpgSQL_stmt_execsql *stmt);
112 static int exec_stmt_dynexecute(PLpgSQL_execstate *estate,
113 PLpgSQL_stmt_dynexecute *stmt);
114 static int exec_stmt_dynfors(PLpgSQL_execstate *estate,
115 PLpgSQL_stmt_dynfors *stmt);
117 static void plpgsql_estate_setup(PLpgSQL_execstate *estate,
118 PLpgSQL_function *func,
120 static void exec_eval_cleanup(PLpgSQL_execstate *estate);
122 static void exec_prepare_plan(PLpgSQL_execstate *estate,
123 PLpgSQL_expr *expr, int cursorOptions);
124 static bool exec_simple_check_node(Node *node);
125 static void exec_simple_check_plan(PLpgSQL_expr *expr);
126 static bool exec_eval_simple_expr(PLpgSQL_execstate *estate,
132 static void exec_assign_expr(PLpgSQL_execstate *estate,
133 PLpgSQL_datum *target,
135 static void exec_assign_value(PLpgSQL_execstate *estate,
136 PLpgSQL_datum *target,
137 Datum value, Oid valtype, bool *isNull);
138 static void exec_eval_datum(PLpgSQL_execstate *estate,
139 PLpgSQL_datum *datum,
144 static int exec_eval_integer(PLpgSQL_execstate *estate,
147 static bool exec_eval_boolean(PLpgSQL_execstate *estate,
150 static Datum exec_eval_expr(PLpgSQL_execstate *estate,
154 static int exec_run_select(PLpgSQL_execstate *estate,
155 PLpgSQL_expr *expr, long maxtuples, Portal *portalP);
156 static void exec_move_row(PLpgSQL_execstate *estate,
159 HeapTuple tup, TupleDesc tupdesc);
160 static HeapTuple make_tuple_from_row(PLpgSQL_execstate *estate,
163 static char *convert_value_to_string(Datum value, Oid valtype);
164 static Datum exec_cast_value(Datum value, Oid valtype,
170 static Datum exec_simple_cast_value(Datum value, Oid valtype,
171 Oid reqtype, int32 reqtypmod,
173 static void exec_init_tuple_store(PLpgSQL_execstate *estate);
174 static bool compatible_tupdesc(TupleDesc td1, TupleDesc td2);
175 static void exec_set_found(PLpgSQL_execstate *estate, bool state);
176 static void plpgsql_create_econtext(PLpgSQL_execstate *estate);
177 static void free_var(PLpgSQL_var *var);
181 * plpgsql_exec_function Called by the call handler for
182 * function execution.
186 plpgsql_exec_function(PLpgSQL_function *func, FunctionCallInfo fcinfo)
188 PLpgSQL_execstate estate;
189 ErrorContextCallback plerrcontext;
194 * Setup the execution state
196 plpgsql_estate_setup(&estate, func, (ReturnSetInfo *) fcinfo->resultinfo);
199 * Setup error traceback support for ereport()
201 plerrcontext.callback = plpgsql_exec_error_callback;
202 plerrcontext.arg = &estate;
203 plerrcontext.previous = error_context_stack;
204 error_context_stack = &plerrcontext;
207 * Make local execution copies of all the datums
209 estate.err_text = gettext_noop("during initialization of execution state");
210 for (i = 0; i < estate.ndatums; i++)
211 estate.datums[i] = copy_plpgsql_datum(func->datums[i]);
214 * Store the actual call argument values into the appropriate variables
216 estate.err_text = gettext_noop("while storing call arguments into local variables");
217 for (i = 0; i < func->fn_nargs; i++)
219 int n = func->fn_argvarnos[i];
221 switch (estate.datums[n]->dtype)
223 case PLPGSQL_DTYPE_VAR:
225 PLpgSQL_var *var = (PLpgSQL_var *) estate.datums[n];
227 var->value = fcinfo->arg[i];
228 var->isnull = fcinfo->argnull[i];
229 var->freeval = false;
233 case PLPGSQL_DTYPE_ROW:
235 PLpgSQL_row *row = (PLpgSQL_row *) estate.datums[n];
237 if (!fcinfo->argnull[i])
243 HeapTupleData tmptup;
245 td = DatumGetHeapTupleHeader(fcinfo->arg[i]);
246 /* Extract rowtype info and find a tupdesc */
247 tupType = HeapTupleHeaderGetTypeId(td);
248 tupTypmod = HeapTupleHeaderGetTypMod(td);
249 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
250 /* Build a temporary HeapTuple control structure */
251 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
252 ItemPointerSetInvalid(&(tmptup.t_self));
253 tmptup.t_tableOid = InvalidOid;
255 exec_move_row(&estate, NULL, row, &tmptup, tupdesc);
256 ReleaseTupleDesc(tupdesc);
260 /* If arg is null, treat it as an empty row */
261 exec_move_row(&estate, NULL, row, NULL, NULL);
267 elog(ERROR, "unrecognized dtype: %d", func->datums[i]->dtype);
271 estate.err_text = gettext_noop("during function entry");
274 * Set the magic variable FOUND to false
276 exec_set_found(&estate, false);
279 * Let the instrumentation plugin peek at this function
281 if (*plugin_ptr && (*plugin_ptr)->func_beg)
282 ((*plugin_ptr)->func_beg) (&estate, func);
285 * Now call the toplevel block of statements
287 estate.err_text = NULL;
288 estate.err_stmt = (PLpgSQL_stmt *) (func->action);
289 rc = exec_stmt_block(&estate, func->action);
290 if (rc != PLPGSQL_RC_RETURN)
292 estate.err_stmt = NULL;
293 estate.err_text = NULL;
296 * Provide a more helpful message if a CONTINUE has been used outside
299 if (rc == PLPGSQL_RC_CONTINUE)
301 (errcode(ERRCODE_SYNTAX_ERROR),
302 errmsg("CONTINUE cannot be used outside a loop")));
305 (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
306 errmsg("control reached end of function without RETURN")));
310 * We got a return value - process it
312 estate.err_stmt = NULL;
313 estate.err_text = gettext_noop("while casting return value to function's return type");
315 fcinfo->isnull = estate.retisnull;
319 ReturnSetInfo *rsi = estate.rsi;
321 /* Check caller can handle a set result */
322 if (!rsi || !IsA(rsi, ReturnSetInfo) ||
323 (rsi->allowedModes & SFRM_Materialize) == 0)
325 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
326 errmsg("set-valued function called in context that cannot accept a set")));
327 rsi->returnMode = SFRM_Materialize;
329 /* If we produced any tuples, send back the result */
330 if (estate.tuple_store)
332 rsi->setResult = estate.tuple_store;
333 if (estate.rettupdesc)
335 MemoryContext oldcxt;
337 oldcxt = MemoryContextSwitchTo(estate.tuple_store_cxt);
338 rsi->setDesc = CreateTupleDescCopy(estate.rettupdesc);
339 MemoryContextSwitchTo(oldcxt);
342 estate.retval = (Datum) 0;
343 fcinfo->isnull = true;
345 else if (!estate.retisnull)
347 if (estate.retistuple)
350 * We have to check that the returned tuple actually matches the
351 * expected result type. XXX would be better to cache the tupdesc
352 * instead of repeating get_call_result_type()
356 switch (get_call_result_type(fcinfo, NULL, &tupdesc))
358 case TYPEFUNC_COMPOSITE:
359 /* got the expected result rowtype, now check it */
360 if (estate.rettupdesc == NULL ||
361 !compatible_tupdesc(estate.rettupdesc, tupdesc))
363 (errcode(ERRCODE_DATATYPE_MISMATCH),
364 errmsg("returned record type does not match expected record type")));
366 case TYPEFUNC_RECORD:
369 * Failed to determine actual type of RECORD. We could
370 * raise an error here, but what this means in practice is
371 * that the caller is expecting any old generic rowtype,
372 * so we don't really need to be restrictive. Pass back
373 * the generated result type, instead.
375 tupdesc = estate.rettupdesc;
376 if (tupdesc == NULL) /* shouldn't happen */
377 elog(ERROR, "return type must be a row type");
380 /* shouldn't get here if retistuple is true ... */
381 elog(ERROR, "return type must be a row type");
386 * Copy tuple to upper executor memory, as a tuple Datum. Make
387 * sure it is labeled with the caller-supplied tuple type.
390 PointerGetDatum(SPI_returntuple((HeapTuple) (estate.retval),
395 /* Cast value to proper type */
396 estate.retval = exec_cast_value(estate.retval, estate.rettype,
398 &(func->fn_retinput),
399 func->fn_rettypioparam,
404 * If the function's return type isn't by value, copy the value
405 * into upper executor memory context.
407 if (!fcinfo->isnull && !func->fn_retbyval)
412 len = datumGetSize(estate.retval, false, func->fn_rettyplen);
413 tmp = SPI_palloc(len);
414 memcpy(tmp, DatumGetPointer(estate.retval), len);
415 estate.retval = PointerGetDatum(tmp);
420 estate.err_text = gettext_noop("during function exit");
423 * Let the instrumentation plugin peek at this function
425 if (*plugin_ptr && (*plugin_ptr)->func_end)
426 ((*plugin_ptr)->func_end) (&estate, func);
428 /* Clean up any leftover temporary memory */
429 FreeExprContext(estate.eval_econtext);
430 estate.eval_econtext = NULL;
431 exec_eval_cleanup(&estate);
434 * Pop the error context stack
436 error_context_stack = plerrcontext.previous;
439 * Return the function's result
441 return estate.retval;
446 * plpgsql_exec_trigger Called by the call handler for
451 plpgsql_exec_trigger(PLpgSQL_function *func,
452 TriggerData *trigdata)
454 PLpgSQL_execstate estate;
455 ErrorContextCallback plerrcontext;
459 PLpgSQL_rec *rec_new,
464 * Setup the execution state
466 plpgsql_estate_setup(&estate, func, NULL);
469 * Setup error traceback support for ereport()
471 plerrcontext.callback = plpgsql_exec_error_callback;
472 plerrcontext.arg = &estate;
473 plerrcontext.previous = error_context_stack;
474 error_context_stack = &plerrcontext;
477 * Make local execution copies of all the datums
479 estate.err_text = gettext_noop("during initialization of execution state");
480 for (i = 0; i < estate.ndatums; i++)
481 estate.datums[i] = copy_plpgsql_datum(func->datums[i]);
484 * Put the OLD and NEW tuples into record variables
486 rec_new = (PLpgSQL_rec *) (estate.datums[func->new_varno]);
487 rec_new->freetup = false;
488 rec_new->freetupdesc = false;
489 rec_old = (PLpgSQL_rec *) (estate.datums[func->old_varno]);
490 rec_old->freetup = false;
491 rec_old->freetupdesc = false;
493 if (TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
496 * Per-statement triggers don't use OLD/NEW variables
499 rec_new->tupdesc = NULL;
501 rec_old->tupdesc = NULL;
503 else if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
505 rec_new->tup = trigdata->tg_trigtuple;
506 rec_new->tupdesc = trigdata->tg_relation->rd_att;
508 rec_old->tupdesc = NULL;
510 else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
512 rec_new->tup = trigdata->tg_newtuple;
513 rec_new->tupdesc = trigdata->tg_relation->rd_att;
514 rec_old->tup = trigdata->tg_trigtuple;
515 rec_old->tupdesc = trigdata->tg_relation->rd_att;
517 else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
520 rec_new->tupdesc = NULL;
521 rec_old->tup = trigdata->tg_trigtuple;
522 rec_old->tupdesc = trigdata->tg_relation->rd_att;
525 elog(ERROR, "unrecognized trigger action: not INSERT, DELETE, or UPDATE");
528 * Assign the special tg_ variables
531 var = (PLpgSQL_var *) (estate.datums[func->tg_op_varno]);
532 if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
533 var->value = DirectFunctionCall1(textin, CStringGetDatum("INSERT"));
534 else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
535 var->value = DirectFunctionCall1(textin, CStringGetDatum("UPDATE"));
536 else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
537 var->value = DirectFunctionCall1(textin, CStringGetDatum("DELETE"));
539 elog(ERROR, "unrecognized trigger action: not INSERT, DELETE, or UPDATE");
543 var = (PLpgSQL_var *) (estate.datums[func->tg_name_varno]);
544 var->value = DirectFunctionCall1(namein,
545 CStringGetDatum(trigdata->tg_trigger->tgname));
549 var = (PLpgSQL_var *) (estate.datums[func->tg_when_varno]);
550 if (TRIGGER_FIRED_BEFORE(trigdata->tg_event))
551 var->value = DirectFunctionCall1(textin, CStringGetDatum("BEFORE"));
552 else if (TRIGGER_FIRED_AFTER(trigdata->tg_event))
553 var->value = DirectFunctionCall1(textin, CStringGetDatum("AFTER"));
555 elog(ERROR, "unrecognized trigger execution time: not BEFORE or AFTER");
559 var = (PLpgSQL_var *) (estate.datums[func->tg_level_varno]);
560 if (TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
561 var->value = DirectFunctionCall1(textin, CStringGetDatum("ROW"));
562 else if (TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
563 var->value = DirectFunctionCall1(textin, CStringGetDatum("STATEMENT"));
565 elog(ERROR, "unrecognized trigger event type: not ROW or STATEMENT");
569 var = (PLpgSQL_var *) (estate.datums[func->tg_relid_varno]);
570 var->value = ObjectIdGetDatum(trigdata->tg_relation->rd_id);
572 var->freeval = false;
574 var = (PLpgSQL_var *) (estate.datums[func->tg_relname_varno]);
575 var->value = DirectFunctionCall1(namein,
576 CStringGetDatum(RelationGetRelationName(trigdata->tg_relation)));
580 var = (PLpgSQL_var *) (estate.datums[func->tg_table_name_varno]);
581 var->value = DirectFunctionCall1(namein,
582 CStringGetDatum(RelationGetRelationName(trigdata->tg_relation)));
586 var = (PLpgSQL_var *) (estate.datums[func->tg_table_schema_varno]);
587 var->value = DirectFunctionCall1(namein,
590 RelationGetNamespace(
591 trigdata->tg_relation))));
595 var = (PLpgSQL_var *) (estate.datums[func->tg_nargs_varno]);
596 var->value = Int16GetDatum(trigdata->tg_trigger->tgnargs);
598 var->freeval = false;
601 * Store the trigger argument values into the special execution state
604 estate.err_text = gettext_noop("while storing call arguments into local variables");
605 estate.trig_nargs = trigdata->tg_trigger->tgnargs;
606 if (estate.trig_nargs == 0)
607 estate.trig_argv = NULL;
610 estate.trig_argv = palloc(sizeof(Datum) * estate.trig_nargs);
611 for (i = 0; i < trigdata->tg_trigger->tgnargs; i++)
612 estate.trig_argv[i] = DirectFunctionCall1(textin,
613 CStringGetDatum(trigdata->tg_trigger->tgargs[i]));
616 estate.err_text = gettext_noop("during function entry");
619 * Set the magic variable FOUND to false
621 exec_set_found(&estate, false);
624 * Let the instrumentation plugin peek at this function
626 if (*plugin_ptr && (*plugin_ptr)->func_beg)
627 ((*plugin_ptr)->func_beg) (&estate, func);
630 * Now call the toplevel block of statements
632 estate.err_text = NULL;
633 estate.err_stmt = (PLpgSQL_stmt *) (func->action);
634 rc = exec_stmt_block(&estate, func->action);
635 if (rc != PLPGSQL_RC_RETURN)
637 estate.err_stmt = NULL;
638 estate.err_text = NULL;
641 * Provide a more helpful message if a CONTINUE has been used outside
644 if (rc == PLPGSQL_RC_CONTINUE)
646 (errcode(ERRCODE_SYNTAX_ERROR),
647 errmsg("CONTINUE cannot be used outside a loop")));
650 (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
651 errmsg("control reached end of trigger procedure without RETURN")));
654 estate.err_stmt = NULL;
655 estate.err_text = gettext_noop("during function exit");
659 (errcode(ERRCODE_DATATYPE_MISMATCH),
660 errmsg("trigger procedure cannot return a set")));
663 * Check that the returned tuple structure has the same attributes, the
664 * relation that fired the trigger has. A per-statement trigger always
665 * needs to return NULL, so we ignore any return value the function itself
666 * produces (XXX: is this a good idea?)
668 * XXX This way it is possible, that the trigger returns a tuple where
669 * attributes don't have the correct atttypmod's length. It's up to the
670 * trigger's programmer to ensure that this doesn't happen. Jan
672 if (estate.retisnull || TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
676 if (!compatible_tupdesc(estate.rettupdesc,
677 trigdata->tg_relation->rd_att))
679 (errcode(ERRCODE_DATATYPE_MISMATCH),
680 errmsg("returned tuple structure does not match table of trigger event")));
681 /* Copy tuple to upper executor memory */
682 rettup = SPI_copytuple((HeapTuple) (estate.retval));
686 * Let the instrumentation plugin peek at this function
688 if (*plugin_ptr && (*plugin_ptr)->func_end)
689 ((*plugin_ptr)->func_end) (&estate, func);
691 /* Clean up any leftover temporary memory */
692 FreeExprContext(estate.eval_econtext);
693 estate.eval_econtext = NULL;
694 exec_eval_cleanup(&estate);
697 * Pop the error context stack
699 error_context_stack = plerrcontext.previous;
702 * Return the trigger's result
709 * error context callback to let us supply a call-stack traceback
712 plpgsql_exec_error_callback(void *arg)
714 PLpgSQL_execstate *estate = (PLpgSQL_execstate *) arg;
716 /* safety check, shouldn't happen */
717 if (estate->err_func == NULL)
720 /* if we are doing RAISE, don't report its location */
721 if (estate->err_text == raise_skip_msg)
724 if (estate->err_text != NULL)
727 * We don't expend the cycles to run gettext() on err_text unless we
728 * actually need it. Therefore, places that set up err_text should
729 * use gettext_noop() to ensure the strings get recorded in the
730 * message dictionary.
732 * If both err_text and err_stmt are set, use the err_text as
733 * description, but report the err_stmt's line number. When
734 * err_stmt is not set, we're in function entry/exit, or some such
735 * place not attached to a specific line number.
737 if (estate->err_stmt != NULL)
740 * translator: last %s is a phrase such as "during statement
741 * block local variable initialization"
743 errcontext("PL/pgSQL function \"%s\" line %d %s",
744 estate->err_func->fn_name,
745 estate->err_stmt->lineno,
746 gettext(estate->err_text));
751 * translator: last %s is a phrase such as "while storing call
752 * arguments into local variables"
754 errcontext("PL/pgSQL function \"%s\" %s",
755 estate->err_func->fn_name,
756 gettext(estate->err_text));
759 else if (estate->err_stmt != NULL)
761 /* translator: last %s is a plpgsql statement type name */
762 errcontext("PL/pgSQL function \"%s\" line %d at %s",
763 estate->err_func->fn_name,
764 estate->err_stmt->lineno,
765 plpgsql_stmt_typename(estate->err_stmt));
768 errcontext("PL/pgSQL function \"%s\"",
769 estate->err_func->fn_name);
774 * Support function for initializing local execution variables
777 static PLpgSQL_datum *
778 copy_plpgsql_datum(PLpgSQL_datum *datum)
780 PLpgSQL_datum *result;
782 switch (datum->dtype)
784 case PLPGSQL_DTYPE_VAR:
786 PLpgSQL_var *new = palloc(sizeof(PLpgSQL_var));
788 memcpy(new, datum, sizeof(PLpgSQL_var));
789 /* Ensure the value is null (possibly not needed?) */
792 new->freeval = false;
794 result = (PLpgSQL_datum *) new;
798 case PLPGSQL_DTYPE_REC:
800 PLpgSQL_rec *new = palloc(sizeof(PLpgSQL_rec));
802 memcpy(new, datum, sizeof(PLpgSQL_rec));
803 /* Ensure the value is null (possibly not needed?) */
806 new->freetup = false;
807 new->freetupdesc = false;
809 result = (PLpgSQL_datum *) new;
813 case PLPGSQL_DTYPE_ROW:
814 case PLPGSQL_DTYPE_RECFIELD:
815 case PLPGSQL_DTYPE_ARRAYELEM:
816 case PLPGSQL_DTYPE_TRIGARG:
819 * These datum records are read-only at runtime, so no need to
826 elog(ERROR, "unrecognized dtype: %d", datum->dtype);
827 result = NULL; /* keep compiler quiet */
836 exception_matches_conditions(ErrorData *edata, PLpgSQL_condition *cond)
838 for (; cond != NULL; cond = cond->next)
840 int sqlerrstate = cond->sqlerrstate;
843 * OTHERS matches everything *except* query-canceled; if you're
844 * foolish enough, you can match that explicitly.
846 if (sqlerrstate == 0)
848 if (edata->sqlerrcode != ERRCODE_QUERY_CANCELED)
852 else if (edata->sqlerrcode == sqlerrstate)
854 /* Category match? */
855 else if (ERRCODE_IS_CATEGORY(sqlerrstate) &&
856 ERRCODE_TO_CATEGORY(edata->sqlerrcode) == sqlerrstate)
864 * exec_stmt_block Execute a block of statements
868 exec_stmt_block(PLpgSQL_execstate *estate, PLpgSQL_stmt_block *block)
870 volatile int rc = -1;
875 * First initialize all variables declared in this block
877 estate->err_text = gettext_noop("during statement block local variable initialization");
879 for (i = 0; i < block->n_initvars; i++)
881 n = block->initvarnos[i];
883 switch (estate->datums[n]->dtype)
885 case PLPGSQL_DTYPE_VAR:
887 PLpgSQL_var *var = (PLpgSQL_var *) (estate->datums[n]);
889 /* free any old value, in case re-entering block */
892 /* Initially it contains a NULL */
893 var->value = (Datum) 0;
896 if (var->default_val == NULL)
899 * If needed, give the datatype a chance to reject
900 * NULLs, by assigning a NULL to the variable.
901 * We claim the value is of type UNKNOWN, not the
902 * var's datatype, else coercion will be skipped.
903 * (Do this before the notnull check to be
904 * consistent with exec_assign_value.)
906 if (!var->datatype->typinput.fn_strict)
908 bool valIsNull = true;
910 exec_assign_value(estate,
911 (PLpgSQL_datum *) var,
918 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
919 errmsg("variable \"%s\" declared NOT NULL cannot default to NULL",
924 exec_assign_expr(estate, (PLpgSQL_datum *) var,
930 case PLPGSQL_DTYPE_REC:
932 PLpgSQL_rec *rec = (PLpgSQL_rec *) (estate->datums[n]);
936 heap_freetuple(rec->tup);
937 FreeTupleDesc(rec->tupdesc);
938 rec->freetup = false;
946 case PLPGSQL_DTYPE_RECFIELD:
947 case PLPGSQL_DTYPE_ARRAYELEM:
951 elog(ERROR, "unrecognized dtype: %d",
952 estate->datums[n]->dtype);
956 if (block->exceptions)
959 * Execute the statements in the block's body inside a sub-transaction
961 MemoryContext oldcontext = CurrentMemoryContext;
962 ResourceOwner oldowner = CurrentResourceOwner;
963 ExprContext *old_eval_econtext = estate->eval_econtext;
964 EState *old_eval_estate = estate->eval_estate;
965 long int old_eval_estate_simple_id = estate->eval_estate_simple_id;
967 estate->err_text = gettext_noop("during statement block entry");
969 BeginInternalSubTransaction(NULL);
970 /* Want to run statements inside function's memory context */
971 MemoryContextSwitchTo(oldcontext);
976 * We need to run the block's statements with a new eval_econtext
977 * that belongs to the current subtransaction; if we try to use
978 * the outer econtext then ExprContext shutdown callbacks will be
979 * called at the wrong times.
981 plpgsql_create_econtext(estate);
983 estate->err_text = NULL;
985 /* Run the block's statements */
986 rc = exec_stmts(estate, block->body);
988 estate->err_text = gettext_noop("during statement block exit");
991 * If the block ended with RETURN, we may need to copy the return
992 * value out of the subtransaction eval_context. This is currently
993 * only needed for scalar result types --- rowtype values will
994 * always exist in the function's own memory context.
996 if (rc == PLPGSQL_RC_RETURN &&
998 !estate->retisnull &&
999 estate->rettupdesc == NULL)
1004 get_typlenbyval(estate->rettype, &resTypLen, &resTypByVal);
1005 estate->retval = datumCopy(estate->retval,
1006 resTypByVal, resTypLen);
1009 /* Commit the inner transaction, return to outer xact context */
1010 ReleaseCurrentSubTransaction();
1011 MemoryContextSwitchTo(oldcontext);
1012 CurrentResourceOwner = oldowner;
1014 /* Revert to outer eval_econtext */
1015 estate->eval_econtext = old_eval_econtext;
1016 estate->eval_estate = old_eval_estate;
1017 estate->eval_estate_simple_id = old_eval_estate_simple_id;
1020 * AtEOSubXact_SPI() should not have popped any SPI context, but
1021 * just in case it did, make sure we remain connected.
1023 SPI_restore_connection();
1030 estate->err_text = gettext_noop("during exception cleanup");
1032 /* Save error info */
1033 MemoryContextSwitchTo(oldcontext);
1034 edata = CopyErrorData();
1037 /* Abort the inner transaction */
1038 RollbackAndReleaseCurrentSubTransaction();
1039 MemoryContextSwitchTo(oldcontext);
1040 CurrentResourceOwner = oldowner;
1042 /* Revert to outer eval_econtext */
1043 estate->eval_econtext = old_eval_econtext;
1044 estate->eval_estate = old_eval_estate;
1045 estate->eval_estate_simple_id = old_eval_estate_simple_id;
1048 * If AtEOSubXact_SPI() popped any SPI context of the subxact, it
1049 * will have left us in a disconnected state. We need this hack
1050 * to return to connected state.
1052 SPI_restore_connection();
1054 /* Look for a matching exception handler */
1055 foreach(e, block->exceptions->exc_list)
1057 PLpgSQL_exception *exception = (PLpgSQL_exception *) lfirst(e);
1059 if (exception_matches_conditions(edata, exception->conditions))
1062 * Initialize the magic SQLSTATE and SQLERRM variables for
1063 * the exception block. We needn't do this until we have
1064 * found a matching exception.
1066 PLpgSQL_var *state_var;
1067 PLpgSQL_var *errm_var;
1069 state_var = (PLpgSQL_var *)
1070 estate->datums[block->exceptions->sqlstate_varno];
1071 state_var->value = DirectFunctionCall1(textin,
1072 CStringGetDatum(unpack_sql_state(edata->sqlerrcode)));
1073 state_var->freeval = true;
1074 state_var->isnull = false;
1076 errm_var = (PLpgSQL_var *)
1077 estate->datums[block->exceptions->sqlerrm_varno];
1078 errm_var->value = DirectFunctionCall1(textin,
1079 CStringGetDatum(edata->message));
1080 errm_var->freeval = true;
1081 errm_var->isnull = false;
1083 estate->err_text = NULL;
1085 rc = exec_stmts(estate, exception->action);
1087 free_var(state_var);
1088 state_var->value = (Datum) 0;
1090 errm_var->value = (Datum) 0;
1095 /* If no match found, re-throw the error */
1097 ReThrowError(edata);
1099 FreeErrorData(edata);
1106 * Just execute the statements in the block's body
1108 estate->err_text = NULL;
1110 rc = exec_stmts(estate, block->body);
1113 estate->err_text = NULL;
1116 * Handle the return code.
1121 case PLPGSQL_RC_CONTINUE:
1122 case PLPGSQL_RC_RETURN:
1125 case PLPGSQL_RC_EXIT:
1126 if (estate->exitlabel == NULL)
1127 return PLPGSQL_RC_OK;
1128 if (block->label == NULL)
1129 return PLPGSQL_RC_EXIT;
1130 if (strcmp(block->label, estate->exitlabel))
1131 return PLPGSQL_RC_EXIT;
1132 estate->exitlabel = NULL;
1133 return PLPGSQL_RC_OK;
1136 elog(ERROR, "unrecognized rc: %d", rc);
1139 return PLPGSQL_RC_OK;
1144 * exec_stmts Iterate over a list of statements
1145 * as long as their return code is OK
1149 exec_stmts(PLpgSQL_execstate *estate, List *stmts)
1156 * Ensure we do a CHECK_FOR_INTERRUPTS() even though there is no
1157 * statement. This prevents hangup in a tight loop if, for instance,
1158 * there is a LOOP construct with an empty body.
1160 CHECK_FOR_INTERRUPTS();
1161 return PLPGSQL_RC_OK;
1166 PLpgSQL_stmt *stmt = (PLpgSQL_stmt *) lfirst(s);
1167 int rc = exec_stmt(estate, stmt);
1169 if (rc != PLPGSQL_RC_OK)
1173 return PLPGSQL_RC_OK;
1178 * exec_stmt Distribute one statement to the statements
1179 * type specific execution function.
1183 exec_stmt(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
1185 PLpgSQL_stmt *save_estmt;
1188 save_estmt = estate->err_stmt;
1189 estate->err_stmt = stmt;
1191 /* Let the plugin know that we are about to execute this statement */
1192 if (*plugin_ptr && (*plugin_ptr)->stmt_beg)
1193 ((*plugin_ptr)->stmt_beg) (estate, stmt);
1195 CHECK_FOR_INTERRUPTS();
1197 switch (stmt->cmd_type)
1199 case PLPGSQL_STMT_BLOCK:
1200 rc = exec_stmt_block(estate, (PLpgSQL_stmt_block *) stmt);
1203 case PLPGSQL_STMT_ASSIGN:
1204 rc = exec_stmt_assign(estate, (PLpgSQL_stmt_assign *) stmt);
1207 case PLPGSQL_STMT_PERFORM:
1208 rc = exec_stmt_perform(estate, (PLpgSQL_stmt_perform *) stmt);
1211 case PLPGSQL_STMT_GETDIAG:
1212 rc = exec_stmt_getdiag(estate, (PLpgSQL_stmt_getdiag *) stmt);
1215 case PLPGSQL_STMT_IF:
1216 rc = exec_stmt_if(estate, (PLpgSQL_stmt_if *) stmt);
1219 case PLPGSQL_STMT_LOOP:
1220 rc = exec_stmt_loop(estate, (PLpgSQL_stmt_loop *) stmt);
1223 case PLPGSQL_STMT_WHILE:
1224 rc = exec_stmt_while(estate, (PLpgSQL_stmt_while *) stmt);
1227 case PLPGSQL_STMT_FORI:
1228 rc = exec_stmt_fori(estate, (PLpgSQL_stmt_fori *) stmt);
1231 case PLPGSQL_STMT_FORS:
1232 rc = exec_stmt_fors(estate, (PLpgSQL_stmt_fors *) stmt);
1235 case PLPGSQL_STMT_EXIT:
1236 rc = exec_stmt_exit(estate, (PLpgSQL_stmt_exit *) stmt);
1239 case PLPGSQL_STMT_RETURN:
1240 rc = exec_stmt_return(estate, (PLpgSQL_stmt_return *) stmt);
1243 case PLPGSQL_STMT_RETURN_NEXT:
1244 rc = exec_stmt_return_next(estate, (PLpgSQL_stmt_return_next *) stmt);
1247 case PLPGSQL_STMT_RAISE:
1248 rc = exec_stmt_raise(estate, (PLpgSQL_stmt_raise *) stmt);
1251 case PLPGSQL_STMT_EXECSQL:
1252 rc = exec_stmt_execsql(estate, (PLpgSQL_stmt_execsql *) stmt);
1255 case PLPGSQL_STMT_DYNEXECUTE:
1256 rc = exec_stmt_dynexecute(estate, (PLpgSQL_stmt_dynexecute *) stmt);
1259 case PLPGSQL_STMT_DYNFORS:
1260 rc = exec_stmt_dynfors(estate, (PLpgSQL_stmt_dynfors *) stmt);
1263 case PLPGSQL_STMT_OPEN:
1264 rc = exec_stmt_open(estate, (PLpgSQL_stmt_open *) stmt);
1267 case PLPGSQL_STMT_FETCH:
1268 rc = exec_stmt_fetch(estate, (PLpgSQL_stmt_fetch *) stmt);
1271 case PLPGSQL_STMT_CLOSE:
1272 rc = exec_stmt_close(estate, (PLpgSQL_stmt_close *) stmt);
1276 estate->err_stmt = save_estmt;
1277 elog(ERROR, "unrecognized cmdtype: %d", stmt->cmd_type);
1280 /* Let the plugin know that we have finished executing this statement */
1281 if (*plugin_ptr && (*plugin_ptr)->stmt_end)
1282 ((*plugin_ptr)->stmt_end) (estate, stmt);
1284 estate->err_stmt = save_estmt;
1291 * exec_stmt_assign Evaluate an expression and
1292 * put the result into a variable.
1296 exec_stmt_assign(PLpgSQL_execstate *estate, PLpgSQL_stmt_assign *stmt)
1298 Assert(stmt->varno >= 0);
1300 exec_assign_expr(estate, estate->datums[stmt->varno], stmt->expr);
1302 return PLPGSQL_RC_OK;
1306 * exec_stmt_perform Evaluate query and discard result (but set
1307 * FOUND depending on whether at least one row
1312 exec_stmt_perform(PLpgSQL_execstate *estate, PLpgSQL_stmt_perform *stmt)
1314 PLpgSQL_expr *expr = stmt->expr;
1316 (void) exec_run_select(estate, expr, 0, NULL);
1317 exec_set_found(estate, (estate->eval_processed != 0));
1318 exec_eval_cleanup(estate);
1320 return PLPGSQL_RC_OK;
1324 * exec_stmt_getdiag Put internal PG information into
1325 * specified variables.
1329 exec_stmt_getdiag(PLpgSQL_execstate *estate, PLpgSQL_stmt_getdiag *stmt)
1333 foreach(lc, stmt->diag_items)
1335 PLpgSQL_diag_item *diag_item = (PLpgSQL_diag_item *) lfirst(lc);
1337 bool isnull = false;
1339 if (diag_item->target <= 0)
1342 var = estate->datums[diag_item->target];
1347 switch (diag_item->kind)
1349 case PLPGSQL_GETDIAG_ROW_COUNT:
1351 exec_assign_value(estate, var,
1352 UInt32GetDatum(estate->eval_processed),
1356 case PLPGSQL_GETDIAG_RESULT_OID:
1358 exec_assign_value(estate, var,
1359 ObjectIdGetDatum(estate->eval_lastoid),
1364 elog(ERROR, "unrecognized attribute request: %d",
1369 return PLPGSQL_RC_OK;
1373 * exec_stmt_if Evaluate a bool expression and
1374 * execute the true or false body
1379 exec_stmt_if(PLpgSQL_execstate *estate, PLpgSQL_stmt_if *stmt)
1384 value = exec_eval_boolean(estate, stmt->cond, &isnull);
1385 exec_eval_cleanup(estate);
1387 if (!isnull && value)
1389 if (stmt->true_body != NIL)
1390 return exec_stmts(estate, stmt->true_body);
1394 if (stmt->false_body != NIL)
1395 return exec_stmts(estate, stmt->false_body);
1398 return PLPGSQL_RC_OK;
1403 * exec_stmt_loop Loop over statements until
1408 exec_stmt_loop(PLpgSQL_execstate *estate, PLpgSQL_stmt_loop *stmt)
1412 int rc = exec_stmts(estate, stmt->body);
1419 case PLPGSQL_RC_EXIT:
1420 if (estate->exitlabel == NULL)
1421 return PLPGSQL_RC_OK;
1422 if (stmt->label == NULL)
1423 return PLPGSQL_RC_EXIT;
1424 if (strcmp(stmt->label, estate->exitlabel) != 0)
1425 return PLPGSQL_RC_EXIT;
1426 estate->exitlabel = NULL;
1427 return PLPGSQL_RC_OK;
1429 case PLPGSQL_RC_CONTINUE:
1430 if (estate->exitlabel == NULL)
1431 /* anonymous continue, so re-run the loop */
1433 else if (stmt->label != NULL &&
1434 strcmp(stmt->label, estate->exitlabel) == 0)
1435 /* label matches named continue, so re-run loop */
1436 estate->exitlabel = NULL;
1438 /* label doesn't match named continue, so propagate upward */
1439 return PLPGSQL_RC_CONTINUE;
1442 case PLPGSQL_RC_RETURN:
1443 return PLPGSQL_RC_RETURN;
1446 elog(ERROR, "unrecognized rc: %d", rc);
1450 return PLPGSQL_RC_OK;
1455 * exec_stmt_while Loop over statements as long
1456 * as an expression evaluates to
1457 * true or an exit occurs.
1461 exec_stmt_while(PLpgSQL_execstate *estate, PLpgSQL_stmt_while *stmt)
1469 value = exec_eval_boolean(estate, stmt->cond, &isnull);
1470 exec_eval_cleanup(estate);
1472 if (isnull || !value)
1475 rc = exec_stmts(estate, stmt->body);
1482 case PLPGSQL_RC_EXIT:
1483 if (estate->exitlabel == NULL)
1484 return PLPGSQL_RC_OK;
1485 if (stmt->label == NULL)
1486 return PLPGSQL_RC_EXIT;
1487 if (strcmp(stmt->label, estate->exitlabel))
1488 return PLPGSQL_RC_EXIT;
1489 estate->exitlabel = NULL;
1490 return PLPGSQL_RC_OK;
1492 case PLPGSQL_RC_CONTINUE:
1493 if (estate->exitlabel == NULL)
1494 /* anonymous continue, so re-run loop */
1496 else if (stmt->label != NULL &&
1497 strcmp(stmt->label, estate->exitlabel) == 0)
1498 /* label matches named continue, so re-run loop */
1499 estate->exitlabel = NULL;
1501 /* label doesn't match named continue, propagate upward */
1502 return PLPGSQL_RC_CONTINUE;
1505 case PLPGSQL_RC_RETURN:
1506 return PLPGSQL_RC_RETURN;
1509 elog(ERROR, "unrecognized rc: %d", rc);
1513 return PLPGSQL_RC_OK;
1518 * exec_stmt_fori Iterate an integer variable
1519 * from a lower to an upper value
1520 * incrementing or decrementing by the BY value
1524 exec_stmt_fori(PLpgSQL_execstate *estate, PLpgSQL_stmt_fori *stmt)
1534 int rc = PLPGSQL_RC_OK;
1536 var = (PLpgSQL_var *) (estate->datums[stmt->var->varno]);
1539 * Get the value of the lower bound
1541 value = exec_eval_expr(estate, stmt->lower, &isnull, &valtype);
1542 value = exec_cast_value(value, valtype, var->datatype->typoid,
1543 &(var->datatype->typinput),
1544 var->datatype->typioparam,
1545 var->datatype->atttypmod, isnull);
1548 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1549 errmsg("lower bound of FOR loop cannot be NULL")));
1550 loop_value = DatumGetInt32(value);
1551 exec_eval_cleanup(estate);
1554 * Get the value of the upper bound
1556 value = exec_eval_expr(estate, stmt->upper, &isnull, &valtype);
1557 value = exec_cast_value(value, valtype, var->datatype->typoid,
1558 &(var->datatype->typinput),
1559 var->datatype->typioparam,
1560 var->datatype->atttypmod, isnull);
1563 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1564 errmsg("upper bound of FOR loop cannot be NULL")));
1565 end_value = DatumGetInt32(value);
1566 exec_eval_cleanup(estate);
1569 * Get the step value
1573 value = exec_eval_expr(estate, stmt->step, &isnull, &valtype);
1574 value = exec_cast_value(value, valtype, var->datatype->typoid,
1575 &(var->datatype->typinput),
1576 var->datatype->typioparam,
1577 var->datatype->atttypmod, isnull);
1580 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1581 errmsg("BY value of FOR loop cannot be NULL")));
1582 step_value = DatumGetInt32(value);
1583 exec_eval_cleanup(estate);
1584 if (step_value <= 0)
1586 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1587 errmsg("BY value of FOR loop must be greater than zero")));
1598 * Check against upper bound
1602 if (loop_value < end_value)
1607 if (loop_value > end_value)
1611 found = true; /* looped at least once */
1614 * Assign current value to loop var
1616 var->value = Int32GetDatum(loop_value);
1617 var->isnull = false;
1620 * Execute the statements
1622 rc = exec_stmts(estate, stmt->body);
1624 if (rc == PLPGSQL_RC_RETURN)
1625 break; /* return from function */
1626 else if (rc == PLPGSQL_RC_EXIT)
1628 if (estate->exitlabel == NULL)
1629 /* unlabelled exit, finish the current loop */
1631 else if (stmt->label != NULL &&
1632 strcmp(stmt->label, estate->exitlabel) == 0)
1634 /* labelled exit, matches the current stmt's label */
1635 estate->exitlabel = NULL;
1640 * otherwise, this is a labelled exit that does not match the
1641 * current statement's label, if any: return RC_EXIT so that the
1642 * EXIT continues to propagate up the stack.
1646 else if (rc == PLPGSQL_RC_CONTINUE)
1648 if (estate->exitlabel == NULL)
1649 /* unlabelled continue, so re-run the current loop */
1651 else if (stmt->label != NULL &&
1652 strcmp(stmt->label, estate->exitlabel) == 0)
1654 /* label matches named continue, so re-run loop */
1655 estate->exitlabel = NULL;
1661 * otherwise, this is a named continue that does not match the
1662 * current statement's label, if any: return RC_CONTINUE so
1663 * that the CONTINUE will propagate up the stack.
1670 * Increase/decrease loop value, unless it would overflow, in which
1671 * case exit the loop.
1675 if ((int32) (loop_value - step_value) > loop_value)
1677 loop_value -= step_value;
1681 if ((int32) (loop_value + step_value) < loop_value)
1683 loop_value += step_value;
1688 * Set the FOUND variable to indicate the result of executing the loop
1689 * (namely, whether we looped one or more times). This must be set here so
1690 * that it does not interfere with the value of the FOUND variable inside
1691 * the loop processing itself.
1693 exec_set_found(estate, found);
1700 * exec_stmt_fors Execute a query, assign each
1701 * tuple to a record or row and
1702 * execute a group of statements
1707 exec_stmt_fors(PLpgSQL_execstate *estate, PLpgSQL_stmt_fors *stmt)
1709 PLpgSQL_rec *rec = NULL;
1710 PLpgSQL_row *row = NULL;
1711 SPITupleTable *tuptab;
1714 int rc = PLPGSQL_RC_OK;
1719 * Determine if we assign to a record or a row
1721 if (stmt->rec != NULL)
1722 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
1723 else if (stmt->row != NULL)
1724 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
1726 elog(ERROR, "unsupported target");
1729 * Open the implicit cursor for the statement and fetch the initial 10
1732 exec_run_select(estate, stmt->query, 0, &portal);
1734 SPI_cursor_fetch(portal, true, 10);
1735 tuptab = SPI_tuptable;
1739 * If the query didn't return any rows, set the target to NULL and return
1740 * with FOUND = false.
1743 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
1745 found = true; /* processed at least one tuple */
1752 for (i = 0; i < n; i++)
1755 * Assign the tuple to the target
1757 exec_move_row(estate, rec, row, tuptab->vals[i], tuptab->tupdesc);
1760 * Execute the statements
1762 rc = exec_stmts(estate, stmt->body);
1763 if (rc != PLPGSQL_RC_OK)
1765 if (rc == PLPGSQL_RC_EXIT)
1767 if (estate->exitlabel == NULL)
1768 /* unlabelled exit, finish the current loop */
1770 else if (stmt->label != NULL &&
1771 strcmp(stmt->label, estate->exitlabel) == 0)
1773 /* labelled exit, matches the current stmt's label */
1774 estate->exitlabel = NULL;
1779 * otherwise, we processed a labelled exit that does not
1780 * match the current statement's label, if any: return
1781 * RC_EXIT so that the EXIT continues to recurse upward.
1784 else if (rc == PLPGSQL_RC_CONTINUE)
1786 if (estate->exitlabel == NULL)
1788 /* anonymous continue, so re-run the current loop */
1792 else if (stmt->label != NULL &&
1793 strcmp(stmt->label, estate->exitlabel) == 0)
1795 /* label matches named continue, so re-run loop */
1797 estate->exitlabel = NULL;
1802 * otherwise, we processed a named continue that does not
1803 * match the current statement's label, if any: return
1804 * RC_CONTINUE so that the CONTINUE will propagate up the
1810 * We're aborting the loop, so cleanup and set FOUND. (This
1811 * code should match the code after the loop.)
1813 SPI_freetuptable(tuptab);
1814 SPI_cursor_close(portal);
1815 exec_set_found(estate, found);
1821 SPI_freetuptable(tuptab);
1824 * Fetch the next 50 tuples
1826 SPI_cursor_fetch(portal, true, 50);
1828 tuptab = SPI_tuptable;
1832 * Release last group of tuples
1834 SPI_freetuptable(tuptab);
1837 * Close the implicit cursor
1839 SPI_cursor_close(portal);
1842 * Set the FOUND variable to indicate the result of executing the loop
1843 * (namely, whether we looped one or more times). This must be set here so
1844 * that it does not interfere with the value of the FOUND variable inside
1845 * the loop processing itself.
1847 exec_set_found(estate, found);
1854 * exec_stmt_exit Implements EXIT and CONTINUE
1856 * This begins the process of exiting / restarting a loop.
1860 exec_stmt_exit(PLpgSQL_execstate *estate, PLpgSQL_stmt_exit *stmt)
1863 * If the exit / continue has a condition, evaluate it
1865 if (stmt->cond != NULL)
1870 value = exec_eval_boolean(estate, stmt->cond, &isnull);
1871 exec_eval_cleanup(estate);
1872 if (isnull || value == false)
1873 return PLPGSQL_RC_OK;
1876 estate->exitlabel = stmt->label;
1878 return PLPGSQL_RC_EXIT;
1880 return PLPGSQL_RC_CONTINUE;
1885 * exec_stmt_return Evaluate an expression and start
1886 * returning from the function.
1890 exec_stmt_return(PLpgSQL_execstate *estate, PLpgSQL_stmt_return *stmt)
1893 * If processing a set-returning PL/PgSQL function, the final RETURN
1894 * indicates that the function is finished producing tuples. The rest of
1895 * the work will be done at the top level.
1897 if (estate->retisset)
1898 return PLPGSQL_RC_RETURN;
1900 /* initialize for null result (possibly a tuple) */
1901 estate->retval = (Datum) 0;
1902 estate->rettupdesc = NULL;
1903 estate->retisnull = true;
1905 if (stmt->retvarno >= 0)
1907 PLpgSQL_datum *retvar = estate->datums[stmt->retvarno];
1909 switch (retvar->dtype)
1911 case PLPGSQL_DTYPE_VAR:
1913 PLpgSQL_var *var = (PLpgSQL_var *) retvar;
1915 estate->retval = var->value;
1916 estate->retisnull = var->isnull;
1917 estate->rettype = var->datatype->typoid;
1921 case PLPGSQL_DTYPE_REC:
1923 PLpgSQL_rec *rec = (PLpgSQL_rec *) retvar;
1925 if (HeapTupleIsValid(rec->tup))
1927 estate->retval = (Datum) rec->tup;
1928 estate->rettupdesc = rec->tupdesc;
1929 estate->retisnull = false;
1934 case PLPGSQL_DTYPE_ROW:
1936 PLpgSQL_row *row = (PLpgSQL_row *) retvar;
1938 Assert(row->rowtupdesc);
1939 estate->retval = (Datum) make_tuple_from_row(estate, row,
1941 if (estate->retval == (Datum) NULL) /* should not happen */
1942 elog(ERROR, "row not compatible with its own tupdesc");
1943 estate->rettupdesc = row->rowtupdesc;
1944 estate->retisnull = false;
1949 elog(ERROR, "unrecognized dtype: %d", retvar->dtype);
1952 return PLPGSQL_RC_RETURN;
1955 if (stmt->expr != NULL)
1957 if (estate->retistuple)
1959 exec_run_select(estate, stmt->expr, 1, NULL);
1960 if (estate->eval_processed > 0)
1962 estate->retval = (Datum) estate->eval_tuptable->vals[0];
1963 estate->rettupdesc = estate->eval_tuptable->tupdesc;
1964 estate->retisnull = false;
1969 /* Normal case for scalar results */
1970 estate->retval = exec_eval_expr(estate, stmt->expr,
1971 &(estate->retisnull),
1972 &(estate->rettype));
1975 return PLPGSQL_RC_RETURN;
1979 * Special hack for function returning VOID: instead of NULL, return a
1980 * non-null VOID value. This is of dubious importance but is kept for
1981 * backwards compatibility. Note that the only other way to get here is
1982 * to have written "RETURN NULL" in a function returning tuple.
1984 if (estate->fn_rettype == VOIDOID)
1986 estate->retval = (Datum) 0;
1987 estate->retisnull = false;
1988 estate->rettype = VOIDOID;
1991 return PLPGSQL_RC_RETURN;
1995 * exec_stmt_return_next Evaluate an expression and add it to the
1996 * list of tuples returned by the current
2001 exec_stmt_return_next(PLpgSQL_execstate *estate,
2002 PLpgSQL_stmt_return_next *stmt)
2007 bool free_tuple = false;
2009 if (!estate->retisset)
2011 (errcode(ERRCODE_SYNTAX_ERROR),
2012 errmsg("cannot use RETURN NEXT in a non-SETOF function")));
2014 if (estate->tuple_store == NULL)
2015 exec_init_tuple_store(estate);
2017 /* rettupdesc will be filled by exec_init_tuple_store */
2018 tupdesc = estate->rettupdesc;
2019 natts = tupdesc->natts;
2021 if (stmt->retvarno >= 0)
2023 PLpgSQL_datum *retvar = estate->datums[stmt->retvarno];
2025 switch (retvar->dtype)
2027 case PLPGSQL_DTYPE_VAR:
2029 PLpgSQL_var *var = (PLpgSQL_var *) retvar;
2030 Datum retval = var->value;
2031 bool isNull = var->isnull;
2035 (errcode(ERRCODE_DATATYPE_MISMATCH),
2036 errmsg("wrong result type supplied in RETURN NEXT")));
2038 /* coerce type if needed */
2039 retval = exec_simple_cast_value(retval,
2040 var->datatype->typoid,
2041 tupdesc->attrs[0]->atttypid,
2042 tupdesc->attrs[0]->atttypmod,
2045 tuple = heap_form_tuple(tupdesc, &retval, &isNull);
2051 case PLPGSQL_DTYPE_REC:
2053 PLpgSQL_rec *rec = (PLpgSQL_rec *) retvar;
2055 if (!HeapTupleIsValid(rec->tup))
2057 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2058 errmsg("record \"%s\" is not assigned yet",
2060 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
2061 if (!compatible_tupdesc(tupdesc, rec->tupdesc))
2063 (errcode(ERRCODE_DATATYPE_MISMATCH),
2064 errmsg("wrong record type supplied in RETURN NEXT")));
2069 case PLPGSQL_DTYPE_ROW:
2071 PLpgSQL_row *row = (PLpgSQL_row *) retvar;
2073 tuple = make_tuple_from_row(estate, row, tupdesc);
2076 (errcode(ERRCODE_DATATYPE_MISMATCH),
2077 errmsg("wrong record type supplied in RETURN NEXT")));
2083 elog(ERROR, "unrecognized dtype: %d", retvar->dtype);
2084 tuple = NULL; /* keep compiler quiet */
2088 else if (stmt->expr)
2096 (errcode(ERRCODE_DATATYPE_MISMATCH),
2097 errmsg("wrong result type supplied in RETURN NEXT")));
2099 retval = exec_eval_expr(estate,
2104 /* coerce type if needed */
2105 retval = exec_simple_cast_value(retval,
2107 tupdesc->attrs[0]->atttypid,
2108 tupdesc->attrs[0]->atttypmod,
2111 tuple = heap_form_tuple(tupdesc, &retval, &isNull);
2115 exec_eval_cleanup(estate);
2120 (errcode(ERRCODE_SYNTAX_ERROR),
2121 errmsg("RETURN NEXT must have a parameter")));
2122 tuple = NULL; /* keep compiler quiet */
2125 if (HeapTupleIsValid(tuple))
2127 MemoryContext oldcxt;
2129 oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
2130 tuplestore_puttuple(estate->tuple_store, tuple);
2131 MemoryContextSwitchTo(oldcxt);
2134 heap_freetuple(tuple);
2137 return PLPGSQL_RC_OK;
2141 exec_init_tuple_store(PLpgSQL_execstate *estate)
2143 ReturnSetInfo *rsi = estate->rsi;
2144 MemoryContext oldcxt;
2147 * Check caller can handle a set result in the way we want
2149 if (!rsi || !IsA(rsi, ReturnSetInfo) ||
2150 (rsi->allowedModes & SFRM_Materialize) == 0 ||
2151 rsi->expectedDesc == NULL)
2153 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2154 errmsg("set-valued function called in context that cannot accept a set")));
2156 estate->tuple_store_cxt = rsi->econtext->ecxt_per_query_memory;
2158 oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
2159 estate->tuple_store = tuplestore_begin_heap(true, false, work_mem);
2160 MemoryContextSwitchTo(oldcxt);
2162 estate->rettupdesc = rsi->expectedDesc;
2166 * exec_stmt_raise Build a message and throw it with elog()
2170 exec_stmt_raise(PLpgSQL_execstate *estate, PLpgSQL_stmt_raise *stmt)
2174 ListCell *current_param;
2176 plpgsql_dstring_init(&ds);
2177 current_param = list_head(stmt->params);
2179 for (cp = stmt->message; *cp; cp++)
2182 * Occurrences of a single % are replaced by the next parameter's
2183 * external representation. Double %'s are converted to one %.
2194 plpgsql_dstring_append_char(&ds, cp[1]);
2199 if (current_param == NULL)
2201 (errcode(ERRCODE_SYNTAX_ERROR),
2202 errmsg("too few parameters specified for RAISE")));
2204 paramvalue = exec_eval_expr(estate,
2205 (PLpgSQL_expr *) lfirst(current_param),
2212 extval = convert_value_to_string(paramvalue, paramtypeid);
2213 plpgsql_dstring_append(&ds, extval);
2214 current_param = lnext(current_param);
2215 exec_eval_cleanup(estate);
2219 plpgsql_dstring_append_char(&ds, cp[0]);
2223 * If more parameters were specified than were required to process the
2224 * format string, throw an error
2226 if (current_param != NULL)
2228 (errcode(ERRCODE_SYNTAX_ERROR),
2229 errmsg("too many parameters specified for RAISE")));
2232 * Throw the error (may or may not come back)
2234 estate->err_text = raise_skip_msg; /* suppress traceback of raise */
2236 ereport(stmt->elog_level,
2237 ((stmt->elog_level >= ERROR) ? errcode(ERRCODE_RAISE_EXCEPTION) : 0,
2238 errmsg_internal("%s", plpgsql_dstring_get(&ds))));
2240 estate->err_text = NULL; /* un-suppress... */
2242 plpgsql_dstring_free(&ds);
2244 return PLPGSQL_RC_OK;
2249 * Initialize a mostly empty execution state
2253 plpgsql_estate_setup(PLpgSQL_execstate *estate,
2254 PLpgSQL_function *func,
2257 estate->retval = (Datum) 0;
2258 estate->retisnull = true;
2259 estate->rettype = InvalidOid;
2261 estate->fn_rettype = func->fn_rettype;
2262 estate->retistuple = func->fn_retistuple;
2263 estate->retisset = func->fn_retset;
2265 estate->readonly_func = func->fn_readonly;
2267 estate->rettupdesc = NULL;
2268 estate->exitlabel = NULL;
2270 estate->tuple_store = NULL;
2271 estate->tuple_store_cxt = NULL;
2274 estate->trig_nargs = 0;
2275 estate->trig_argv = NULL;
2277 estate->found_varno = func->found_varno;
2278 estate->ndatums = func->ndatums;
2279 estate->datums = palloc(sizeof(PLpgSQL_datum *) * estate->ndatums);
2280 /* caller is expected to fill the datums array */
2282 estate->eval_tuptable = NULL;
2283 estate->eval_processed = 0;
2284 estate->eval_lastoid = InvalidOid;
2286 estate->err_func = func;
2287 estate->err_stmt = NULL;
2288 estate->err_text = NULL;
2291 * Create an EState and ExprContext for evaluation of simple expressions.
2293 plpgsql_create_econtext(estate);
2296 * Let the plugin see this function before we initialize any local
2297 * PL/pgSQL variables - note that we also give the plugin a few function
2298 * pointers so it can call back into PL/pgSQL for doing things like
2299 * variable assignments and stack traces
2303 (*plugin_ptr)->error_callback = plpgsql_exec_error_callback;
2304 (*plugin_ptr)->assign_expr = exec_assign_expr;
2306 if ((*plugin_ptr)->func_setup)
2307 ((*plugin_ptr)->func_setup) (estate, func);
2312 * Release temporary memory used by expression/subselect evaluation
2314 * NB: the result of the evaluation is no longer valid after this is done,
2315 * unless it is a pass-by-value datatype.
2319 exec_eval_cleanup(PLpgSQL_execstate *estate)
2321 /* Clear result of a full SPI_execute */
2322 if (estate->eval_tuptable != NULL)
2323 SPI_freetuptable(estate->eval_tuptable);
2324 estate->eval_tuptable = NULL;
2326 /* Clear result of exec_eval_simple_expr (but keep the econtext) */
2327 if (estate->eval_econtext != NULL)
2328 ResetExprContext(estate->eval_econtext);
2333 * Generate a prepared plan
2337 exec_prepare_plan(PLpgSQL_execstate *estate,
2338 PLpgSQL_expr *expr, int cursorOptions)
2345 * We need a temporary argtypes array to load with data. (The finished
2346 * plan structure will contain a copy of it.)
2348 argtypes = (Oid *) palloc(expr->nparams * sizeof(Oid));
2350 for (i = 0; i < expr->nparams; i++)
2355 exec_eval_datum(estate, estate->datums[expr->params[i]],
2357 &argtypes[i], ¶mval, ¶misnull);
2361 * Generate and save the plan
2363 plan = SPI_prepare_cursor(expr->query, expr->nparams, argtypes,
2367 /* Some SPI errors deserve specific error messages */
2370 case SPI_ERROR_COPY:
2372 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2373 errmsg("cannot COPY to/from client in PL/pgSQL")));
2374 case SPI_ERROR_TRANSACTION:
2376 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2377 errmsg("cannot begin/end transactions in PL/pgSQL"),
2378 errhint("Use a BEGIN block with an EXCEPTION clause instead.")));
2380 elog(ERROR, "SPI_prepare_cursor failed for \"%s\": %s",
2381 expr->query, SPI_result_code_string(SPI_result));
2384 expr->plan = SPI_saveplan(plan);
2387 expr->plan_argtypes = plan->argtypes;
2388 exec_simple_check_plan(expr);
2395 * exec_stmt_execsql Execute an SQL statement (possibly with INTO).
2399 exec_stmt_execsql(PLpgSQL_execstate *estate,
2400 PLpgSQL_stmt_execsql *stmt)
2407 PLpgSQL_expr *expr = stmt->sqlstmt;
2410 * On the first call for this statement generate the plan, and detect
2411 * whether the statement is INSERT/UPDATE/DELETE
2413 if (expr->plan == NULL)
2417 exec_prepare_plan(estate, expr, 0);
2418 stmt->mod_stmt = false;
2419 foreach(l, expr->plan->plancache_list)
2421 CachedPlanSource *plansource = (CachedPlanSource *) lfirst(l);
2424 foreach(l2, plansource->plan->stmt_list)
2426 PlannedStmt *p = (PlannedStmt *) lfirst(l2);
2428 if (IsA(p, PlannedStmt) &&
2431 if (p->commandType == CMD_INSERT ||
2432 p->commandType == CMD_UPDATE ||
2433 p->commandType == CMD_DELETE)
2434 stmt->mod_stmt = true;
2441 * Now build up the values and nulls arguments for SPI_execute_plan()
2443 values = (Datum *) palloc(expr->nparams * sizeof(Datum));
2444 nulls = (char *) palloc(expr->nparams * sizeof(char));
2446 for (i = 0; i < expr->nparams; i++)
2448 PLpgSQL_datum *datum = estate->datums[expr->params[i]];
2452 exec_eval_datum(estate, datum, expr->plan_argtypes[i],
2453 ¶mtypeid, &values[i], ¶misnull);
2461 * If we have INTO, then we only need one row back ... but if we have INTO
2462 * STRICT, ask for two rows, so that we can verify the statement returns
2463 * only one. INSERT/UPDATE/DELETE are always treated strictly. Without
2464 * INTO, just run the statement to completion (tcount = 0).
2466 * We could just ask for two rows always when using INTO, but there are
2467 * some cases where demanding the extra row costs significant time, eg by
2468 * forcing completion of a sequential scan. So don't do it unless we need
2469 * to enforce strictness.
2473 if (stmt->strict || stmt->mod_stmt)
2484 rc = SPI_execute_plan(expr->plan, values, nulls,
2485 estate->readonly_func, tcount);
2488 * Check for error, and set FOUND if appropriate (for historical reasons
2489 * we set FOUND only for certain query types). Also Assert that we
2490 * identified the statement type the same as SPI did.
2495 Assert(!stmt->mod_stmt);
2496 exec_set_found(estate, (SPI_processed != 0));
2502 case SPI_OK_INSERT_RETURNING:
2503 case SPI_OK_UPDATE_RETURNING:
2504 case SPI_OK_DELETE_RETURNING:
2505 Assert(stmt->mod_stmt);
2506 exec_set_found(estate, (SPI_processed != 0));
2509 case SPI_OK_SELINTO:
2510 case SPI_OK_UTILITY:
2511 Assert(!stmt->mod_stmt);
2515 elog(ERROR, "SPI_execute_plan failed executing query \"%s\": %s",
2516 expr->query, SPI_result_code_string(rc));
2519 /* All variants should save result info for GET DIAGNOSTICS */
2520 estate->eval_processed = SPI_processed;
2521 estate->eval_lastoid = SPI_lastoid;
2523 /* Process INTO if present */
2526 SPITupleTable *tuptab = SPI_tuptable;
2527 uint32 n = SPI_processed;
2528 PLpgSQL_rec *rec = NULL;
2529 PLpgSQL_row *row = NULL;
2531 /* If the statement did not return a tuple table, complain */
2534 (errcode(ERRCODE_SYNTAX_ERROR),
2535 errmsg("INTO used with a command that cannot return data")));
2537 /* Determine if we assign to a record or a row */
2538 if (stmt->rec != NULL)
2539 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
2540 else if (stmt->row != NULL)
2541 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
2543 elog(ERROR, "unsupported target");
2546 * If SELECT ... INTO specified STRICT, and the query didn't find
2547 * exactly one row, throw an error. If STRICT was not specified, then
2548 * allow the query to find any number of rows.
2554 (errcode(ERRCODE_NO_DATA_FOUND),
2555 errmsg("query returned no rows")));
2556 /* set the target to NULL(s) */
2557 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
2561 if (n > 1 && (stmt->strict || stmt->mod_stmt))
2563 (errcode(ERRCODE_TOO_MANY_ROWS),
2564 errmsg("query returned more than one row")));
2565 /* Put the first result row into the target */
2566 exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
2570 SPI_freetuptable(SPI_tuptable);
2574 /* If the statement returned a tuple table, complain */
2575 if (SPI_tuptable != NULL)
2577 (errcode(ERRCODE_SYNTAX_ERROR),
2578 errmsg("query has no destination for result data"),
2579 (rc == SPI_OK_SELECT) ? errhint("If you want to discard the results of a SELECT, use PERFORM instead.") : 0));
2585 return PLPGSQL_RC_OK;
2590 * exec_stmt_dynexecute Execute a dynamic SQL query
2591 * (possibly with INTO).
2595 exec_stmt_dynexecute(PLpgSQL_execstate *estate,
2596 PLpgSQL_stmt_dynexecute *stmt)
2599 bool isnull = false;
2605 * First we evaluate the string expression after the EXECUTE keyword. Its
2606 * result is the querystring we have to execute.
2608 query = exec_eval_expr(estate, stmt->query, &isnull, &restype);
2611 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2612 errmsg("cannot EXECUTE a null querystring")));
2614 /* Get the C-String representation */
2615 querystr = convert_value_to_string(query, restype);
2617 exec_eval_cleanup(estate);
2620 * Call SPI_execute() without preparing a saved plan.
2622 exec_res = SPI_execute(querystr, estate->readonly_func, 0);
2630 case SPI_OK_INSERT_RETURNING:
2631 case SPI_OK_UPDATE_RETURNING:
2632 case SPI_OK_DELETE_RETURNING:
2633 case SPI_OK_UTILITY:
2639 * Also allow a zero return, which implies the querystring
2640 * contained no commands.
2644 case SPI_OK_SELINTO:
2647 * We want to disallow SELECT INTO for now, because its behavior
2648 * is not consistent with SELECT INTO in a normal plpgsql context.
2649 * (We need to reimplement EXECUTE to parse the string as a
2650 * plpgsql command, not just feed it to SPI_execute.) However,
2651 * CREATE AS should be allowed ... and since it produces the same
2652 * parsetree as SELECT INTO, there's no way to tell the difference
2653 * except to look at the source text. Wotta kluge!
2658 for (ptr = querystr; *ptr; ptr++)
2659 if (!scanner_isspace(*ptr))
2661 if (*ptr == 'S' || *ptr == 's')
2663 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2664 errmsg("EXECUTE of SELECT ... INTO is not implemented yet")));
2668 /* Some SPI errors deserve specific error messages */
2669 case SPI_ERROR_COPY:
2671 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2672 errmsg("cannot COPY to/from client in PL/pgSQL")));
2673 case SPI_ERROR_TRANSACTION:
2675 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2676 errmsg("cannot begin/end transactions in PL/pgSQL"),
2677 errhint("Use a BEGIN block with an EXCEPTION clause instead.")));
2680 elog(ERROR, "SPI_execute failed executing query \"%s\": %s",
2681 querystr, SPI_result_code_string(exec_res));
2685 /* Save result info for GET DIAGNOSTICS */
2686 estate->eval_processed = SPI_processed;
2687 estate->eval_lastoid = SPI_lastoid;
2689 /* Process INTO if present */
2692 SPITupleTable *tuptab = SPI_tuptable;
2693 uint32 n = SPI_processed;
2694 PLpgSQL_rec *rec = NULL;
2695 PLpgSQL_row *row = NULL;
2697 /* If the statement did not return a tuple table, complain */
2700 (errcode(ERRCODE_SYNTAX_ERROR),
2701 errmsg("INTO used with a command that cannot return data")));
2703 /* Determine if we assign to a record or a row */
2704 if (stmt->rec != NULL)
2705 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
2706 else if (stmt->row != NULL)
2707 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
2709 elog(ERROR, "unsupported target");
2712 * If SELECT ... INTO specified STRICT, and the query didn't find
2713 * exactly one row, throw an error. If STRICT was not specified, then
2714 * allow the query to find any number of rows.
2720 (errcode(ERRCODE_NO_DATA_FOUND),
2721 errmsg("query returned no rows")));
2722 /* set the target to NULL(s) */
2723 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
2727 if (n > 1 && stmt->strict)
2729 (errcode(ERRCODE_TOO_MANY_ROWS),
2730 errmsg("query returned more than one row")));
2731 /* Put the first result row into the target */
2732 exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
2738 * It might be a good idea to raise an error if the query returned
2739 * tuples that are being ignored, but historically we have not done
2744 /* Release any result from SPI_execute, as well as the querystring */
2745 SPI_freetuptable(SPI_tuptable);
2748 return PLPGSQL_RC_OK;
2753 * exec_stmt_dynfors Execute a dynamic query, assign each
2754 * tuple to a record or row and
2755 * execute a group of statements
2760 exec_stmt_dynfors(PLpgSQL_execstate *estate, PLpgSQL_stmt_dynfors *stmt)
2766 PLpgSQL_rec *rec = NULL;
2767 PLpgSQL_row *row = NULL;
2768 SPITupleTable *tuptab;
2775 * Determine if we assign to a record or a row
2777 if (stmt->rec != NULL)
2778 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
2779 else if (stmt->row != NULL)
2780 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
2782 elog(ERROR, "unsupported target");
2785 * Evaluate the string expression after the EXECUTE keyword. It's result
2786 * is the querystring we have to execute.
2788 query = exec_eval_expr(estate, stmt->query, &isnull, &restype);
2791 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2792 errmsg("cannot EXECUTE a null querystring")));
2794 /* Get the C-String representation */
2795 querystr = convert_value_to_string(query, restype);
2797 exec_eval_cleanup(estate);
2800 * Prepare a plan and open an implicit cursor for the query
2802 plan = SPI_prepare(querystr, 0, NULL);
2804 elog(ERROR, "SPI_prepare failed for \"%s\": %s",
2805 querystr, SPI_result_code_string(SPI_result));
2806 portal = SPI_cursor_open(NULL, plan, NULL, NULL,
2807 estate->readonly_func);
2809 elog(ERROR, "could not open implicit cursor for query \"%s\": %s",
2810 querystr, SPI_result_code_string(SPI_result));
2815 * Fetch the initial 10 tuples
2817 SPI_cursor_fetch(portal, true, 10);
2818 tuptab = SPI_tuptable;
2822 * If the query didn't return any rows, set the target to NULL and return
2823 * with FOUND = false.
2826 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
2828 found = true; /* processed at least one tuple */
2837 for (i = 0; i < n; i++)
2842 * Assign the tuple to the target
2844 exec_move_row(estate, rec, row, tuptab->vals[i], tuptab->tupdesc);
2847 * Execute the statements
2849 rc = exec_stmts(estate, stmt->body);
2851 if (rc != PLPGSQL_RC_OK)
2853 if (rc == PLPGSQL_RC_EXIT)
2855 if (estate->exitlabel == NULL)
2856 /* unlabelled exit, finish the current loop */
2858 else if (stmt->label != NULL &&
2859 strcmp(stmt->label, estate->exitlabel) == 0)
2861 /* labelled exit, matches the current stmt's label */
2862 estate->exitlabel = NULL;
2867 * otherwise, we processed a labelled exit that does not
2868 * match the current statement's label, if any: return
2869 * RC_EXIT so that the EXIT continues to recurse upward.
2872 else if (rc == PLPGSQL_RC_CONTINUE)
2874 if (estate->exitlabel == NULL)
2875 /* unlabelled continue, continue the current loop */
2877 else if (stmt->label != NULL &&
2878 strcmp(stmt->label, estate->exitlabel) == 0)
2880 /* labelled continue, matches the current stmt's label */
2881 estate->exitlabel = NULL;
2886 * otherwise, we process a labelled continue that does not
2887 * match the current statement's label, so propagate
2888 * RC_CONTINUE upward in the stack.
2893 * We're aborting the loop, so cleanup and set FOUND. (This
2894 * code should match the code after the loop.)
2896 SPI_freetuptable(tuptab);
2897 SPI_cursor_close(portal);
2898 exec_set_found(estate, found);
2904 SPI_freetuptable(tuptab);
2907 * Fetch the next 50 tuples
2909 SPI_cursor_fetch(portal, true, 50);
2911 tuptab = SPI_tuptable;
2915 * Release last group of tuples
2917 SPI_freetuptable(tuptab);
2920 * Close the implicit cursor
2922 SPI_cursor_close(portal);
2925 * Set the FOUND variable to indicate the result of executing the loop
2926 * (namely, whether we looped one or more times). This must be set here so
2927 * that it does not interfere with the value of the FOUND variable inside
2928 * the loop processing itself.
2930 exec_set_found(estate, found);
2932 return PLPGSQL_RC_OK;
2937 * exec_stmt_open Execute an OPEN cursor statement
2941 exec_stmt_open(PLpgSQL_execstate *estate, PLpgSQL_stmt_open *stmt)
2943 PLpgSQL_var *curvar = NULL;
2944 char *curname = NULL;
2945 PLpgSQL_expr *query = NULL;
2954 * Get the cursor variable and if it has an assigned name, check
2955 * that it's not in use currently.
2958 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
2959 if (!curvar->isnull)
2961 curname = DatumGetCString(DirectFunctionCall1(textout, curvar->value));
2962 if (SPI_cursor_find(curname) != NULL)
2964 (errcode(ERRCODE_DUPLICATE_CURSOR),
2965 errmsg("cursor \"%s\" already in use", curname)));
2969 * Process the OPEN according to it's type.
2972 if (stmt->query != NULL)
2975 * This is an OPEN refcursor FOR SELECT ...
2977 * We just make sure the query is planned. The real work is
2981 query = stmt->query;
2982 if (query->plan == NULL)
2983 exec_prepare_plan(estate, query, stmt->cursor_options);
2985 else if (stmt->dynquery != NULL)
2988 * This is an OPEN refcursor FOR EXECUTE ...
2997 * We evaluate the string expression after the
2998 * EXECUTE keyword. It's result is the querystring we have
3002 queryD = exec_eval_expr(estate, stmt->dynquery, &isnull, &restype);
3005 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3006 errmsg("cannot EXECUTE a null querystring")));
3008 /* Get the C-String representation */
3009 querystr = convert_value_to_string(queryD, restype);
3011 exec_eval_cleanup(estate);
3014 * Now we prepare a query plan for it and open a cursor
3017 curplan = SPI_prepare_cursor(querystr, 0, NULL, stmt->cursor_options);
3018 if (curplan == NULL)
3019 elog(ERROR, "SPI_prepare_cursor failed for \"%s\": %s",
3020 querystr, SPI_result_code_string(SPI_result));
3021 portal = SPI_cursor_open(curname, curplan, NULL, NULL,
3022 estate->readonly_func);
3024 elog(ERROR, "could not open cursor for query \"%s\": %s",
3025 querystr, SPI_result_code_string(SPI_result));
3027 SPI_freeplan(curplan);
3030 * Store the eventually assigned cursor name in the cursor variable
3034 curvar->value = DirectFunctionCall1(textin, CStringGetDatum(portal->name));
3035 curvar->isnull = false;
3036 curvar->freeval = true;
3038 return PLPGSQL_RC_OK;
3043 * This is an OPEN cursor
3045 * Note: parser should already have checked that statement supplies
3046 * args iff cursor needs them, but we check again to be safe.
3049 if (stmt->argquery != NULL)
3052 * OPEN CURSOR with args. We fake a SELECT ... INTO ...
3053 * statement to evaluate the args and put 'em into the
3057 PLpgSQL_stmt_execsql set_args;
3059 if (curvar->cursor_explicit_argrow < 0)
3061 (errcode(ERRCODE_SYNTAX_ERROR),
3062 errmsg("arguments given for cursor without arguments")));
3064 memset(&set_args, 0, sizeof(set_args));
3065 set_args.cmd_type = PLPGSQL_STMT_EXECSQL;
3066 set_args.lineno = stmt->lineno;
3067 set_args.sqlstmt = stmt->argquery;
3068 set_args.into = true;
3069 /* XXX historically this has not been STRICT */
3070 set_args.row = (PLpgSQL_row *)
3071 (estate->datums[curvar->cursor_explicit_argrow]);
3073 if (exec_stmt_execsql(estate, &set_args) != PLPGSQL_RC_OK)
3074 elog(ERROR, "open cursor failed during argument processing");
3078 if (curvar->cursor_explicit_argrow >= 0)
3080 (errcode(ERRCODE_SYNTAX_ERROR),
3081 errmsg("arguments required for cursor")));
3084 query = curvar->cursor_explicit_expr;
3085 if (query->plan == NULL)
3086 exec_prepare_plan(estate, query, curvar->cursor_options);
3090 * Here we go if we have a saved plan where we have to put
3091 * values into, either from an explicit cursor or from a
3092 * refcursor opened with OPEN ... FOR SELECT ...;
3095 values = (Datum *) palloc(query->nparams * sizeof(Datum));
3096 nulls = (char *) palloc(query->nparams * sizeof(char));
3098 for (i = 0; i < query->nparams; i++)
3100 PLpgSQL_datum *datum = estate->datums[query->params[i]];
3104 exec_eval_datum(estate, datum, query->plan_argtypes[i],
3105 ¶mtypeid, &values[i], ¶misnull);
3116 portal = SPI_cursor_open(curname, query->plan, values, nulls,
3117 estate->readonly_func);
3119 elog(ERROR, "could not open cursor: %s",
3120 SPI_result_code_string(SPI_result));
3128 * Store the eventually assigned portal name in the cursor variable
3132 curvar->value = DirectFunctionCall1(textin, CStringGetDatum(portal->name));
3133 curvar->isnull = false;
3134 curvar->freeval = true;
3136 return PLPGSQL_RC_OK;
3141 * exec_stmt_fetch Fetch from a cursor into a target, or just
3142 * move the current position of the cursor
3146 exec_stmt_fetch(PLpgSQL_execstate *estate, PLpgSQL_stmt_fetch *stmt)
3148 PLpgSQL_var *curvar = NULL;
3149 PLpgSQL_rec *rec = NULL;
3150 PLpgSQL_row *row = NULL;
3151 long how_many = stmt->how_many;
3152 SPITupleTable *tuptab;
3158 * Get the portal of the cursor by name
3161 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
3164 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3165 errmsg("cursor variable \"%s\" is NULL", curvar->refname)));
3166 curname = DatumGetCString(DirectFunctionCall1(textout, curvar->value));
3168 portal = SPI_cursor_find(curname);
3171 (errcode(ERRCODE_UNDEFINED_CURSOR),
3172 errmsg("cursor \"%s\" does not exist", curname)));
3175 /* Calculate position for FETCH_RELATIVE or FETCH_ABSOLUTE */
3180 /* XXX should be doing this in LONG not INT width */
3181 how_many = exec_eval_integer(estate, stmt->expr, &isnull);
3185 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3186 errmsg("relative or absolute cursor position is NULL")));
3188 exec_eval_cleanup(estate);
3194 * Determine if we fetch into a record or a row
3197 if (stmt->rec != NULL)
3198 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->recno]);
3199 else if (stmt->row != NULL)
3200 row = (PLpgSQL_row *) (estate->datums[stmt->row->rowno]);
3202 elog(ERROR, "unsupported target");
3205 * Fetch 1 tuple from the cursor
3208 SPI_scroll_cursor_fetch(portal, stmt->direction, how_many);
3209 tuptab = SPI_tuptable;
3213 * Set the target and the global FOUND variable appropriately.
3218 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
3219 exec_set_found(estate, false);
3223 exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
3224 exec_set_found(estate, true);
3227 SPI_freetuptable(tuptab);
3231 /* Move the cursor */
3232 SPI_scroll_cursor_move(portal, stmt->direction, how_many);
3235 /* Set the global FOUND variable appropriately. */
3236 exec_set_found(estate, n != 0);
3239 return PLPGSQL_RC_OK;
3243 * exec_stmt_close Close a cursor
3247 exec_stmt_close(PLpgSQL_execstate *estate, PLpgSQL_stmt_close *stmt)
3249 PLpgSQL_var *curvar = NULL;
3254 * Get the portal of the cursor by name
3257 curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
3260 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3261 errmsg("cursor variable \"%s\" is NULL", curvar->refname)));
3262 curname = DatumGetCString(DirectFunctionCall1(textout, curvar->value));
3264 portal = SPI_cursor_find(curname);
3267 (errcode(ERRCODE_UNDEFINED_CURSOR),
3268 errmsg("cursor \"%s\" does not exist", curname)));
3275 SPI_cursor_close(portal);
3277 return PLPGSQL_RC_OK;
3282 * exec_assign_expr Put an expression's result into
3287 exec_assign_expr(PLpgSQL_execstate *estate, PLpgSQL_datum *target,
3292 bool isnull = false;
3294 value = exec_eval_expr(estate, expr, &isnull, &valtype);
3295 exec_assign_value(estate, target, value, valtype, &isnull);
3296 exec_eval_cleanup(estate);
3301 * exec_assign_value Put a value into a target field
3305 exec_assign_value(PLpgSQL_execstate *estate,
3306 PLpgSQL_datum *target,
3307 Datum value, Oid valtype, bool *isNull)
3309 switch (target->dtype)
3311 case PLPGSQL_DTYPE_VAR:
3314 * Target is a variable
3316 PLpgSQL_var *var = (PLpgSQL_var *) target;
3319 newvalue = exec_cast_value(value, valtype, var->datatype->typoid,
3320 &(var->datatype->typinput),
3321 var->datatype->typioparam,
3322 var->datatype->atttypmod,
3325 if (*isNull && var->notnull)
3327 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3328 errmsg("NULL cannot be assigned to variable \"%s\" declared NOT NULL",
3332 * If type is by-reference, make sure we have a freshly
3333 * palloc'd copy; the originally passed value may not live as
3334 * long as the variable! But we don't need to re-copy if
3335 * exec_cast_value performed a conversion; its output must
3336 * already be palloc'd.
3338 if (!var->datatype->typbyval && !*isNull)
3340 if (newvalue == value)
3341 newvalue = datumCopy(newvalue,
3343 var->datatype->typlen);
3347 * Now free the old value. (We can't do this any earlier
3348 * because of the possibility that we are assigning the var's
3349 * old value to it, eg "foo := foo". We could optimize out
3350 * the assignment altogether in such cases, but it's too
3351 * infrequent to be worth testing for.)
3355 var->value = newvalue;
3356 var->isnull = *isNull;
3357 if (!var->datatype->typbyval && !*isNull)
3358 var->freeval = true;
3362 case PLPGSQL_DTYPE_ROW:
3365 * Target is a row variable
3367 PLpgSQL_row *row = (PLpgSQL_row *) target;
3369 /* Source must be of RECORD or composite type */
3370 if (!type_is_rowtype(valtype))
3372 (errcode(ERRCODE_DATATYPE_MISMATCH),
3373 errmsg("cannot assign non-composite value to a row variable")));
3376 /* If source is null, just assign nulls to the row */
3377 exec_move_row(estate, NULL, row, NULL, NULL);
3385 HeapTupleData tmptup;
3387 /* Else source is a tuple Datum, safe to do this: */
3388 td = DatumGetHeapTupleHeader(value);
3389 /* Extract rowtype info and find a tupdesc */
3390 tupType = HeapTupleHeaderGetTypeId(td);
3391 tupTypmod = HeapTupleHeaderGetTypMod(td);
3392 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
3393 /* Build a temporary HeapTuple control structure */
3394 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
3395 ItemPointerSetInvalid(&(tmptup.t_self));
3396 tmptup.t_tableOid = InvalidOid;
3398 exec_move_row(estate, NULL, row, &tmptup, tupdesc);
3399 ReleaseTupleDesc(tupdesc);
3404 case PLPGSQL_DTYPE_REC:
3407 * Target is a record variable
3409 PLpgSQL_rec *rec = (PLpgSQL_rec *) target;
3411 /* Source must be of RECORD or composite type */
3412 if (!type_is_rowtype(valtype))
3414 (errcode(ERRCODE_DATATYPE_MISMATCH),
3415 errmsg("cannot assign non-composite value to a record variable")));
3418 /* If source is null, just assign nulls to the record */
3419 exec_move_row(estate, rec, NULL, NULL, NULL);
3427 HeapTupleData tmptup;
3429 /* Else source is a tuple Datum, safe to do this: */
3430 td = DatumGetHeapTupleHeader(value);
3431 /* Extract rowtype info and find a tupdesc */
3432 tupType = HeapTupleHeaderGetTypeId(td);
3433 tupTypmod = HeapTupleHeaderGetTypMod(td);
3434 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
3435 /* Build a temporary HeapTuple control structure */
3436 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
3437 ItemPointerSetInvalid(&(tmptup.t_self));
3438 tmptup.t_tableOid = InvalidOid;
3440 exec_move_row(estate, rec, NULL, &tmptup, tupdesc);
3441 ReleaseTupleDesc(tupdesc);
3446 case PLPGSQL_DTYPE_RECFIELD:
3449 * Target is a field of a record
3451 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) target;
3464 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
3467 * Check that there is already a tuple in the record. We need
3468 * that because records don't have any predefined field
3471 if (!HeapTupleIsValid(rec->tup))
3473 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3474 errmsg("record \"%s\" is not assigned yet",
3476 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
3479 * Get the number of the records field to change and the
3480 * number of attributes in the tuple.
3482 fno = SPI_fnumber(rec->tupdesc, recfield->fieldname);
3483 if (fno == SPI_ERROR_NOATTRIBUTE)
3485 (errcode(ERRCODE_UNDEFINED_COLUMN),
3486 errmsg("record \"%s\" has no field \"%s\"",
3487 rec->refname, recfield->fieldname)));
3489 natts = rec->tupdesc->natts;
3492 * Set up values/datums arrays for heap_formtuple. For all
3493 * the attributes except the one we want to replace, use the
3494 * value that's in the old tuple.
3496 values = palloc(sizeof(Datum) * natts);
3497 nulls = palloc(natts);
3499 for (i = 0; i < natts; i++)
3503 values[i] = SPI_getbinval(rec->tup, rec->tupdesc,
3512 * Now insert the new value, being careful to cast it to the
3515 atttype = SPI_gettypeid(rec->tupdesc, fno + 1);
3516 atttypmod = rec->tupdesc->attrs[fno]->atttypmod;
3517 attisnull = *isNull;
3518 values[fno] = exec_simple_cast_value(value,
3529 * Avoid leaking the result of exec_simple_cast_value, if it
3530 * performed a conversion to a pass-by-ref type.
3532 if (!attisnull && values[fno] != value && !get_typbyval(atttype))
3533 mustfree = DatumGetPointer(values[fno]);
3538 * Now call heap_formtuple() to create a new tuple that
3539 * replaces the old one in the record.
3541 newtup = heap_formtuple(rec->tupdesc, values, nulls);
3544 heap_freetuple(rec->tup);
3547 rec->freetup = true;
3557 case PLPGSQL_DTYPE_ARRAYELEM:
3561 PLpgSQL_expr *subscripts[MAXDIM];
3562 int subscriptvals[MAXDIM];
3563 bool oldarrayisnull;
3570 Datum oldarraydatum,
3572 ArrayType *oldarrayval;
3573 ArrayType *newarrayval;
3576 * Target is an element of an array
3578 * To handle constructs like x[1][2] := something, we have to
3579 * be prepared to deal with a chain of arrayelem datums. Chase
3580 * back to find the base array datum, and save the subscript
3581 * expressions as we go. (We are scanning right to left here,
3582 * but want to evaluate the subscripts left-to-right to
3583 * minimize surprises.)
3588 PLpgSQL_arrayelem *arrayelem = (PLpgSQL_arrayelem *) target;
3590 if (nsubscripts >= MAXDIM)
3592 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
3593 errmsg("number of array dimensions exceeds the maximum allowed, %d",
3595 subscripts[nsubscripts++] = arrayelem->subscript;
3596 target = estate->datums[arrayelem->arrayparentno];
3597 } while (target->dtype == PLPGSQL_DTYPE_ARRAYELEM);
3599 /* Fetch current value of array datum */
3600 exec_eval_datum(estate, target, InvalidOid,
3601 &arraytypeid, &oldarraydatum, &oldarrayisnull);
3603 arrayelemtypeid = get_element_type(arraytypeid);
3604 if (!OidIsValid(arrayelemtypeid))
3606 (errcode(ERRCODE_DATATYPE_MISMATCH),
3607 errmsg("subscripted object is not an array")));
3609 get_typlenbyvalalign(arrayelemtypeid,
3613 arraytyplen = get_typlen(arraytypeid);
3616 * Evaluate the subscripts, switch into left-to-right order.
3617 * Like ExecEvalArrayRef(), complain if any subscript is null.
3619 for (i = 0; i < nsubscripts; i++)
3624 exec_eval_integer(estate,
3625 subscripts[nsubscripts - 1 - i],
3629 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3630 errmsg("array subscript in assignment must not be NULL")));
3633 /* Coerce source value to match array element type. */
3634 coerced_value = exec_simple_cast_value(value,
3641 * If the original array is null, cons up an empty array so
3642 * that the assignment can proceed; we'll end with a
3643 * one-element array containing just the assigned-to
3644 * subscript. This only works for varlena arrays, though; for
3645 * fixed-length array types we skip the assignment. We can't
3646 * support assignment of a null entry into a fixed-length
3647 * array, either, so that's a no-op too. This is all ugly but
3648 * corresponds to the current behavior of ExecEvalArrayRef().
3650 if (arraytyplen > 0 && /* fixed-length array? */
3651 (oldarrayisnull || *isNull))
3655 oldarrayval = construct_empty_array(arrayelemtypeid);
3657 oldarrayval = (ArrayType *) DatumGetPointer(oldarraydatum);
3660 * Build the modified array value.
3662 newarrayval = array_set(oldarrayval,
3673 * Avoid leaking the result of exec_simple_cast_value, if it
3674 * performed a conversion to a pass-by-ref type.
3676 if (!*isNull && coerced_value != value && !elemtypbyval)
3677 pfree(DatumGetPointer(coerced_value));
3680 * Assign the new array to the base variable. It's never NULL
3684 exec_assign_value(estate, target,
3685 PointerGetDatum(newarrayval),
3686 arraytypeid, isNull);
3689 * Avoid leaking the modified array value, too.
3696 elog(ERROR, "unrecognized dtype: %d", target->dtype);
3701 * exec_eval_datum Get current value of a PLpgSQL_datum
3703 * The type oid, value in Datum format, and null flag are returned.
3705 * If expectedtypeid isn't InvalidOid, it is checked against the actual type.
3707 * At present this doesn't handle PLpgSQL_expr or PLpgSQL_arrayelem datums.
3709 * NOTE: caller must not modify the returned value, since it points right
3710 * at the stored value in the case of pass-by-reference datatypes. In some
3711 * cases we have to palloc a return value, and in such cases we put it into
3712 * the estate's short-term memory context.
3715 exec_eval_datum(PLpgSQL_execstate *estate,
3716 PLpgSQL_datum *datum,
3722 MemoryContext oldcontext;
3724 switch (datum->dtype)
3726 case PLPGSQL_DTYPE_VAR:
3728 PLpgSQL_var *var = (PLpgSQL_var *) datum;
3730 *typeid = var->datatype->typoid;
3731 *value = var->value;
3732 *isnull = var->isnull;
3733 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3735 (errcode(ERRCODE_DATATYPE_MISMATCH),
3736 errmsg("type of \"%s\" does not match that when preparing the plan",
3741 case PLPGSQL_DTYPE_ROW:
3743 PLpgSQL_row *row = (PLpgSQL_row *) datum;
3746 if (!row->rowtupdesc) /* should not happen */
3747 elog(ERROR, "row variable has no tupdesc");
3748 /* Make sure we have a valid type/typmod setting */
3749 BlessTupleDesc(row->rowtupdesc);
3750 oldcontext = MemoryContextSwitchTo(estate->eval_econtext->ecxt_per_tuple_memory);
3751 tup = make_tuple_from_row(estate, row, row->rowtupdesc);
3752 if (tup == NULL) /* should not happen */
3753 elog(ERROR, "row not compatible with its own tupdesc");
3754 MemoryContextSwitchTo(oldcontext);
3755 *typeid = row->rowtupdesc->tdtypeid;
3756 *value = HeapTupleGetDatum(tup);
3758 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3760 (errcode(ERRCODE_DATATYPE_MISMATCH),
3761 errmsg("type of \"%s\" does not match that when preparing the plan",
3766 case PLPGSQL_DTYPE_REC:
3768 PLpgSQL_rec *rec = (PLpgSQL_rec *) datum;
3769 HeapTupleData worktup;
3771 if (!HeapTupleIsValid(rec->tup))
3773 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3774 errmsg("record \"%s\" is not assigned yet",
3776 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
3777 Assert(rec->tupdesc != NULL);
3778 /* Make sure we have a valid type/typmod setting */
3779 BlessTupleDesc(rec->tupdesc);
3782 * In a trigger, the NEW and OLD parameters are likely to be
3783 * on-disk tuples that don't have the desired Datum fields.
3784 * Copy the tuple body and insert the right values.
3786 oldcontext = MemoryContextSwitchTo(estate->eval_econtext->ecxt_per_tuple_memory);
3787 heap_copytuple_with_tuple(rec->tup, &worktup);
3788 HeapTupleHeaderSetDatumLength(worktup.t_data, worktup.t_len);
3789 HeapTupleHeaderSetTypeId(worktup.t_data, rec->tupdesc->tdtypeid);
3790 HeapTupleHeaderSetTypMod(worktup.t_data, rec->tupdesc->tdtypmod);
3791 MemoryContextSwitchTo(oldcontext);
3792 *typeid = rec->tupdesc->tdtypeid;
3793 *value = HeapTupleGetDatum(&worktup);
3795 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3797 (errcode(ERRCODE_DATATYPE_MISMATCH),
3798 errmsg("type of \"%s\" does not match that when preparing the plan",
3803 case PLPGSQL_DTYPE_RECFIELD:
3805 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) datum;
3809 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
3810 if (!HeapTupleIsValid(rec->tup))
3812 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3813 errmsg("record \"%s\" is not assigned yet",
3815 errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
3816 fno = SPI_fnumber(rec->tupdesc, recfield->fieldname);
3817 if (fno == SPI_ERROR_NOATTRIBUTE)
3819 (errcode(ERRCODE_UNDEFINED_COLUMN),
3820 errmsg("record \"%s\" has no field \"%s\"",
3821 rec->refname, recfield->fieldname)));
3822 *typeid = SPI_gettypeid(rec->tupdesc, fno);
3823 *value = SPI_getbinval(rec->tup, rec->tupdesc, fno, isnull);
3824 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3826 (errcode(ERRCODE_DATATYPE_MISMATCH),
3827 errmsg("type of \"%s.%s\" does not match that when preparing the plan",
3828 rec->refname, recfield->fieldname)));
3832 case PLPGSQL_DTYPE_TRIGARG:
3834 PLpgSQL_trigarg *trigarg = (PLpgSQL_trigarg *) datum;
3838 tgargno = exec_eval_integer(estate, trigarg->argnum, isnull);
3839 if (*isnull || tgargno < 0 || tgargno >= estate->trig_nargs)
3846 *value = estate->trig_argv[tgargno];
3849 if (expectedtypeid != InvalidOid && expectedtypeid != *typeid)
3851 (errcode(ERRCODE_DATATYPE_MISMATCH),
3852 errmsg("type of tgargv[%d] does not match that when preparing the plan",
3858 elog(ERROR, "unrecognized dtype: %d", datum->dtype);
3863 * exec_eval_integer Evaluate an expression, coerce result to int4
3865 * Note we do not do exec_eval_cleanup here; the caller must do it at
3866 * some later point. (We do this because the caller may be holding the
3867 * results of other, pass-by-reference, expression evaluations, such as
3868 * an array value to be subscripted. Also see notes in exec_eval_simple_expr
3869 * about allocation of the parameter array.)
3873 exec_eval_integer(PLpgSQL_execstate *estate,
3880 exprdatum = exec_eval_expr(estate, expr, isNull, &exprtypeid);
3881 exprdatum = exec_simple_cast_value(exprdatum, exprtypeid,
3884 return DatumGetInt32(exprdatum);
3888 * exec_eval_boolean Evaluate an expression, coerce result to bool
3890 * Note we do not do exec_eval_cleanup here; the caller must do it at
3895 exec_eval_boolean(PLpgSQL_execstate *estate,
3902 exprdatum = exec_eval_expr(estate, expr, isNull, &exprtypeid);
3903 exprdatum = exec_simple_cast_value(exprdatum, exprtypeid,
3906 return DatumGetBool(exprdatum);
3910 * exec_eval_expr Evaluate an expression and return
3913 * NOTE: caller must do exec_eval_cleanup when done with the Datum.
3917 exec_eval_expr(PLpgSQL_execstate *estate,
3926 * If first time through, create a plan for this expression.
3928 if (expr->plan == NULL)
3929 exec_prepare_plan(estate, expr, 0);
3932 * If this is a simple expression, bypass SPI and use the executor
3935 if (exec_eval_simple_expr(estate, expr, &result, isNull, rettype))
3939 * Else do it the hard way via exec_run_select
3941 rc = exec_run_select(estate, expr, 2, NULL);
3942 if (rc != SPI_OK_SELECT)
3944 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3945 errmsg("query \"%s\" did not return data", expr->query)));
3948 * If there are no rows selected, the result is NULL.
3950 if (estate->eval_processed == 0)
3957 * Check that the expression returned one single Datum
3959 if (estate->eval_processed > 1)
3961 (errcode(ERRCODE_CARDINALITY_VIOLATION),
3962 errmsg("query \"%s\" returned more than one row",
3964 if (estate->eval_tuptable->tupdesc->natts != 1)
3966 (errcode(ERRCODE_SYNTAX_ERROR),
3967 errmsg("query \"%s\" returned %d columns", expr->query,
3968 estate->eval_tuptable->tupdesc->natts)));
3971 * Return the result and its type
3973 *rettype = SPI_gettypeid(estate->eval_tuptable->tupdesc, 1);
3974 return SPI_getbinval(estate->eval_tuptable->vals[0],
3975 estate->eval_tuptable->tupdesc, 1, isNull);
3980 * exec_run_select Execute a select query
3984 exec_run_select(PLpgSQL_execstate *estate,
3985 PLpgSQL_expr *expr, long maxtuples, Portal *portalP)
3993 * On the first call for this expression generate the plan
3995 if (expr->plan == NULL)
3996 exec_prepare_plan(estate, expr, 0);
3999 * Now build up the values and nulls arguments for SPI_execute_plan()
4001 values = (Datum *) palloc(expr->nparams * sizeof(Datum));
4002 nulls = (char *) palloc(expr->nparams * sizeof(char));
4004 for (i = 0; i < expr->nparams; i++)
4006 PLpgSQL_datum *datum = estate->datums[expr->params[i]];
4010 exec_eval_datum(estate, datum, expr->plan_argtypes[i],
4011 ¶mtypeid, &values[i], ¶misnull);
4019 * If a portal was requested, put the query into the portal
4021 if (portalP != NULL)
4023 *portalP = SPI_cursor_open(NULL, expr->plan, values, nulls,
4024 estate->readonly_func);
4025 if (*portalP == NULL)
4026 elog(ERROR, "could not open implicit cursor for query \"%s\": %s",
4027 expr->query, SPI_result_code_string(SPI_result));
4030 return SPI_OK_CURSOR;
4036 rc = SPI_execute_plan(expr->plan, values, nulls,
4037 estate->readonly_func, maxtuples);
4038 if (rc != SPI_OK_SELECT)
4040 (errcode(ERRCODE_SYNTAX_ERROR),
4041 errmsg("query \"%s\" is not a SELECT", expr->query)));
4043 /* Save query results for eventual cleanup */
4044 Assert(estate->eval_tuptable == NULL);
4045 estate->eval_tuptable = SPI_tuptable;
4046 estate->eval_processed = SPI_processed;
4047 estate->eval_lastoid = SPI_lastoid;
4057 * exec_eval_simple_expr - Evaluate a simple expression returning
4058 * a Datum by directly calling ExecEvalExpr().
4060 * If successful, store results into *result, *isNull, *rettype and return
4061 * TRUE. If the expression is not simple (any more), return FALSE.
4063 * It is possible though unlikely for a simple expression to become non-simple
4064 * (consider for example redefining a trivial view). We must handle that for
4065 * correctness; fortunately it's normally inexpensive to do
4066 * RevalidateCachedPlan on a simple expression. We do not consider the other
4067 * direction (non-simple expression becoming simple) because we'll still give
4068 * correct results if that happens, and it's unlikely to be worth the cycles
4071 * Note: if pass-by-reference, the result is in the eval_econtext's
4072 * temporary memory context. It will be freed when exec_eval_cleanup
4077 exec_eval_simple_expr(PLpgSQL_execstate *estate,
4083 ExprContext *econtext = estate->eval_econtext;
4084 CachedPlanSource *plansource;
4086 ParamListInfo paramLI;
4088 Snapshot saveActiveSnapshot;
4091 * Forget it if expression wasn't simple before.
4093 if (expr->expr_simple_expr == NULL)
4097 * Revalidate cached plan, so that we will notice if it became stale.
4098 * (We also need to hold a refcount while using the plan.) Note that
4099 * even if replanning occurs, the length of plancache_list can't change,
4100 * since it is a property of the raw parsetree generated from the query
4103 Assert(list_length(expr->plan->plancache_list) == 1);
4104 plansource = (CachedPlanSource *) linitial(expr->plan->plancache_list);
4105 cplan = RevalidateCachedPlan(plansource, true);
4106 if (cplan->generation != expr->expr_simple_generation)
4108 /* It got replanned ... is it still simple? */
4109 exec_simple_check_plan(expr);
4110 if (expr->expr_simple_expr == NULL)
4112 /* Ooops, release refcount and fail */
4113 ReleaseCachedPlan(cplan, true);
4119 * Pass back previously-determined result type.
4121 *rettype = expr->expr_simple_type;
4124 * Prepare the expression for execution, if it's not been done already in
4125 * the current eval_estate. (This will be forced to happen if we called
4126 * exec_simple_check_plan above.)
4128 if (expr->expr_simple_id != estate->eval_estate_simple_id)
4130 expr->expr_simple_state = ExecPrepareExpr(expr->expr_simple_expr,
4131 estate->eval_estate);
4132 expr->expr_simple_id = estate->eval_estate_simple_id;
4136 * Param list can live in econtext's temporary memory context.
4138 * XXX think about avoiding repeated palloc's for param lists? Beware
4139 * however that this routine is re-entrant: exec_eval_datum() can call it
4140 * back for subscript evaluation, and so there can be a need to have more
4141 * than one active param list.
4143 if (expr->nparams > 0)
4145 /* sizeof(ParamListInfoData) includes the first array element */
4146 paramLI = (ParamListInfo)
4147 MemoryContextAlloc(econtext->ecxt_per_tuple_memory,
4148 sizeof(ParamListInfoData) +
4149 (expr->nparams - 1) *sizeof(ParamExternData));
4150 paramLI->numParams = expr->nparams;
4152 for (i = 0; i < expr->nparams; i++)
4154 ParamExternData *prm = ¶mLI->params[i];
4155 PLpgSQL_datum *datum = estate->datums[expr->params[i]];
4158 exec_eval_datum(estate, datum, expr->plan_argtypes[i],
4160 &prm->value, &prm->isnull);
4167 * Now we can safely make the econtext point to the param list.
4169 econtext->ecxt_param_list_info = paramLI;
4172 * We have to do some of the things SPI_execute_plan would do, in
4173 * particular advance the snapshot if we are in a non-read-only function.
4174 * Without this, stable functions within the expression would fail to see
4175 * updates made so far by our own function.
4178 saveActiveSnapshot = ActiveSnapshot;
4182 MemoryContext oldcontext;
4184 oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
4185 if (!estate->readonly_func)
4187 CommandCounterIncrement();
4188 ActiveSnapshot = CopySnapshot(GetTransactionSnapshot());
4192 * Finally we can call the executor to evaluate the expression
4194 *result = ExecEvalExpr(expr->expr_simple_state,
4198 MemoryContextSwitchTo(oldcontext);
4202 /* Restore global vars and propagate error */
4203 ActiveSnapshot = saveActiveSnapshot;
4208 ActiveSnapshot = saveActiveSnapshot;
4212 * Now we can release our refcount on the cached plan.
4214 ReleaseCachedPlan(cplan, true);
4224 * exec_move_row Move one tuple's values into a record or row
4228 exec_move_row(PLpgSQL_execstate *estate,
4231 HeapTuple tup, TupleDesc tupdesc)
4234 * Record is simple - just copy the tuple and its descriptor into the
4240 * copy input first, just in case it is pointing at variable's value
4242 if (HeapTupleIsValid(tup))
4243 tup = heap_copytuple(tup);
4245 tupdesc = CreateTupleDescCopy(tupdesc);
4249 heap_freetuple(rec->tup);
4250 rec->freetup = false;
4252 if (rec->freetupdesc)
4254 FreeTupleDesc(rec->tupdesc);
4255 rec->freetupdesc = false;
4258 if (HeapTupleIsValid(tup))
4261 rec->freetup = true;
4265 /* If we have a tupdesc but no data, form an all-nulls tuple */
4268 nulls = (char *) palloc(tupdesc->natts * sizeof(char));
4269 memset(nulls, 'n', tupdesc->natts * sizeof(char));
4271 rec->tup = heap_formtuple(tupdesc, NULL, nulls);
4272 rec->freetup = true;
4281 rec->tupdesc = tupdesc;
4282 rec->freetupdesc = true;
4285 rec->tupdesc = NULL;
4291 * Row is a bit more complicated in that we assign the individual
4292 * attributes of the tuple to the variables the row points to.
4294 * NOTE: this code used to demand row->nfields == HeapTupleHeaderGetNatts(tup->t_data,
4295 * but that's wrong. The tuple might have more fields than we expected if
4296 * it's from an inheritance-child table of the current table, or it might
4297 * have fewer if the table has had columns added by ALTER TABLE. Ignore
4298 * extra columns and assume NULL for missing columns, the same as
4299 * heap_getattr would do. We also have to skip over dropped columns in
4300 * either the source or destination.
4302 * If we have no tuple data at all, we'll assign NULL to all columns of
4311 if (HeapTupleIsValid(tup))
4312 t_natts = HeapTupleHeaderGetNatts(tup->t_data);
4317 for (fnum = 0; fnum < row->nfields; fnum++)
4324 if (row->varnos[fnum] < 0)
4325 continue; /* skip dropped column in row struct */
4327 var = (PLpgSQL_var *) (estate->datums[row->varnos[fnum]]);
4329 while (anum < t_natts && tupdesc->attrs[anum]->attisdropped)
4330 anum++; /* skip dropped column in tuple */
4334 value = SPI_getbinval(tup, tupdesc, anum + 1, &isnull);
4335 valtype = SPI_gettypeid(tupdesc, anum + 1);
4342 valtype = InvalidOid;
4345 exec_assign_value(estate, (PLpgSQL_datum *) var,
4346 value, valtype, &isnull);
4352 elog(ERROR, "unsupported target");
4356 * make_tuple_from_row Make a tuple from the values of a row object
4358 * A NULL return indicates rowtype mismatch; caller must raise suitable error
4362 make_tuple_from_row(PLpgSQL_execstate *estate,
4366 int natts = tupdesc->natts;
4372 if (natts != row->nfields)
4375 dvalues = (Datum *) palloc0(natts * sizeof(Datum));
4376 nulls = (bool *) palloc(natts * sizeof(bool));
4378 for (i = 0; i < natts; i++)
4382 if (tupdesc->attrs[i]->attisdropped)
4384 nulls[i] = true; /* leave the column as null */
4387 if (row->varnos[i] < 0) /* should not happen */
4388 elog(ERROR, "dropped rowtype entry for non-dropped column");
4390 exec_eval_datum(estate, estate->datums[row->varnos[i]],
4391 InvalidOid, &fieldtypeid, &dvalues[i], &nulls[i]);
4392 if (fieldtypeid != tupdesc->attrs[i]->atttypid)
4396 tuple = heap_form_tuple(tupdesc, dvalues, nulls);
4405 * convert_value_to_string Convert a non-null Datum to C string
4407 * Note: callers generally assume that the result is a palloc'd string and
4408 * should be pfree'd. This is not all that safe an assumption ...
4410 * Note: not caching the conversion function lookup is bad for performance.
4414 convert_value_to_string(Datum value, Oid valtype)
4420 getTypeOutputInfo(valtype, &typoutput, &typIsVarlena);
4423 * We do SPI_push to allow the datatype output function to use SPI.
4424 * However we do not mess around with CommandCounterIncrement or advancing
4425 * the snapshot, which means that a stable output function would not see
4426 * updates made so far by our own function. The use-case for such
4427 * scenarios seems too narrow to justify the cycles that would be
4432 str = OidOutputFunctionCall(typoutput, value);
4440 * exec_cast_value Cast a value if required
4444 exec_cast_value(Datum value, Oid valtype,
4452 * If the type of the queries return value isn't that of the variable,
4455 if (valtype != reqtype || reqtypmod != -1)
4461 extval = convert_value_to_string(value, valtype);
4463 /* Allow input function to use SPI ... see notes above */
4466 value = InputFunctionCall(reqinput, extval,
4467 reqtypioparam, reqtypmod);
4477 value = InputFunctionCall(reqinput, NULL,
4478 reqtypioparam, reqtypmod);
4488 * exec_simple_cast_value Cast a value if required
4490 * As above, but need not supply details about target type. Note that this
4491 * is slower than exec_cast_value with cached type info, and so should be
4492 * avoided in heavily used code paths.
4496 exec_simple_cast_value(Datum value, Oid valtype,
4497 Oid reqtype, int32 reqtypmod,
4502 if (valtype != reqtype || reqtypmod != -1)
4506 FmgrInfo finfo_input;
4508 getTypeInputInfo(reqtype, &typinput, &typioparam);
4510 fmgr_info(typinput, &finfo_input);
4512 value = exec_cast_value(value,
4527 * exec_simple_check_node - Recursively check if an expression
4528 * is made only of simple things we can
4529 * hand out directly to ExecEvalExpr()
4530 * instead of calling SPI.
4534 exec_simple_check_node(Node *node)
4539 switch (nodeTag(node))
4549 ArrayRef *expr = (ArrayRef *) node;
4551 if (!exec_simple_check_node((Node *) expr->refupperindexpr))
4553 if (!exec_simple_check_node((Node *) expr->reflowerindexpr))
4555 if (!exec_simple_check_node((Node *) expr->refexpr))
4557 if (!exec_simple_check_node((Node *) expr->refassgnexpr))
4565 FuncExpr *expr = (FuncExpr *) node;
4567 if (expr->funcretset)
4569 if (!exec_simple_check_node((Node *) expr->args))
4577 OpExpr *expr = (OpExpr *) node;
4581 if (!exec_simple_check_node((Node *) expr->args))
4587 case T_DistinctExpr:
4589 DistinctExpr *expr = (DistinctExpr *) node;
4593 if (!exec_simple_check_node((Node *) expr->args))
4599 case T_ScalarArrayOpExpr:
4601 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
4603 if (!exec_simple_check_node((Node *) expr->args))
4611 BoolExpr *expr = (BoolExpr *) node;
4613 if (!exec_simple_check_node((Node *) expr->args))
4620 return exec_simple_check_node((Node *) ((FieldSelect *) node)->arg);
4624 FieldStore *expr = (FieldStore *) node;
4626 if (!exec_simple_check_node((Node *) expr->arg))
4628 if (!exec_simple_check_node((Node *) expr->newvals))
4635 return exec_simple_check_node((Node *) ((RelabelType *) node)->arg);
4638 return exec_simple_check_node((Node *) ((CoerceViaIO *) node)->arg);
4640 case T_ArrayCoerceExpr:
4641 return exec_simple_check_node((Node *) ((ArrayCoerceExpr *) node)->arg);
4643 case T_ConvertRowtypeExpr:
4644 return exec_simple_check_node((Node *) ((ConvertRowtypeExpr *) node)->arg);
4648 CaseExpr *expr = (CaseExpr *) node;
4650 if (!exec_simple_check_node((Node *) expr->arg))
4652 if (!exec_simple_check_node((Node *) expr->args))
4654 if (!exec_simple_check_node((Node *) expr->defresult))
4662 CaseWhen *when = (CaseWhen *) node;
4664 if (!exec_simple_check_node((Node *) when->expr))
4666 if (!exec_simple_check_node((Node *) when->result))
4672 case T_CaseTestExpr:
4677 ArrayExpr *expr = (ArrayExpr *) node;
4679 if (!exec_simple_check_node((Node *) expr->elements))
4687 RowExpr *expr = (RowExpr *) node;
4689 if (!exec_simple_check_node((Node *) expr->args))
4695 case T_RowCompareExpr:
4697 RowCompareExpr *expr = (RowCompareExpr *) node;
4699 if (!exec_simple_check_node((Node *) expr->largs))
4701 if (!exec_simple_check_node((Node *) expr->rargs))
4707 case T_CoalesceExpr:
4709 CoalesceExpr *expr = (CoalesceExpr *) node;
4711 if (!exec_simple_check_node((Node *) expr->args))
4719 MinMaxExpr *expr = (MinMaxExpr *) node;
4721 if (!exec_simple_check_node((Node *) expr->args))
4729 XmlExpr *expr = (XmlExpr *) node;
4731 if (!exec_simple_check_node((Node *) expr->named_args))
4733 if (!exec_simple_check_node((Node *) expr->args))
4741 NullIfExpr *expr = (NullIfExpr *) node;
4745 if (!exec_simple_check_node((Node *) expr->args))
4752 return exec_simple_check_node((Node *) ((NullTest *) node)->arg);
4755 return exec_simple_check_node((Node *) ((BooleanTest *) node)->arg);
4757 case T_CoerceToDomain:
4758 return exec_simple_check_node((Node *) ((CoerceToDomain *) node)->arg);
4760 case T_CoerceToDomainValue:
4765 List *expr = (List *) node;
4770 if (!exec_simple_check_node(lfirst(l)))
4784 * exec_simple_check_plan - Check if a plan is simple enough to
4785 * be evaluated by ExecEvalExpr() instead
4790 exec_simple_check_plan(PLpgSQL_expr *expr)
4792 CachedPlanSource *plansource;
4798 * Initialize to "not simple", and remember the plan generation number
4799 * we last checked. (If the query produces more or less than one parsetree
4800 * we just leave expr_simple_generation set to 0.)
4802 expr->expr_simple_expr = NULL;
4803 expr->expr_simple_generation = 0;
4806 * 1. We can only evaluate queries that resulted in one single execution
4809 if (list_length(expr->plan->plancache_list) != 1)
4811 plansource = (CachedPlanSource *) linitial(expr->plan->plancache_list);
4812 expr->expr_simple_generation = plansource->generation;
4813 if (list_length(plansource->plan->stmt_list) != 1)
4816 stmt = (PlannedStmt *) linitial(plansource->plan->stmt_list);
4819 * 2. It must be a RESULT plan --> no scan's required
4821 if (!IsA(stmt, PlannedStmt))
4823 plan = stmt->planTree;
4824 if (!IsA(plan, Result))
4828 * 3. Can't have any subplan or qual clause, either
4830 if (plan->lefttree != NULL ||
4831 plan->righttree != NULL ||
4832 plan->initPlan != NULL ||
4833 plan->qual != NULL ||
4834 ((Result *) plan)->resconstantqual != NULL)
4838 * 4. The plan must have a single attribute as result
4840 if (list_length(plan->targetlist) != 1)
4843 tle = (TargetEntry *) linitial(plan->targetlist);
4846 * 5. Check that all the nodes in the expression are non-scary.
4848 if (!exec_simple_check_node((Node *) tle->expr))
4852 * Yes - this is a simple expression. Mark it as such, and initialize
4853 * state to "not valid in current transaction".
4855 expr->expr_simple_expr = tle->expr;
4856 expr->expr_simple_state = NULL;
4857 expr->expr_simple_id = -1;
4858 /* Also stash away the expression result type */
4859 expr->expr_simple_type = exprType((Node *) tle->expr);
4863 * Check two tupledescs have matching number and types of attributes
4866 compatible_tupdesc(TupleDesc td1, TupleDesc td2)
4870 if (td1->natts != td2->natts)
4873 for (i = 0; i < td1->natts; i++)
4875 if (td1->attrs[i]->atttypid != td2->attrs[i]->atttypid)
4883 * exec_set_found Set the global found variable
4888 exec_set_found(PLpgSQL_execstate *estate, bool state)
4892 var = (PLpgSQL_var *) (estate->datums[estate->found_varno]);
4893 var->value = (Datum) state;
4894 var->isnull = false;
4898 * plpgsql_create_econtext --- create an eval_econtext for the current function
4900 * We may need to create a new eval_estate too, if there's not one already
4901 * for the current (sub) transaction. The EState will be cleaned up at
4902 * (sub) transaction end.
4905 plpgsql_create_econtext(PLpgSQL_execstate *estate)
4907 SubTransactionId my_subxid = GetCurrentSubTransactionId();
4908 SimpleEstateStackEntry *entry = simple_estate_stack;
4910 /* Create new EState if not one for current subxact */
4911 if (entry == NULL ||
4912 entry->xact_subxid != my_subxid)
4914 MemoryContext oldcontext;
4916 /* Stack entries are kept in TopTransactionContext for simplicity */
4917 entry = (SimpleEstateStackEntry *)
4918 MemoryContextAlloc(TopTransactionContext,
4919 sizeof(SimpleEstateStackEntry));
4921 /* But each EState should be a child of its CurTransactionContext */
4922 oldcontext = MemoryContextSwitchTo(CurTransactionContext);
4923 entry->xact_eval_estate = CreateExecutorState();
4924 MemoryContextSwitchTo(oldcontext);
4926 /* Assign a reasonably-unique ID to this EState */
4927 entry->xact_estate_simple_id = simple_estate_id_counter++;
4928 entry->xact_subxid = my_subxid;
4930 entry->next = simple_estate_stack;
4931 simple_estate_stack = entry;
4934 /* Link plpgsql estate to it */
4935 estate->eval_estate = entry->xact_eval_estate;
4936 estate->eval_estate_simple_id = entry->xact_estate_simple_id;
4938 /* And create a child econtext for the current function */
4939 estate->eval_econtext = CreateExprContext(estate->eval_estate);
4943 * plpgsql_xact_cb --- post-transaction-commit-or-abort cleanup
4945 * If a simple-expression EState was created in the current transaction,
4946 * it has to be cleaned up.
4949 plpgsql_xact_cb(XactEvent event, void *arg)
4952 * If we are doing a clean transaction shutdown, free the EState (so that
4953 * any remaining resources will be released correctly). In an abort, we
4954 * expect the regular abort recovery procedures to release everything of
4955 * interest. We don't need to free the individual stack entries since
4956 * TopTransactionContext is about to go away anyway.
4958 * Note: if plpgsql_subxact_cb is doing its job, there should be at most
4959 * one stack entry, but we may as well code this as a loop.
4961 if (event != XACT_EVENT_ABORT)
4963 while (simple_estate_stack != NULL)
4965 FreeExecutorState(simple_estate_stack->xact_eval_estate);
4966 simple_estate_stack = simple_estate_stack->next;
4970 simple_estate_stack = NULL;
4974 * plpgsql_subxact_cb --- post-subtransaction-commit-or-abort cleanup
4976 * If a simple-expression EState was created in the current subtransaction,
4977 * it has to be cleaned up.
4980 plpgsql_subxact_cb(SubXactEvent event, SubTransactionId mySubid,
4981 SubTransactionId parentSubid, void *arg)
4983 if (event == SUBXACT_EVENT_START_SUB)
4986 if (simple_estate_stack != NULL &&
4987 simple_estate_stack->xact_subxid == mySubid)
4989 SimpleEstateStackEntry *next;
4991 if (event == SUBXACT_EVENT_COMMIT_SUB)
4992 FreeExecutorState(simple_estate_stack->xact_eval_estate);
4993 next = simple_estate_stack->next;
4994 pfree(simple_estate_stack);
4995 simple_estate_stack = next;
5000 * free_var --- pfree any pass-by-reference value of the variable.
5002 * This should always be followed by some assignment to var->value,
5003 * as it leaves a dangling pointer.
5006 free_var(PLpgSQL_var *var)
5010 pfree(DatumGetPointer(var->value));
5011 var->freeval = false;