]> granicus.if.org Git - postgresql/blob - src/pl/plpgsql/src/pl_exec.c
88cb8eb1045289a9d0086bfcaddd0818bb868bcf
[postgresql] / src / pl / plpgsql / src / pl_exec.c
1 /*-------------------------------------------------------------------------
2  *
3  * pl_exec.c            - Executor for the PL/pgSQL
4  *                        procedural language
5  *
6  * Portions Copyright (c) 1996-2011, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        src/pl/plpgsql/src/pl_exec.c
12  *
13  *-------------------------------------------------------------------------
14  */
15
16 #include "plpgsql.h"
17
18 #include <ctype.h>
19
20 #include "access/transam.h"
21 #include "access/tupconvert.h"
22 #include "catalog/pg_proc.h"
23 #include "catalog/pg_type.h"
24 #include "executor/spi_priv.h"
25 #include "funcapi.h"
26 #include "miscadmin.h"
27 #include "nodes/nodeFuncs.h"
28 #include "parser/scansup.h"
29 #include "storage/proc.h"
30 #include "tcop/tcopprot.h"
31 #include "utils/array.h"
32 #include "utils/builtins.h"
33 #include "utils/datum.h"
34 #include "utils/lsyscache.h"
35 #include "utils/memutils.h"
36 #include "utils/snapmgr.h"
37 #include "utils/typcache.h"
38
39
40 static const char *const raise_skip_msg = "RAISE";
41
42 typedef struct
43 {
44         int                     nargs;                  /* number of arguments */
45         Oid                *types;                      /* types of arguments */
46         Datum      *values;                     /* evaluated argument values */
47         char       *nulls;                      /* null markers (' '/'n' style) */
48         bool       *freevals;           /* which arguments are pfree-able */
49 } PreparedParamsData;
50
51 /*
52  * All plpgsql function executions within a single transaction share the same
53  * executor EState for evaluating "simple" expressions.  Each function call
54  * creates its own "eval_econtext" ExprContext within this estate for
55  * per-evaluation workspace.  eval_econtext is freed at normal function exit,
56  * and the EState is freed at transaction end (in case of error, we assume
57  * that the abort mechanisms clean it all up).  Furthermore, any exception
58  * block within a function has to have its own eval_econtext separate from
59  * the containing function's, so that we can clean up ExprContext callbacks
60  * properly at subtransaction exit.  We maintain a stack that tracks the
61  * individual econtexts so that we can clean up correctly at subxact exit.
62  *
63  * This arrangement is a bit tedious to maintain, but it's worth the trouble
64  * so that we don't have to re-prepare simple expressions on each trip through
65  * a function.  (We assume the case to optimize is many repetitions of a
66  * function within a transaction.)
67  */
68 typedef struct SimpleEcontextStackEntry
69 {
70         ExprContext *stack_econtext;    /* a stacked econtext */
71         SubTransactionId xact_subxid;           /* ID for current subxact */
72         struct SimpleEcontextStackEntry *next;          /* next stack entry up */
73 } SimpleEcontextStackEntry;
74
75 static EState *simple_eval_estate = NULL;
76 static SimpleEcontextStackEntry *simple_econtext_stack = NULL;
77
78 /************************************************************
79  * Local function forward declarations
80  ************************************************************/
81 static void plpgsql_exec_error_callback(void *arg);
82 static PLpgSQL_datum *copy_plpgsql_datum(PLpgSQL_datum *datum);
83
84 static int exec_stmt_block(PLpgSQL_execstate *estate,
85                                 PLpgSQL_stmt_block *block);
86 static int exec_stmts(PLpgSQL_execstate *estate,
87                    List *stmts);
88 static int exec_stmt(PLpgSQL_execstate *estate,
89                   PLpgSQL_stmt *stmt);
90 static int exec_stmt_assign(PLpgSQL_execstate *estate,
91                                  PLpgSQL_stmt_assign *stmt);
92 static int exec_stmt_perform(PLpgSQL_execstate *estate,
93                                   PLpgSQL_stmt_perform *stmt);
94 static int exec_stmt_getdiag(PLpgSQL_execstate *estate,
95                                   PLpgSQL_stmt_getdiag *stmt);
96 static int exec_stmt_if(PLpgSQL_execstate *estate,
97                          PLpgSQL_stmt_if *stmt);
98 static int exec_stmt_case(PLpgSQL_execstate *estate,
99                            PLpgSQL_stmt_case *stmt);
100 static int exec_stmt_loop(PLpgSQL_execstate *estate,
101                            PLpgSQL_stmt_loop *stmt);
102 static int exec_stmt_while(PLpgSQL_execstate *estate,
103                                 PLpgSQL_stmt_while *stmt);
104 static int exec_stmt_fori(PLpgSQL_execstate *estate,
105                            PLpgSQL_stmt_fori *stmt);
106 static int exec_stmt_fors(PLpgSQL_execstate *estate,
107                            PLpgSQL_stmt_fors *stmt);
108 static int exec_stmt_forc(PLpgSQL_execstate *estate,
109                            PLpgSQL_stmt_forc *stmt);
110 static int exec_stmt_foreach_a(PLpgSQL_execstate *estate,
111                                     PLpgSQL_stmt_foreach_a *stmt);
112 static int exec_stmt_open(PLpgSQL_execstate *estate,
113                            PLpgSQL_stmt_open *stmt);
114 static int exec_stmt_fetch(PLpgSQL_execstate *estate,
115                                 PLpgSQL_stmt_fetch *stmt);
116 static int exec_stmt_close(PLpgSQL_execstate *estate,
117                                 PLpgSQL_stmt_close *stmt);
118 static int exec_stmt_exit(PLpgSQL_execstate *estate,
119                            PLpgSQL_stmt_exit *stmt);
120 static int exec_stmt_return(PLpgSQL_execstate *estate,
121                                  PLpgSQL_stmt_return *stmt);
122 static int exec_stmt_return_next(PLpgSQL_execstate *estate,
123                                           PLpgSQL_stmt_return_next *stmt);
124 static int exec_stmt_return_query(PLpgSQL_execstate *estate,
125                                            PLpgSQL_stmt_return_query *stmt);
126 static int exec_stmt_raise(PLpgSQL_execstate *estate,
127                                 PLpgSQL_stmt_raise *stmt);
128 static int exec_stmt_execsql(PLpgSQL_execstate *estate,
129                                   PLpgSQL_stmt_execsql *stmt);
130 static int exec_stmt_dynexecute(PLpgSQL_execstate *estate,
131                                          PLpgSQL_stmt_dynexecute *stmt);
132 static int exec_stmt_dynfors(PLpgSQL_execstate *estate,
133                                   PLpgSQL_stmt_dynfors *stmt);
134
135 static void plpgsql_estate_setup(PLpgSQL_execstate *estate,
136                                          PLpgSQL_function *func,
137                                          ReturnSetInfo *rsi);
138 static void exec_eval_cleanup(PLpgSQL_execstate *estate);
139
140 static void exec_prepare_plan(PLpgSQL_execstate *estate,
141                                   PLpgSQL_expr *expr, int cursorOptions);
142 static bool exec_simple_check_node(Node *node);
143 static void exec_simple_check_plan(PLpgSQL_expr *expr);
144 static bool exec_eval_simple_expr(PLpgSQL_execstate *estate,
145                                           PLpgSQL_expr *expr,
146                                           Datum *result,
147                                           bool *isNull,
148                                           Oid *rettype);
149
150 static void exec_assign_expr(PLpgSQL_execstate *estate,
151                                  PLpgSQL_datum *target,
152                                  PLpgSQL_expr *expr);
153 static void exec_assign_value(PLpgSQL_execstate *estate,
154                                   PLpgSQL_datum *target,
155                                   Datum value, Oid valtype, bool *isNull);
156 static void exec_eval_datum(PLpgSQL_execstate *estate,
157                                 PLpgSQL_datum *datum,
158                                 Oid *typeid,
159                                 int32 *typetypmod,
160                                 Datum *value,
161                                 bool *isnull);
162 static int exec_eval_integer(PLpgSQL_execstate *estate,
163                                   PLpgSQL_expr *expr,
164                                   bool *isNull);
165 static bool exec_eval_boolean(PLpgSQL_execstate *estate,
166                                   PLpgSQL_expr *expr,
167                                   bool *isNull);
168 static Datum exec_eval_expr(PLpgSQL_execstate *estate,
169                            PLpgSQL_expr *expr,
170                            bool *isNull,
171                            Oid *rettype);
172 static int exec_run_select(PLpgSQL_execstate *estate,
173                                 PLpgSQL_expr *expr, long maxtuples, Portal *portalP);
174 static int exec_for_query(PLpgSQL_execstate *estate, PLpgSQL_stmt_forq *stmt,
175                            Portal portal, bool prefetch_ok);
176 static ParamListInfo setup_param_list(PLpgSQL_execstate *estate,
177                                  PLpgSQL_expr *expr);
178 static void plpgsql_param_fetch(ParamListInfo params, int paramid);
179 static void exec_move_row(PLpgSQL_execstate *estate,
180                           PLpgSQL_rec *rec,
181                           PLpgSQL_row *row,
182                           HeapTuple tup, TupleDesc tupdesc);
183 static HeapTuple make_tuple_from_row(PLpgSQL_execstate *estate,
184                                         PLpgSQL_row *row,
185                                         TupleDesc tupdesc);
186 static char *convert_value_to_string(Datum value, Oid valtype);
187 static Datum exec_cast_value(Datum value, Oid valtype,
188                                 Oid reqtype,
189                                 FmgrInfo *reqinput,
190                                 Oid reqtypioparam,
191                                 int32 reqtypmod,
192                                 bool isnull);
193 static Datum exec_simple_cast_value(Datum value, Oid valtype,
194                                            Oid reqtype, int32 reqtypmod,
195                                            bool isnull);
196 static void exec_init_tuple_store(PLpgSQL_execstate *estate);
197 static void exec_set_found(PLpgSQL_execstate *estate, bool state);
198 static void plpgsql_create_econtext(PLpgSQL_execstate *estate);
199 static void plpgsql_destroy_econtext(PLpgSQL_execstate *estate);
200 static void free_var(PLpgSQL_var *var);
201 static void assign_text_var(PLpgSQL_var *var, const char *str);
202 static PreparedParamsData *exec_eval_using_params(PLpgSQL_execstate *estate,
203                                            List *params);
204 static void free_params_data(PreparedParamsData *ppd);
205 static Portal exec_dynquery_with_params(PLpgSQL_execstate *estate,
206                                                   PLpgSQL_expr *dynquery, List *params,
207                                                   const char *portalname, int cursorOptions);
208
209
210 /* ----------
211  * plpgsql_exec_function        Called by the call handler for
212  *                              function execution.
213  * ----------
214  */
215 Datum
216 plpgsql_exec_function(PLpgSQL_function *func, FunctionCallInfo fcinfo)
217 {
218         PLpgSQL_execstate estate;
219         ErrorContextCallback plerrcontext;
220         int                     i;
221         int                     rc;
222
223         /*
224          * Setup the execution state
225          */
226         plpgsql_estate_setup(&estate, func, (ReturnSetInfo *) fcinfo->resultinfo);
227
228         /*
229          * Setup error traceback support for ereport()
230          */
231         plerrcontext.callback = plpgsql_exec_error_callback;
232         plerrcontext.arg = &estate;
233         plerrcontext.previous = error_context_stack;
234         error_context_stack = &plerrcontext;
235
236         /*
237          * Make local execution copies of all the datums
238          */
239         estate.err_text = gettext_noop("during initialization of execution state");
240         for (i = 0; i < estate.ndatums; i++)
241                 estate.datums[i] = copy_plpgsql_datum(func->datums[i]);
242
243         /*
244          * Store the actual call argument values into the appropriate variables
245          */
246         estate.err_text = gettext_noop("while storing call arguments into local variables");
247         for (i = 0; i < func->fn_nargs; i++)
248         {
249                 int                     n = func->fn_argvarnos[i];
250
251                 switch (estate.datums[n]->dtype)
252                 {
253                         case PLPGSQL_DTYPE_VAR:
254                                 {
255                                         PLpgSQL_var *var = (PLpgSQL_var *) estate.datums[n];
256
257                                         var->value = fcinfo->arg[i];
258                                         var->isnull = fcinfo->argnull[i];
259                                         var->freeval = false;
260                                 }
261                                 break;
262
263                         case PLPGSQL_DTYPE_ROW:
264                                 {
265                                         PLpgSQL_row *row = (PLpgSQL_row *) estate.datums[n];
266
267                                         if (!fcinfo->argnull[i])
268                                         {
269                                                 HeapTupleHeader td;
270                                                 Oid                     tupType;
271                                                 int32           tupTypmod;
272                                                 TupleDesc       tupdesc;
273                                                 HeapTupleData tmptup;
274
275                                                 td = DatumGetHeapTupleHeader(fcinfo->arg[i]);
276                                                 /* Extract rowtype info and find a tupdesc */
277                                                 tupType = HeapTupleHeaderGetTypeId(td);
278                                                 tupTypmod = HeapTupleHeaderGetTypMod(td);
279                                                 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
280                                                 /* Build a temporary HeapTuple control structure */
281                                                 tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
282                                                 ItemPointerSetInvalid(&(tmptup.t_self));
283                                                 tmptup.t_tableOid = InvalidOid;
284                                                 tmptup.t_data = td;
285                                                 exec_move_row(&estate, NULL, row, &tmptup, tupdesc);
286                                                 ReleaseTupleDesc(tupdesc);
287                                         }
288                                         else
289                                         {
290                                                 /* If arg is null, treat it as an empty row */
291                                                 exec_move_row(&estate, NULL, row, NULL, NULL);
292                                         }
293                                 }
294                                 break;
295
296                         default:
297                                 elog(ERROR, "unrecognized dtype: %d", func->datums[i]->dtype);
298                 }
299         }
300
301         estate.err_text = gettext_noop("during function entry");
302
303         /*
304          * Set the magic variable FOUND to false
305          */
306         exec_set_found(&estate, false);
307
308         /*
309          * Let the instrumentation plugin peek at this function
310          */
311         if (*plugin_ptr && (*plugin_ptr)->func_beg)
312                 ((*plugin_ptr)->func_beg) (&estate, func);
313
314         /*
315          * Now call the toplevel block of statements
316          */
317         estate.err_text = NULL;
318         estate.err_stmt = (PLpgSQL_stmt *) (func->action);
319         rc = exec_stmt_block(&estate, func->action);
320         if (rc != PLPGSQL_RC_RETURN)
321         {
322                 estate.err_stmt = NULL;
323                 estate.err_text = NULL;
324
325                 /*
326                  * Provide a more helpful message if a CONTINUE or RAISE has been used
327                  * outside the context it can work in.
328                  */
329                 if (rc == PLPGSQL_RC_CONTINUE)
330                         ereport(ERROR,
331                                         (errcode(ERRCODE_SYNTAX_ERROR),
332                                          errmsg("CONTINUE cannot be used outside a loop")));
333                 else
334                         ereport(ERROR,
335                            (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
336                                 errmsg("control reached end of function without RETURN")));
337         }
338
339         /*
340          * We got a return value - process it
341          */
342         estate.err_stmt = NULL;
343         estate.err_text = gettext_noop("while casting return value to function's return type");
344
345         fcinfo->isnull = estate.retisnull;
346
347         if (estate.retisset)
348         {
349                 ReturnSetInfo *rsi = estate.rsi;
350
351                 /* Check caller can handle a set result */
352                 if (!rsi || !IsA(rsi, ReturnSetInfo) ||
353                         (rsi->allowedModes & SFRM_Materialize) == 0)
354                         ereport(ERROR,
355                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
356                                          errmsg("set-valued function called in context that cannot accept a set")));
357                 rsi->returnMode = SFRM_Materialize;
358
359                 /* If we produced any tuples, send back the result */
360                 if (estate.tuple_store)
361                 {
362                         rsi->setResult = estate.tuple_store;
363                         if (estate.rettupdesc)
364                         {
365                                 MemoryContext oldcxt;
366
367                                 oldcxt = MemoryContextSwitchTo(estate.tuple_store_cxt);
368                                 rsi->setDesc = CreateTupleDescCopy(estate.rettupdesc);
369                                 MemoryContextSwitchTo(oldcxt);
370                         }
371                 }
372                 estate.retval = (Datum) 0;
373                 fcinfo->isnull = true;
374         }
375         else if (!estate.retisnull)
376         {
377                 if (estate.retistuple)
378                 {
379                         /*
380                          * We have to check that the returned tuple actually matches the
381                          * expected result type.  XXX would be better to cache the tupdesc
382                          * instead of repeating get_call_result_type()
383                          */
384                         HeapTuple       rettup = (HeapTuple) DatumGetPointer(estate.retval);
385                         TupleDesc       tupdesc;
386                         TupleConversionMap *tupmap;
387
388                         switch (get_call_result_type(fcinfo, NULL, &tupdesc))
389                         {
390                                 case TYPEFUNC_COMPOSITE:
391                                         /* got the expected result rowtype, now check it */
392                                         tupmap = convert_tuples_by_position(estate.rettupdesc,
393                                                                                                                 tupdesc,
394                                                                                                                 gettext_noop("returned record type does not match expected record type"));
395                                         /* it might need conversion */
396                                         if (tupmap)
397                                                 rettup = do_convert_tuple(rettup, tupmap);
398                                         /* no need to free map, we're about to return anyway */
399                                         break;
400                                 case TYPEFUNC_RECORD:
401
402                                         /*
403                                          * Failed to determine actual type of RECORD.  We could
404                                          * raise an error here, but what this means in practice is
405                                          * that the caller is expecting any old generic rowtype,
406                                          * so we don't really need to be restrictive. Pass back
407                                          * the generated result type, instead.
408                                          */
409                                         tupdesc = estate.rettupdesc;
410                                         if (tupdesc == NULL)            /* shouldn't happen */
411                                                 elog(ERROR, "return type must be a row type");
412                                         break;
413                                 default:
414                                         /* shouldn't get here if retistuple is true ... */
415                                         elog(ERROR, "return type must be a row type");
416                                         break;
417                         }
418
419                         /*
420                          * Copy tuple to upper executor memory, as a tuple Datum. Make
421                          * sure it is labeled with the caller-supplied tuple type.
422                          */
423                         estate.retval = PointerGetDatum(SPI_returntuple(rettup, tupdesc));
424                 }
425                 else
426                 {
427                         /* Cast value to proper type */
428                         estate.retval = exec_cast_value(estate.retval, estate.rettype,
429                                                                                         func->fn_rettype,
430                                                                                         &(func->fn_retinput),
431                                                                                         func->fn_rettypioparam,
432                                                                                         -1,
433                                                                                         fcinfo->isnull);
434
435                         /*
436                          * If the function's return type isn't by value, copy the value
437                          * into upper executor memory context.
438                          */
439                         if (!fcinfo->isnull && !func->fn_retbyval)
440                         {
441                                 Size            len;
442                                 void       *tmp;
443
444                                 len = datumGetSize(estate.retval, false, func->fn_rettyplen);
445                                 tmp = SPI_palloc(len);
446                                 memcpy(tmp, DatumGetPointer(estate.retval), len);
447                                 estate.retval = PointerGetDatum(tmp);
448                         }
449                 }
450         }
451
452         estate.err_text = gettext_noop("during function exit");
453
454         /*
455          * Let the instrumentation plugin peek at this function
456          */
457         if (*plugin_ptr && (*plugin_ptr)->func_end)
458                 ((*plugin_ptr)->func_end) (&estate, func);
459
460         /* Clean up any leftover temporary memory */
461         plpgsql_destroy_econtext(&estate);
462         exec_eval_cleanup(&estate);
463
464         /*
465          * Pop the error context stack
466          */
467         error_context_stack = plerrcontext.previous;
468
469         /*
470          * Return the function's result
471          */
472         return estate.retval;
473 }
474
475
476 /* ----------
477  * plpgsql_exec_trigger         Called by the call handler for
478  *                              trigger execution.
479  * ----------
480  */
481 HeapTuple
482 plpgsql_exec_trigger(PLpgSQL_function *func,
483                                          TriggerData *trigdata)
484 {
485         PLpgSQL_execstate estate;
486         ErrorContextCallback plerrcontext;
487         int                     i;
488         int                     rc;
489         PLpgSQL_var *var;
490         PLpgSQL_rec *rec_new,
491                            *rec_old;
492         HeapTuple       rettup;
493
494         /*
495          * Setup the execution state
496          */
497         plpgsql_estate_setup(&estate, func, NULL);
498
499         /*
500          * Setup error traceback support for ereport()
501          */
502         plerrcontext.callback = plpgsql_exec_error_callback;
503         plerrcontext.arg = &estate;
504         plerrcontext.previous = error_context_stack;
505         error_context_stack = &plerrcontext;
506
507         /*
508          * Make local execution copies of all the datums
509          */
510         estate.err_text = gettext_noop("during initialization of execution state");
511         for (i = 0; i < estate.ndatums; i++)
512                 estate.datums[i] = copy_plpgsql_datum(func->datums[i]);
513
514         /*
515          * Put the OLD and NEW tuples into record variables
516          *
517          * We make the tupdescs available in both records even though only one may
518          * have a value.  This allows parsing of record references to succeed in
519          * functions that are used for multiple trigger types.  For example, we
520          * might have a test like "if (TG_OP = 'INSERT' and NEW.foo = 'xyz')",
521          * which should parse regardless of the current trigger type.
522          */
523         rec_new = (PLpgSQL_rec *) (estate.datums[func->new_varno]);
524         rec_new->freetup = false;
525         rec_new->tupdesc = trigdata->tg_relation->rd_att;
526         rec_new->freetupdesc = false;
527         rec_old = (PLpgSQL_rec *) (estate.datums[func->old_varno]);
528         rec_old->freetup = false;
529         rec_old->tupdesc = trigdata->tg_relation->rd_att;
530         rec_old->freetupdesc = false;
531
532         if (!TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
533         {
534                 /*
535                  * Per-statement triggers don't use OLD/NEW variables
536                  */
537                 rec_new->tup = NULL;
538                 rec_old->tup = NULL;
539         }
540         else if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
541         {
542                 rec_new->tup = trigdata->tg_trigtuple;
543                 rec_old->tup = NULL;
544         }
545         else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
546         {
547                 rec_new->tup = trigdata->tg_newtuple;
548                 rec_old->tup = trigdata->tg_trigtuple;
549         }
550         else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
551         {
552                 rec_new->tup = NULL;
553                 rec_old->tup = trigdata->tg_trigtuple;
554         }
555         else
556                 elog(ERROR, "unrecognized trigger action: not INSERT, DELETE, or UPDATE");
557
558         /*
559          * Assign the special tg_ variables
560          */
561
562         var = (PLpgSQL_var *) (estate.datums[func->tg_op_varno]);
563         if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
564                 var->value = CStringGetTextDatum("INSERT");
565         else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
566                 var->value = CStringGetTextDatum("UPDATE");
567         else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
568                 var->value = CStringGetTextDatum("DELETE");
569         else if (TRIGGER_FIRED_BY_TRUNCATE(trigdata->tg_event))
570                 var->value = CStringGetTextDatum("TRUNCATE");
571         else
572                 elog(ERROR, "unrecognized trigger action: not INSERT, DELETE, UPDATE, or TRUNCATE");
573         var->isnull = false;
574         var->freeval = true;
575
576         var = (PLpgSQL_var *) (estate.datums[func->tg_name_varno]);
577         var->value = DirectFunctionCall1(namein,
578                                                           CStringGetDatum(trigdata->tg_trigger->tgname));
579         var->isnull = false;
580         var->freeval = true;
581
582         var = (PLpgSQL_var *) (estate.datums[func->tg_when_varno]);
583         if (TRIGGER_FIRED_BEFORE(trigdata->tg_event))
584                 var->value = CStringGetTextDatum("BEFORE");
585         else if (TRIGGER_FIRED_AFTER(trigdata->tg_event))
586                 var->value = CStringGetTextDatum("AFTER");
587         else if (TRIGGER_FIRED_INSTEAD(trigdata->tg_event))
588                 var->value = CStringGetTextDatum("INSTEAD OF");
589         else
590                 elog(ERROR, "unrecognized trigger execution time: not BEFORE, AFTER, or INSTEAD OF");
591         var->isnull = false;
592         var->freeval = true;
593
594         var = (PLpgSQL_var *) (estate.datums[func->tg_level_varno]);
595         if (TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
596                 var->value = CStringGetTextDatum("ROW");
597         else if (TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
598                 var->value = CStringGetTextDatum("STATEMENT");
599         else
600                 elog(ERROR, "unrecognized trigger event type: not ROW or STATEMENT");
601         var->isnull = false;
602         var->freeval = true;
603
604         var = (PLpgSQL_var *) (estate.datums[func->tg_relid_varno]);
605         var->value = ObjectIdGetDatum(trigdata->tg_relation->rd_id);
606         var->isnull = false;
607         var->freeval = false;
608
609         var = (PLpgSQL_var *) (estate.datums[func->tg_relname_varno]);
610         var->value = DirectFunctionCall1(namein,
611                         CStringGetDatum(RelationGetRelationName(trigdata->tg_relation)));
612         var->isnull = false;
613         var->freeval = true;
614
615         var = (PLpgSQL_var *) (estate.datums[func->tg_table_name_varno]);
616         var->value = DirectFunctionCall1(namein,
617                         CStringGetDatum(RelationGetRelationName(trigdata->tg_relation)));
618         var->isnull = false;
619         var->freeval = true;
620
621         var = (PLpgSQL_var *) (estate.datums[func->tg_table_schema_varno]);
622         var->value = DirectFunctionCall1(namein,
623                                                                          CStringGetDatum(
624                                                                                                          get_namespace_name(
625                                                                                                                 RelationGetNamespace(
626                                                                                                    trigdata->tg_relation))));
627         var->isnull = false;
628         var->freeval = true;
629
630         var = (PLpgSQL_var *) (estate.datums[func->tg_nargs_varno]);
631         var->value = Int16GetDatum(trigdata->tg_trigger->tgnargs);
632         var->isnull = false;
633         var->freeval = false;
634
635         var = (PLpgSQL_var *) (estate.datums[func->tg_argv_varno]);
636         if (trigdata->tg_trigger->tgnargs > 0)
637         {
638                 /*
639                  * For historical reasons, tg_argv[] subscripts start at zero not one.
640                  * So we can't use construct_array().
641                  */
642                 int                     nelems = trigdata->tg_trigger->tgnargs;
643                 Datum      *elems;
644                 int                     dims[1];
645                 int                     lbs[1];
646
647                 elems = palloc(sizeof(Datum) * nelems);
648                 for (i = 0; i < nelems; i++)
649                         elems[i] = CStringGetTextDatum(trigdata->tg_trigger->tgargs[i]);
650                 dims[0] = nelems;
651                 lbs[0] = 0;
652
653                 var->value = PointerGetDatum(construct_md_array(elems, NULL,
654                                                                                                                 1, dims, lbs,
655                                                                                                                 TEXTOID,
656                                                                                                                 -1, false, 'i'));
657                 var->isnull = false;
658                 var->freeval = true;
659         }
660         else
661         {
662                 var->value = (Datum) 0;
663                 var->isnull = true;
664                 var->freeval = false;
665         }
666
667         estate.err_text = gettext_noop("during function entry");
668
669         /*
670          * Set the magic variable FOUND to false
671          */
672         exec_set_found(&estate, false);
673
674         /*
675          * Let the instrumentation plugin peek at this function
676          */
677         if (*plugin_ptr && (*plugin_ptr)->func_beg)
678                 ((*plugin_ptr)->func_beg) (&estate, func);
679
680         /*
681          * Now call the toplevel block of statements
682          */
683         estate.err_text = NULL;
684         estate.err_stmt = (PLpgSQL_stmt *) (func->action);
685         rc = exec_stmt_block(&estate, func->action);
686         if (rc != PLPGSQL_RC_RETURN)
687         {
688                 estate.err_stmt = NULL;
689                 estate.err_text = NULL;
690
691                 /*
692                  * Provide a more helpful message if a CONTINUE or RAISE has been used
693                  * outside the context it can work in.
694                  */
695                 if (rc == PLPGSQL_RC_CONTINUE)
696                         ereport(ERROR,
697                                         (errcode(ERRCODE_SYNTAX_ERROR),
698                                          errmsg("CONTINUE cannot be used outside a loop")));
699                 else
700                         ereport(ERROR,
701                            (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
702                                 errmsg("control reached end of trigger procedure without RETURN")));
703         }
704
705         estate.err_stmt = NULL;
706         estate.err_text = gettext_noop("during function exit");
707
708         if (estate.retisset)
709                 ereport(ERROR,
710                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
711                                  errmsg("trigger procedure cannot return a set")));
712
713         /*
714          * Check that the returned tuple structure has the same attributes, the
715          * relation that fired the trigger has. A per-statement trigger always
716          * needs to return NULL, so we ignore any return value the function itself
717          * produces (XXX: is this a good idea?)
718          *
719          * XXX This way it is possible, that the trigger returns a tuple where
720          * attributes don't have the correct atttypmod's length. It's up to the
721          * trigger's programmer to ensure that this doesn't happen. Jan
722          */
723         if (estate.retisnull || !TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
724                 rettup = NULL;
725         else
726         {
727                 TupleConversionMap *tupmap;
728
729                 rettup = (HeapTuple) DatumGetPointer(estate.retval);
730                 /* check rowtype compatibility */
731                 tupmap = convert_tuples_by_position(estate.rettupdesc,
732                                                                                         trigdata->tg_relation->rd_att,
733                                                                                         gettext_noop("returned row structure does not match the structure of the triggering table"));
734                 /* it might need conversion */
735                 if (tupmap)
736                         rettup = do_convert_tuple(rettup, tupmap);
737                 /* no need to free map, we're about to return anyway */
738
739                 /* Copy tuple to upper executor memory */
740                 rettup = SPI_copytuple(rettup);
741         }
742
743         /*
744          * Let the instrumentation plugin peek at this function
745          */
746         if (*plugin_ptr && (*plugin_ptr)->func_end)
747                 ((*plugin_ptr)->func_end) (&estate, func);
748
749         /* Clean up any leftover temporary memory */
750         plpgsql_destroy_econtext(&estate);
751         exec_eval_cleanup(&estate);
752
753         /*
754          * Pop the error context stack
755          */
756         error_context_stack = plerrcontext.previous;
757
758         /*
759          * Return the trigger's result
760          */
761         return rettup;
762 }
763
764
765 /*
766  * error context callback to let us supply a call-stack traceback
767  */
768 static void
769 plpgsql_exec_error_callback(void *arg)
770 {
771         PLpgSQL_execstate *estate = (PLpgSQL_execstate *) arg;
772
773         /* if we are doing RAISE, don't report its location */
774         if (estate->err_text == raise_skip_msg)
775                 return;
776
777         if (estate->err_text != NULL)
778         {
779                 /*
780                  * We don't expend the cycles to run gettext() on err_text unless we
781                  * actually need it.  Therefore, places that set up err_text should
782                  * use gettext_noop() to ensure the strings get recorded in the
783                  * message dictionary.
784                  *
785                  * If both err_text and err_stmt are set, use the err_text as
786                  * description, but report the err_stmt's line number.  When err_stmt
787                  * is not set, we're in function entry/exit, or some such place not
788                  * attached to a specific line number.
789                  */
790                 if (estate->err_stmt != NULL)
791                 {
792                         /*
793                          * translator: last %s is a phrase such as "during statement block
794                          * local variable initialization"
795                          */
796                         errcontext("PL/pgSQL function \"%s\" line %d %s",
797                                            estate->func->fn_name,
798                                            estate->err_stmt->lineno,
799                                            _(estate->err_text));
800                 }
801                 else
802                 {
803                         /*
804                          * translator: last %s is a phrase such as "while storing call
805                          * arguments into local variables"
806                          */
807                         errcontext("PL/pgSQL function \"%s\" %s",
808                                            estate->func->fn_name,
809                                            _(estate->err_text));
810                 }
811         }
812         else if (estate->err_stmt != NULL)
813         {
814                 /* translator: last %s is a plpgsql statement type name */
815                 errcontext("PL/pgSQL function \"%s\" line %d at %s",
816                                    estate->func->fn_name,
817                                    estate->err_stmt->lineno,
818                                    plpgsql_stmt_typename(estate->err_stmt));
819         }
820         else
821                 errcontext("PL/pgSQL function \"%s\"",
822                                    estate->func->fn_name);
823 }
824
825
826 /* ----------
827  * Support function for initializing local execution variables
828  * ----------
829  */
830 static PLpgSQL_datum *
831 copy_plpgsql_datum(PLpgSQL_datum *datum)
832 {
833         PLpgSQL_datum *result;
834
835         switch (datum->dtype)
836         {
837                 case PLPGSQL_DTYPE_VAR:
838                         {
839                                 PLpgSQL_var *new = palloc(sizeof(PLpgSQL_var));
840
841                                 memcpy(new, datum, sizeof(PLpgSQL_var));
842                                 /* Ensure the value is null (possibly not needed?) */
843                                 new->value = 0;
844                                 new->isnull = true;
845                                 new->freeval = false;
846
847                                 result = (PLpgSQL_datum *) new;
848                         }
849                         break;
850
851                 case PLPGSQL_DTYPE_REC:
852                         {
853                                 PLpgSQL_rec *new = palloc(sizeof(PLpgSQL_rec));
854
855                                 memcpy(new, datum, sizeof(PLpgSQL_rec));
856                                 /* Ensure the value is null (possibly not needed?) */
857                                 new->tup = NULL;
858                                 new->tupdesc = NULL;
859                                 new->freetup = false;
860                                 new->freetupdesc = false;
861
862                                 result = (PLpgSQL_datum *) new;
863                         }
864                         break;
865
866                 case PLPGSQL_DTYPE_ROW:
867                 case PLPGSQL_DTYPE_RECFIELD:
868                 case PLPGSQL_DTYPE_ARRAYELEM:
869
870                         /*
871                          * These datum records are read-only at runtime, so no need to
872                          * copy them
873                          */
874                         result = datum;
875                         break;
876
877                 default:
878                         elog(ERROR, "unrecognized dtype: %d", datum->dtype);
879                         result = NULL;          /* keep compiler quiet */
880                         break;
881         }
882
883         return result;
884 }
885
886
887 static bool
888 exception_matches_conditions(ErrorData *edata, PLpgSQL_condition *cond)
889 {
890         for (; cond != NULL; cond = cond->next)
891         {
892                 int                     sqlerrstate = cond->sqlerrstate;
893
894                 /*
895                  * OTHERS matches everything *except* query-canceled; if you're
896                  * foolish enough, you can match that explicitly.
897                  */
898                 if (sqlerrstate == 0)
899                 {
900                         if (edata->sqlerrcode != ERRCODE_QUERY_CANCELED)
901                                 return true;
902                 }
903                 /* Exact match? */
904                 else if (edata->sqlerrcode == sqlerrstate)
905                         return true;
906                 /* Category match? */
907                 else if (ERRCODE_IS_CATEGORY(sqlerrstate) &&
908                                  ERRCODE_TO_CATEGORY(edata->sqlerrcode) == sqlerrstate)
909                         return true;
910         }
911         return false;
912 }
913
914
915 /* ----------
916  * exec_stmt_block                      Execute a block of statements
917  * ----------
918  */
919 static int
920 exec_stmt_block(PLpgSQL_execstate *estate, PLpgSQL_stmt_block *block)
921 {
922         volatile int rc = -1;
923         int                     i;
924         int                     n;
925
926         /*
927          * First initialize all variables declared in this block
928          */
929         estate->err_text = gettext_noop("during statement block local variable initialization");
930
931         for (i = 0; i < block->n_initvars; i++)
932         {
933                 n = block->initvarnos[i];
934
935                 switch (estate->datums[n]->dtype)
936                 {
937                         case PLPGSQL_DTYPE_VAR:
938                                 {
939                                         PLpgSQL_var *var = (PLpgSQL_var *) (estate->datums[n]);
940
941                                         /* free any old value, in case re-entering block */
942                                         free_var(var);
943
944                                         /* Initially it contains a NULL */
945                                         var->value = (Datum) 0;
946                                         var->isnull = true;
947
948                                         if (var->default_val == NULL)
949                                         {
950                                                 /*
951                                                  * If needed, give the datatype a chance to reject
952                                                  * NULLs, by assigning a NULL to the variable. We
953                                                  * claim the value is of type UNKNOWN, not the var's
954                                                  * datatype, else coercion will be skipped. (Do this
955                                                  * before the notnull check to be consistent with
956                                                  * exec_assign_value.)
957                                                  */
958                                                 if (!var->datatype->typinput.fn_strict)
959                                                 {
960                                                         bool            valIsNull = true;
961
962                                                         exec_assign_value(estate,
963                                                                                           (PLpgSQL_datum *) var,
964                                                                                           (Datum) 0,
965                                                                                           UNKNOWNOID,
966                                                                                           &valIsNull);
967                                                 }
968                                                 if (var->notnull)
969                                                         ereport(ERROR,
970                                                                         (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
971                                                                          errmsg("variable \"%s\" declared NOT NULL cannot default to NULL",
972                                                                                         var->refname)));
973                                         }
974                                         else
975                                         {
976                                                 exec_assign_expr(estate, (PLpgSQL_datum *) var,
977                                                                                  var->default_val);
978                                         }
979                                 }
980                                 break;
981
982                         case PLPGSQL_DTYPE_REC:
983                                 {
984                                         PLpgSQL_rec *rec = (PLpgSQL_rec *) (estate->datums[n]);
985
986                                         if (rec->freetup)
987                                         {
988                                                 heap_freetuple(rec->tup);
989                                                 rec->freetup = false;
990                                         }
991                                         if (rec->freetupdesc)
992                                         {
993                                                 FreeTupleDesc(rec->tupdesc);
994                                                 rec->freetupdesc = false;
995                                         }
996                                         rec->tup = NULL;
997                                         rec->tupdesc = NULL;
998                                 }
999                                 break;
1000
1001                         case PLPGSQL_DTYPE_RECFIELD:
1002                         case PLPGSQL_DTYPE_ARRAYELEM:
1003                                 break;
1004
1005                         default:
1006                                 elog(ERROR, "unrecognized dtype: %d",
1007                                          estate->datums[n]->dtype);
1008                 }
1009         }
1010
1011         if (block->exceptions)
1012         {
1013                 /*
1014                  * Execute the statements in the block's body inside a sub-transaction
1015                  */
1016                 MemoryContext oldcontext = CurrentMemoryContext;
1017                 ResourceOwner oldowner = CurrentResourceOwner;
1018                 ExprContext *old_eval_econtext = estate->eval_econtext;
1019                 ErrorData *save_cur_error = estate->cur_error;
1020
1021                 estate->err_text = gettext_noop("during statement block entry");
1022
1023                 BeginInternalSubTransaction(NULL);
1024                 /* Want to run statements inside function's memory context */
1025                 MemoryContextSwitchTo(oldcontext);
1026
1027                 PG_TRY();
1028                 {
1029                         /*
1030                          * We need to run the block's statements with a new eval_econtext
1031                          * that belongs to the current subtransaction; if we try to use
1032                          * the outer econtext then ExprContext shutdown callbacks will be
1033                          * called at the wrong times.
1034                          */
1035                         plpgsql_create_econtext(estate);
1036
1037                         estate->err_text = NULL;
1038
1039                         /* Run the block's statements */
1040                         rc = exec_stmts(estate, block->body);
1041
1042                         estate->err_text = gettext_noop("during statement block exit");
1043
1044                         /*
1045                          * If the block ended with RETURN, we may need to copy the return
1046                          * value out of the subtransaction eval_context.  This is
1047                          * currently only needed for scalar result types --- rowtype
1048                          * values will always exist in the function's own memory context.
1049                          */
1050                         if (rc == PLPGSQL_RC_RETURN &&
1051                                 !estate->retisset &&
1052                                 !estate->retisnull &&
1053                                 estate->rettupdesc == NULL)
1054                         {
1055                                 int16           resTypLen;
1056                                 bool            resTypByVal;
1057
1058                                 get_typlenbyval(estate->rettype, &resTypLen, &resTypByVal);
1059                                 estate->retval = datumCopy(estate->retval,
1060                                                                                    resTypByVal, resTypLen);
1061                         }
1062
1063                         /* Commit the inner transaction, return to outer xact context */
1064                         ReleaseCurrentSubTransaction();
1065                         MemoryContextSwitchTo(oldcontext);
1066                         CurrentResourceOwner = oldowner;
1067
1068                         /*
1069                          * Revert to outer eval_econtext.  (The inner one was
1070                          * automatically cleaned up during subxact exit.)
1071                          */
1072                         estate->eval_econtext = old_eval_econtext;
1073
1074                         /*
1075                          * AtEOSubXact_SPI() should not have popped any SPI context, but
1076                          * just in case it did, make sure we remain connected.
1077                          */
1078                         SPI_restore_connection();
1079                 }
1080                 PG_CATCH();
1081                 {
1082                         ErrorData  *edata;
1083                         ListCell   *e;
1084
1085                         estate->err_text = gettext_noop("during exception cleanup");
1086
1087                         /* Save error info */
1088                         MemoryContextSwitchTo(oldcontext);
1089                         edata = CopyErrorData();
1090                         FlushErrorState();
1091
1092                         /* Abort the inner transaction */
1093                         RollbackAndReleaseCurrentSubTransaction();
1094                         MemoryContextSwitchTo(oldcontext);
1095                         CurrentResourceOwner = oldowner;
1096
1097                         /* Revert to outer eval_econtext */
1098                         estate->eval_econtext = old_eval_econtext;
1099
1100                         /*
1101                          * If AtEOSubXact_SPI() popped any SPI context of the subxact, it
1102                          * will have left us in a disconnected state.  We need this hack
1103                          * to return to connected state.
1104                          */
1105                         SPI_restore_connection();
1106
1107                         /* Must clean up the econtext too */
1108                         exec_eval_cleanup(estate);
1109
1110                         /* Look for a matching exception handler */
1111                         foreach(e, block->exceptions->exc_list)
1112                         {
1113                                 PLpgSQL_exception *exception = (PLpgSQL_exception *) lfirst(e);
1114
1115                                 if (exception_matches_conditions(edata, exception->conditions))
1116                                 {
1117                                         /*
1118                                          * Initialize the magic SQLSTATE and SQLERRM variables for
1119                                          * the exception block. We needn't do this until we have
1120                                          * found a matching exception.
1121                                          */
1122                                         PLpgSQL_var *state_var;
1123                                         PLpgSQL_var *errm_var;
1124
1125                                         state_var = (PLpgSQL_var *)
1126                                                 estate->datums[block->exceptions->sqlstate_varno];
1127                                         errm_var = (PLpgSQL_var *)
1128                                                 estate->datums[block->exceptions->sqlerrm_varno];
1129
1130                                         assign_text_var(state_var,
1131                                                                         unpack_sql_state(edata->sqlerrcode));
1132                                         assign_text_var(errm_var, edata->message);
1133
1134                                         /*
1135                                          * Also set up cur_error so the error data is accessible
1136                                          * inside the handler.
1137                                          */
1138                                         estate->cur_error = edata;
1139
1140                                         estate->err_text = NULL;
1141
1142                                         rc = exec_stmts(estate, exception->action);
1143
1144                                         free_var(state_var);
1145                                         state_var->value = (Datum) 0;
1146                                         state_var->isnull = true;
1147                                         free_var(errm_var);
1148                                         errm_var->value = (Datum) 0;
1149                                         errm_var->isnull = true;
1150
1151                                         break;
1152                                 }
1153                         }
1154
1155                         /*
1156                          * Restore previous state of cur_error, whether or not we executed
1157                          * a handler.  This is needed in case an error got thrown from
1158                          * some inner block's exception handler.
1159                          */
1160                         estate->cur_error = save_cur_error;
1161
1162                         /* If no match found, re-throw the error */
1163                         if (e == NULL)
1164                                 ReThrowError(edata);
1165                         else
1166                                 FreeErrorData(edata);
1167                 }
1168                 PG_END_TRY();
1169
1170                 Assert(save_cur_error == estate->cur_error);
1171         }
1172         else
1173         {
1174                 /*
1175                  * Just execute the statements in the block's body
1176                  */
1177                 estate->err_text = NULL;
1178
1179                 rc = exec_stmts(estate, block->body);
1180         }
1181
1182         estate->err_text = NULL;
1183
1184         /*
1185          * Handle the return code.
1186          */
1187         switch (rc)
1188         {
1189                 case PLPGSQL_RC_OK:
1190                 case PLPGSQL_RC_RETURN:
1191                 case PLPGSQL_RC_CONTINUE:
1192                         return rc;
1193
1194                 case PLPGSQL_RC_EXIT:
1195
1196                         /*
1197                          * This is intentionally different from the handling of RC_EXIT
1198                          * for loops: to match a block, we require a match by label.
1199                          */
1200                         if (estate->exitlabel == NULL)
1201                                 return PLPGSQL_RC_EXIT;
1202                         if (block->label == NULL)
1203                                 return PLPGSQL_RC_EXIT;
1204                         if (strcmp(block->label, estate->exitlabel) != 0)
1205                                 return PLPGSQL_RC_EXIT;
1206                         estate->exitlabel = NULL;
1207                         return PLPGSQL_RC_OK;
1208
1209                 default:
1210                         elog(ERROR, "unrecognized rc: %d", rc);
1211         }
1212
1213         return PLPGSQL_RC_OK;
1214 }
1215
1216
1217 /* ----------
1218  * exec_stmts                   Iterate over a list of statements
1219  *                              as long as their return code is OK
1220  * ----------
1221  */
1222 static int
1223 exec_stmts(PLpgSQL_execstate *estate, List *stmts)
1224 {
1225         ListCell   *s;
1226
1227         if (stmts == NIL)
1228         {
1229                 /*
1230                  * Ensure we do a CHECK_FOR_INTERRUPTS() even though there is no
1231                  * statement.  This prevents hangup in a tight loop if, for instance,
1232                  * there is a LOOP construct with an empty body.
1233                  */
1234                 CHECK_FOR_INTERRUPTS();
1235                 return PLPGSQL_RC_OK;
1236         }
1237
1238         foreach(s, stmts)
1239         {
1240                 PLpgSQL_stmt *stmt = (PLpgSQL_stmt *) lfirst(s);
1241                 int                     rc = exec_stmt(estate, stmt);
1242
1243                 if (rc != PLPGSQL_RC_OK)
1244                         return rc;
1245         }
1246
1247         return PLPGSQL_RC_OK;
1248 }
1249
1250
1251 /* ----------
1252  * exec_stmt                    Distribute one statement to the statements
1253  *                              type specific execution function.
1254  * ----------
1255  */
1256 static int
1257 exec_stmt(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
1258 {
1259         PLpgSQL_stmt *save_estmt;
1260         int                     rc = -1;
1261
1262         save_estmt = estate->err_stmt;
1263         estate->err_stmt = stmt;
1264
1265         /* Let the plugin know that we are about to execute this statement */
1266         if (*plugin_ptr && (*plugin_ptr)->stmt_beg)
1267                 ((*plugin_ptr)->stmt_beg) (estate, stmt);
1268
1269         CHECK_FOR_INTERRUPTS();
1270
1271         switch ((enum PLpgSQL_stmt_types) stmt->cmd_type)
1272         {
1273                 case PLPGSQL_STMT_BLOCK:
1274                         rc = exec_stmt_block(estate, (PLpgSQL_stmt_block *) stmt);
1275                         break;
1276
1277                 case PLPGSQL_STMT_ASSIGN:
1278                         rc = exec_stmt_assign(estate, (PLpgSQL_stmt_assign *) stmt);
1279                         break;
1280
1281                 case PLPGSQL_STMT_PERFORM:
1282                         rc = exec_stmt_perform(estate, (PLpgSQL_stmt_perform *) stmt);
1283                         break;
1284
1285                 case PLPGSQL_STMT_GETDIAG:
1286                         rc = exec_stmt_getdiag(estate, (PLpgSQL_stmt_getdiag *) stmt);
1287                         break;
1288
1289                 case PLPGSQL_STMT_IF:
1290                         rc = exec_stmt_if(estate, (PLpgSQL_stmt_if *) stmt);
1291                         break;
1292
1293                 case PLPGSQL_STMT_CASE:
1294                         rc = exec_stmt_case(estate, (PLpgSQL_stmt_case *) stmt);
1295                         break;
1296
1297                 case PLPGSQL_STMT_LOOP:
1298                         rc = exec_stmt_loop(estate, (PLpgSQL_stmt_loop *) stmt);
1299                         break;
1300
1301                 case PLPGSQL_STMT_WHILE:
1302                         rc = exec_stmt_while(estate, (PLpgSQL_stmt_while *) stmt);
1303                         break;
1304
1305                 case PLPGSQL_STMT_FORI:
1306                         rc = exec_stmt_fori(estate, (PLpgSQL_stmt_fori *) stmt);
1307                         break;
1308
1309                 case PLPGSQL_STMT_FORS:
1310                         rc = exec_stmt_fors(estate, (PLpgSQL_stmt_fors *) stmt);
1311                         break;
1312
1313                 case PLPGSQL_STMT_FORC:
1314                         rc = exec_stmt_forc(estate, (PLpgSQL_stmt_forc *) stmt);
1315                         break;
1316
1317                 case PLPGSQL_STMT_FOREACH_A:
1318                         rc = exec_stmt_foreach_a(estate, (PLpgSQL_stmt_foreach_a *) stmt);
1319                         break;
1320
1321                 case PLPGSQL_STMT_EXIT:
1322                         rc = exec_stmt_exit(estate, (PLpgSQL_stmt_exit *) stmt);
1323                         break;
1324
1325                 case PLPGSQL_STMT_RETURN:
1326                         rc = exec_stmt_return(estate, (PLpgSQL_stmt_return *) stmt);
1327                         break;
1328
1329                 case PLPGSQL_STMT_RETURN_NEXT:
1330                         rc = exec_stmt_return_next(estate, (PLpgSQL_stmt_return_next *) stmt);
1331                         break;
1332
1333                 case PLPGSQL_STMT_RETURN_QUERY:
1334                         rc = exec_stmt_return_query(estate, (PLpgSQL_stmt_return_query *) stmt);
1335                         break;
1336
1337                 case PLPGSQL_STMT_RAISE:
1338                         rc = exec_stmt_raise(estate, (PLpgSQL_stmt_raise *) stmt);
1339                         break;
1340
1341                 case PLPGSQL_STMT_EXECSQL:
1342                         rc = exec_stmt_execsql(estate, (PLpgSQL_stmt_execsql *) stmt);
1343                         break;
1344
1345                 case PLPGSQL_STMT_DYNEXECUTE:
1346                         rc = exec_stmt_dynexecute(estate, (PLpgSQL_stmt_dynexecute *) stmt);
1347                         break;
1348
1349                 case PLPGSQL_STMT_DYNFORS:
1350                         rc = exec_stmt_dynfors(estate, (PLpgSQL_stmt_dynfors *) stmt);
1351                         break;
1352
1353                 case PLPGSQL_STMT_OPEN:
1354                         rc = exec_stmt_open(estate, (PLpgSQL_stmt_open *) stmt);
1355                         break;
1356
1357                 case PLPGSQL_STMT_FETCH:
1358                         rc = exec_stmt_fetch(estate, (PLpgSQL_stmt_fetch *) stmt);
1359                         break;
1360
1361                 case PLPGSQL_STMT_CLOSE:
1362                         rc = exec_stmt_close(estate, (PLpgSQL_stmt_close *) stmt);
1363                         break;
1364
1365                 default:
1366                         estate->err_stmt = save_estmt;
1367                         elog(ERROR, "unrecognized cmdtype: %d", stmt->cmd_type);
1368         }
1369
1370         /* Let the plugin know that we have finished executing this statement */
1371         if (*plugin_ptr && (*plugin_ptr)->stmt_end)
1372                 ((*plugin_ptr)->stmt_end) (estate, stmt);
1373
1374         estate->err_stmt = save_estmt;
1375
1376         return rc;
1377 }
1378
1379
1380 /* ----------
1381  * exec_stmt_assign                     Evaluate an expression and
1382  *                                      put the result into a variable.
1383  * ----------
1384  */
1385 static int
1386 exec_stmt_assign(PLpgSQL_execstate *estate, PLpgSQL_stmt_assign *stmt)
1387 {
1388         Assert(stmt->varno >= 0);
1389
1390         exec_assign_expr(estate, estate->datums[stmt->varno], stmt->expr);
1391
1392         return PLPGSQL_RC_OK;
1393 }
1394
1395 /* ----------
1396  * exec_stmt_perform            Evaluate query and discard result (but set
1397  *                                                      FOUND depending on whether at least one row
1398  *                                                      was returned).
1399  * ----------
1400  */
1401 static int
1402 exec_stmt_perform(PLpgSQL_execstate *estate, PLpgSQL_stmt_perform *stmt)
1403 {
1404         PLpgSQL_expr *expr = stmt->expr;
1405
1406         (void) exec_run_select(estate, expr, 0, NULL);
1407         exec_set_found(estate, (estate->eval_processed != 0));
1408         exec_eval_cleanup(estate);
1409
1410         return PLPGSQL_RC_OK;
1411 }
1412
1413 /* ----------
1414  * exec_stmt_getdiag                                    Put internal PG information into
1415  *                                                                              specified variables.
1416  * ----------
1417  */
1418 static int
1419 exec_stmt_getdiag(PLpgSQL_execstate *estate, PLpgSQL_stmt_getdiag *stmt)
1420 {
1421         ListCell   *lc;
1422
1423         foreach(lc, stmt->diag_items)
1424         {
1425                 PLpgSQL_diag_item *diag_item = (PLpgSQL_diag_item *) lfirst(lc);
1426                 PLpgSQL_datum *var;
1427                 bool            isnull = false;
1428
1429                 if (diag_item->target <= 0)
1430                         continue;
1431
1432                 var = estate->datums[diag_item->target];
1433
1434                 if (var == NULL)
1435                         continue;
1436
1437                 switch (diag_item->kind)
1438                 {
1439                         case PLPGSQL_GETDIAG_ROW_COUNT:
1440
1441                                 exec_assign_value(estate, var,
1442                                                                   UInt32GetDatum(estate->eval_processed),
1443                                                                   INT4OID, &isnull);
1444                                 break;
1445
1446                         case PLPGSQL_GETDIAG_RESULT_OID:
1447
1448                                 exec_assign_value(estate, var,
1449                                                                   ObjectIdGetDatum(estate->eval_lastoid),
1450                                                                   OIDOID, &isnull);
1451                                 break;
1452
1453                         default:
1454                                 elog(ERROR, "unrecognized attribute request: %d",
1455                                          diag_item->kind);
1456                 }
1457         }
1458
1459         return PLPGSQL_RC_OK;
1460 }
1461
1462 /* ----------
1463  * exec_stmt_if                         Evaluate a bool expression and
1464  *                                      execute the true or false body
1465  *                                      conditionally.
1466  * ----------
1467  */
1468 static int
1469 exec_stmt_if(PLpgSQL_execstate *estate, PLpgSQL_stmt_if *stmt)
1470 {
1471         bool            value;
1472         bool            isnull;
1473
1474         value = exec_eval_boolean(estate, stmt->cond, &isnull);
1475         exec_eval_cleanup(estate);
1476
1477         if (!isnull && value)
1478         {
1479                 if (stmt->true_body != NIL)
1480                         return exec_stmts(estate, stmt->true_body);
1481         }
1482         else
1483         {
1484                 if (stmt->false_body != NIL)
1485                         return exec_stmts(estate, stmt->false_body);
1486         }
1487
1488         return PLPGSQL_RC_OK;
1489 }
1490
1491
1492 /*-----------
1493  * exec_stmt_case
1494  *-----------
1495  */
1496 static int
1497 exec_stmt_case(PLpgSQL_execstate *estate, PLpgSQL_stmt_case *stmt)
1498 {
1499         PLpgSQL_var *t_var = NULL;
1500         bool            isnull;
1501         ListCell   *l;
1502
1503         if (stmt->t_expr != NULL)
1504         {
1505                 /* simple case */
1506                 Datum           t_val;
1507                 Oid                     t_oid;
1508
1509                 t_val = exec_eval_expr(estate, stmt->t_expr, &isnull, &t_oid);
1510
1511                 t_var = (PLpgSQL_var *) estate->datums[stmt->t_varno];
1512
1513                 /*
1514                  * When expected datatype is different from real, change it. Note that
1515                  * what we're modifying here is an execution copy of the datum, so
1516                  * this doesn't affect the originally stored function parse tree.
1517                  */
1518                 if (t_var->datatype->typoid != t_oid)
1519                         t_var->datatype = plpgsql_build_datatype(t_oid, -1);
1520
1521                 /* now we can assign to the variable */
1522                 exec_assign_value(estate,
1523                                                   (PLpgSQL_datum *) t_var,
1524                                                   t_val,
1525                                                   t_oid,
1526                                                   &isnull);
1527
1528                 exec_eval_cleanup(estate);
1529         }
1530
1531         /* Now search for a successful WHEN clause */
1532         foreach(l, stmt->case_when_list)
1533         {
1534                 PLpgSQL_case_when *cwt = (PLpgSQL_case_when *) lfirst(l);
1535                 bool            value;
1536
1537                 value = exec_eval_boolean(estate, cwt->expr, &isnull);
1538                 exec_eval_cleanup(estate);
1539                 if (!isnull && value)
1540                 {
1541                         /* Found it */
1542
1543                         /* We can now discard any value we had for the temp variable */
1544                         if (t_var != NULL)
1545                         {
1546                                 free_var(t_var);
1547                                 t_var->value = (Datum) 0;
1548                                 t_var->isnull = true;
1549                         }
1550
1551                         /* Evaluate the statement(s), and we're done */
1552                         return exec_stmts(estate, cwt->stmts);
1553                 }
1554         }
1555
1556         /* We can now discard any value we had for the temp variable */
1557         if (t_var != NULL)
1558         {
1559                 free_var(t_var);
1560                 t_var->value = (Datum) 0;
1561                 t_var->isnull = true;
1562         }
1563
1564         /* SQL2003 mandates this error if there was no ELSE clause */
1565         if (!stmt->have_else)
1566                 ereport(ERROR,
1567                                 (errcode(ERRCODE_CASE_NOT_FOUND),
1568                                  errmsg("case not found"),
1569                                  errhint("CASE statement is missing ELSE part.")));
1570
1571         /* Evaluate the ELSE statements, and we're done */
1572         return exec_stmts(estate, stmt->else_stmts);
1573 }
1574
1575
1576 /* ----------
1577  * exec_stmt_loop                       Loop over statements until
1578  *                                      an exit occurs.
1579  * ----------
1580  */
1581 static int
1582 exec_stmt_loop(PLpgSQL_execstate *estate, PLpgSQL_stmt_loop *stmt)
1583 {
1584         for (;;)
1585         {
1586                 int                     rc = exec_stmts(estate, stmt->body);
1587
1588                 switch (rc)
1589                 {
1590                         case PLPGSQL_RC_OK:
1591                                 break;
1592
1593                         case PLPGSQL_RC_EXIT:
1594                                 if (estate->exitlabel == NULL)
1595                                         return PLPGSQL_RC_OK;
1596                                 if (stmt->label == NULL)
1597                                         return PLPGSQL_RC_EXIT;
1598                                 if (strcmp(stmt->label, estate->exitlabel) != 0)
1599                                         return PLPGSQL_RC_EXIT;
1600                                 estate->exitlabel = NULL;
1601                                 return PLPGSQL_RC_OK;
1602
1603                         case PLPGSQL_RC_CONTINUE:
1604                                 if (estate->exitlabel == NULL)
1605                                         /* anonymous continue, so re-run the loop */
1606                                         break;
1607                                 else if (stmt->label != NULL &&
1608                                                  strcmp(stmt->label, estate->exitlabel) == 0)
1609                                         /* label matches named continue, so re-run loop */
1610                                         estate->exitlabel = NULL;
1611                                 else
1612                                         /* label doesn't match named continue, so propagate upward */
1613                                         return PLPGSQL_RC_CONTINUE;
1614                                 break;
1615
1616                         case PLPGSQL_RC_RETURN:
1617                                 return rc;
1618
1619                         default:
1620                                 elog(ERROR, "unrecognized rc: %d", rc);
1621                 }
1622         }
1623
1624         return PLPGSQL_RC_OK;
1625 }
1626
1627
1628 /* ----------
1629  * exec_stmt_while                      Loop over statements as long
1630  *                                      as an expression evaluates to
1631  *                                      true or an exit occurs.
1632  * ----------
1633  */
1634 static int
1635 exec_stmt_while(PLpgSQL_execstate *estate, PLpgSQL_stmt_while *stmt)
1636 {
1637         for (;;)
1638         {
1639                 int                     rc;
1640                 bool            value;
1641                 bool            isnull;
1642
1643                 value = exec_eval_boolean(estate, stmt->cond, &isnull);
1644                 exec_eval_cleanup(estate);
1645
1646                 if (isnull || !value)
1647                         break;
1648
1649                 rc = exec_stmts(estate, stmt->body);
1650
1651                 switch (rc)
1652                 {
1653                         case PLPGSQL_RC_OK:
1654                                 break;
1655
1656                         case PLPGSQL_RC_EXIT:
1657                                 if (estate->exitlabel == NULL)
1658                                         return PLPGSQL_RC_OK;
1659                                 if (stmt->label == NULL)
1660                                         return PLPGSQL_RC_EXIT;
1661                                 if (strcmp(stmt->label, estate->exitlabel) != 0)
1662                                         return PLPGSQL_RC_EXIT;
1663                                 estate->exitlabel = NULL;
1664                                 return PLPGSQL_RC_OK;
1665
1666                         case PLPGSQL_RC_CONTINUE:
1667                                 if (estate->exitlabel == NULL)
1668                                         /* anonymous continue, so re-run loop */
1669                                         break;
1670                                 else if (stmt->label != NULL &&
1671                                                  strcmp(stmt->label, estate->exitlabel) == 0)
1672                                         /* label matches named continue, so re-run loop */
1673                                         estate->exitlabel = NULL;
1674                                 else
1675                                         /* label doesn't match named continue, propagate upward */
1676                                         return PLPGSQL_RC_CONTINUE;
1677                                 break;
1678
1679                         case PLPGSQL_RC_RETURN:
1680                                 return rc;
1681
1682                         default:
1683                                 elog(ERROR, "unrecognized rc: %d", rc);
1684                 }
1685         }
1686
1687         return PLPGSQL_RC_OK;
1688 }
1689
1690
1691 /* ----------
1692  * exec_stmt_fori                       Iterate an integer variable
1693  *                                      from a lower to an upper value
1694  *                                      incrementing or decrementing by the BY value
1695  * ----------
1696  */
1697 static int
1698 exec_stmt_fori(PLpgSQL_execstate *estate, PLpgSQL_stmt_fori *stmt)
1699 {
1700         PLpgSQL_var *var;
1701         Datum           value;
1702         bool            isnull;
1703         Oid                     valtype;
1704         int32           loop_value;
1705         int32           end_value;
1706         int32           step_value;
1707         bool            found = false;
1708         int                     rc = PLPGSQL_RC_OK;
1709
1710         var = (PLpgSQL_var *) (estate->datums[stmt->var->dno]);
1711
1712         /*
1713          * Get the value of the lower bound
1714          */
1715         value = exec_eval_expr(estate, stmt->lower, &isnull, &valtype);
1716         value = exec_cast_value(value, valtype, var->datatype->typoid,
1717                                                         &(var->datatype->typinput),
1718                                                         var->datatype->typioparam,
1719                                                         var->datatype->atttypmod, isnull);
1720         if (isnull)
1721                 ereport(ERROR,
1722                                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1723                                  errmsg("lower bound of FOR loop cannot be null")));
1724         loop_value = DatumGetInt32(value);
1725         exec_eval_cleanup(estate);
1726
1727         /*
1728          * Get the value of the upper bound
1729          */
1730         value = exec_eval_expr(estate, stmt->upper, &isnull, &valtype);
1731         value = exec_cast_value(value, valtype, var->datatype->typoid,
1732                                                         &(var->datatype->typinput),
1733                                                         var->datatype->typioparam,
1734                                                         var->datatype->atttypmod, isnull);
1735         if (isnull)
1736                 ereport(ERROR,
1737                                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1738                                  errmsg("upper bound of FOR loop cannot be null")));
1739         end_value = DatumGetInt32(value);
1740         exec_eval_cleanup(estate);
1741
1742         /*
1743          * Get the step value
1744          */
1745         if (stmt->step)
1746         {
1747                 value = exec_eval_expr(estate, stmt->step, &isnull, &valtype);
1748                 value = exec_cast_value(value, valtype, var->datatype->typoid,
1749                                                                 &(var->datatype->typinput),
1750                                                                 var->datatype->typioparam,
1751                                                                 var->datatype->atttypmod, isnull);
1752                 if (isnull)
1753                         ereport(ERROR,
1754                                         (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1755                                          errmsg("BY value of FOR loop cannot be null")));
1756                 step_value = DatumGetInt32(value);
1757                 exec_eval_cleanup(estate);
1758                 if (step_value <= 0)
1759                         ereport(ERROR,
1760                                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1761                                   errmsg("BY value of FOR loop must be greater than zero")));
1762         }
1763         else
1764                 step_value = 1;
1765
1766         /*
1767          * Now do the loop
1768          */
1769         for (;;)
1770         {
1771                 /*
1772                  * Check against upper bound
1773                  */
1774                 if (stmt->reverse)
1775                 {
1776                         if (loop_value < end_value)
1777                                 break;
1778                 }
1779                 else
1780                 {
1781                         if (loop_value > end_value)
1782                                 break;
1783                 }
1784
1785                 found = true;                   /* looped at least once */
1786
1787                 /*
1788                  * Assign current value to loop var
1789                  */
1790                 var->value = Int32GetDatum(loop_value);
1791                 var->isnull = false;
1792
1793                 /*
1794                  * Execute the statements
1795                  */
1796                 rc = exec_stmts(estate, stmt->body);
1797
1798                 if (rc == PLPGSQL_RC_RETURN)
1799                         break;                          /* break out of the loop */
1800                 else if (rc == PLPGSQL_RC_EXIT)
1801                 {
1802                         if (estate->exitlabel == NULL)
1803                                 /* unlabelled exit, finish the current loop */
1804                                 rc = PLPGSQL_RC_OK;
1805                         else if (stmt->label != NULL &&
1806                                          strcmp(stmt->label, estate->exitlabel) == 0)
1807                         {
1808                                 /* labelled exit, matches the current stmt's label */
1809                                 estate->exitlabel = NULL;
1810                                 rc = PLPGSQL_RC_OK;
1811                         }
1812
1813                         /*
1814                          * otherwise, this is a labelled exit that does not match the
1815                          * current statement's label, if any: return RC_EXIT so that the
1816                          * EXIT continues to propagate up the stack.
1817                          */
1818                         break;
1819                 }
1820                 else if (rc == PLPGSQL_RC_CONTINUE)
1821                 {
1822                         if (estate->exitlabel == NULL)
1823                                 /* unlabelled continue, so re-run the current loop */
1824                                 rc = PLPGSQL_RC_OK;
1825                         else if (stmt->label != NULL &&
1826                                          strcmp(stmt->label, estate->exitlabel) == 0)
1827                         {
1828                                 /* label matches named continue, so re-run loop */
1829                                 estate->exitlabel = NULL;
1830                                 rc = PLPGSQL_RC_OK;
1831                         }
1832                         else
1833                         {
1834                                 /*
1835                                  * otherwise, this is a named continue that does not match the
1836                                  * current statement's label, if any: return RC_CONTINUE so
1837                                  * that the CONTINUE will propagate up the stack.
1838                                  */
1839                                 break;
1840                         }
1841                 }
1842
1843                 /*
1844                  * Increase/decrease loop value, unless it would overflow, in which
1845                  * case exit the loop.
1846                  */
1847                 if (stmt->reverse)
1848                 {
1849                         if ((int32) (loop_value - step_value) > loop_value)
1850                                 break;
1851                         loop_value -= step_value;
1852                 }
1853                 else
1854                 {
1855                         if ((int32) (loop_value + step_value) < loop_value)
1856                                 break;
1857                         loop_value += step_value;
1858                 }
1859         }
1860
1861         /*
1862          * Set the FOUND variable to indicate the result of executing the loop
1863          * (namely, whether we looped one or more times). This must be set here so
1864          * that it does not interfere with the value of the FOUND variable inside
1865          * the loop processing itself.
1866          */
1867         exec_set_found(estate, found);
1868
1869         return rc;
1870 }
1871
1872
1873 /* ----------
1874  * exec_stmt_fors                       Execute a query, assign each
1875  *                                      tuple to a record or row and
1876  *                                      execute a group of statements
1877  *                                      for it.
1878  * ----------
1879  */
1880 static int
1881 exec_stmt_fors(PLpgSQL_execstate *estate, PLpgSQL_stmt_fors *stmt)
1882 {
1883         Portal          portal;
1884         int                     rc;
1885
1886         /*
1887          * Open the implicit cursor for the statement using exec_run_select
1888          */
1889         exec_run_select(estate, stmt->query, 0, &portal);
1890
1891         /*
1892          * Execute the loop
1893          */
1894         rc = exec_for_query(estate, (PLpgSQL_stmt_forq *) stmt, portal, true);
1895
1896         /*
1897          * Close the implicit cursor
1898          */
1899         SPI_cursor_close(portal);
1900
1901         return rc;
1902 }
1903
1904
1905 /* ----------
1906  * exec_stmt_forc                       Execute a loop for each row from a cursor.
1907  * ----------
1908  */
1909 static int
1910 exec_stmt_forc(PLpgSQL_execstate *estate, PLpgSQL_stmt_forc *stmt)
1911 {
1912         PLpgSQL_var *curvar;
1913         char       *curname = NULL;
1914         const char *portalname;
1915         PLpgSQL_expr *query;
1916         ParamListInfo paramLI;
1917         Portal          portal;
1918         int                     rc;
1919
1920         /* ----------
1921          * Get the cursor variable and if it has an assigned name, check
1922          * that it's not in use currently.
1923          * ----------
1924          */
1925         curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
1926         if (!curvar->isnull)
1927         {
1928                 curname = TextDatumGetCString(curvar->value);
1929                 if (SPI_cursor_find(curname) != NULL)
1930                         ereport(ERROR,
1931                                         (errcode(ERRCODE_DUPLICATE_CURSOR),
1932                                          errmsg("cursor \"%s\" already in use", curname)));
1933         }
1934
1935         /* ----------
1936          * Open the cursor just like an OPEN command
1937          *
1938          * Note: parser should already have checked that statement supplies
1939          * args iff cursor needs them, but we check again to be safe.
1940          * ----------
1941          */
1942         if (stmt->argquery != NULL)
1943         {
1944                 /* ----------
1945                  * OPEN CURSOR with args.  We fake a SELECT ... INTO ...
1946                  * statement to evaluate the args and put 'em into the
1947                  * internal row.
1948                  * ----------
1949                  */
1950                 PLpgSQL_stmt_execsql set_args;
1951
1952                 if (curvar->cursor_explicit_argrow < 0)
1953                         ereport(ERROR,
1954                                         (errcode(ERRCODE_SYNTAX_ERROR),
1955                                          errmsg("arguments given for cursor without arguments")));
1956
1957                 memset(&set_args, 0, sizeof(set_args));
1958                 set_args.cmd_type = PLPGSQL_STMT_EXECSQL;
1959                 set_args.lineno = stmt->lineno;
1960                 set_args.sqlstmt = stmt->argquery;
1961                 set_args.into = true;
1962                 /* XXX historically this has not been STRICT */
1963                 set_args.row = (PLpgSQL_row *)
1964                         (estate->datums[curvar->cursor_explicit_argrow]);
1965
1966                 if (exec_stmt_execsql(estate, &set_args) != PLPGSQL_RC_OK)
1967                         elog(ERROR, "open cursor failed during argument processing");
1968         }
1969         else
1970         {
1971                 if (curvar->cursor_explicit_argrow >= 0)
1972                         ereport(ERROR,
1973                                         (errcode(ERRCODE_SYNTAX_ERROR),
1974                                          errmsg("arguments required for cursor")));
1975         }
1976
1977         query = curvar->cursor_explicit_expr;
1978         Assert(query);
1979
1980         if (query->plan == NULL)
1981                 exec_prepare_plan(estate, query, curvar->cursor_options);
1982
1983         /*
1984          * Set up ParamListInfo (note this is only carrying a hook function, not
1985          * any actual data values, at this point)
1986          */
1987         paramLI = setup_param_list(estate, query);
1988
1989         /*
1990          * Open the cursor (the paramlist will get copied into the portal)
1991          */
1992         portal = SPI_cursor_open_with_paramlist(curname, query->plan,
1993                                                                                         paramLI,
1994                                                                                         estate->readonly_func);
1995         if (portal == NULL)
1996                 elog(ERROR, "could not open cursor: %s",
1997                          SPI_result_code_string(SPI_result));
1998         portalname = portal->name;
1999
2000         /* don't need paramlist any more */
2001         if (paramLI)
2002                 pfree(paramLI);
2003
2004         /*
2005          * If cursor variable was NULL, store the generated portal name in it
2006          */
2007         if (curname == NULL)
2008                 assign_text_var(curvar, portal->name);
2009
2010         /*
2011          * Execute the loop.  We can't prefetch because the cursor is accessible
2012          * to the user, for instance via UPDATE WHERE CURRENT OF within the loop.
2013          */
2014         rc = exec_for_query(estate, (PLpgSQL_stmt_forq *) stmt, portal, false);
2015
2016         /* ----------
2017          * Close portal, and restore cursor variable if it was initially NULL.
2018          * ----------
2019          */
2020         SPI_cursor_close(portal);
2021
2022         if (curname == NULL)
2023         {
2024                 free_var(curvar);
2025                 curvar->value = (Datum) 0;
2026                 curvar->isnull = true;
2027         }
2028
2029         if (curname)
2030                 pfree(curname);
2031
2032         return rc;
2033 }
2034
2035
2036 /* ----------
2037  * exec_stmt_foreach_a                  Loop over elements or slices of an array
2038  *
2039  * When looping over elements, the loop variable is the same type that the
2040  * array stores (eg: integer), when looping through slices, the loop variable
2041  * is an array of size and dimensions to match the size of the slice.
2042  * ----------
2043  */
2044 static int
2045 exec_stmt_foreach_a(PLpgSQL_execstate *estate, PLpgSQL_stmt_foreach_a *stmt)
2046 {
2047         ArrayType                  *arr;
2048         Oid                                     arrtype;
2049         PLpgSQL_datum      *loop_var;
2050         Oid                                     loop_var_elem_type;
2051         bool                            found = false;
2052         int                                     rc = PLPGSQL_RC_OK;
2053         ArrayIterator           array_iterator;
2054         Oid                                     iterator_result_type;
2055         Datum                           value;
2056         bool                            isnull;
2057
2058         /* get the value of the array expression */
2059         value = exec_eval_expr(estate, stmt->expr, &isnull, &arrtype);
2060         if (isnull)
2061                 ereport(ERROR,
2062                                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2063                                  errmsg("FOREACH expression must not be NULL")));
2064
2065         /* check the type of the expression - must be an array */
2066         if (!OidIsValid(get_element_type(arrtype)))
2067                 ereport(ERROR,
2068                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
2069                                  errmsg("FOREACH expression must yield an array, not type %s",
2070                                                 format_type_be(arrtype))));
2071
2072         /*
2073          * We must copy the array, else it will disappear in exec_eval_cleanup.
2074          * This is annoying, but cleanup will certainly happen while running the
2075          * loop body, so we have little choice.
2076          */
2077         arr = DatumGetArrayTypePCopy(value);
2078
2079         /* Clean up any leftover temporary memory */
2080         exec_eval_cleanup(estate);
2081
2082         /* Slice dimension must be less than or equal to array dimension */
2083         if (stmt->slice < 0 || stmt->slice > ARR_NDIM(arr))
2084                 ereport(ERROR,
2085                                 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2086                                  errmsg("slice dimension (%d) is out of the valid range 0..%d",
2087                                                 stmt->slice, ARR_NDIM(arr))));
2088
2089         /* Set up the loop variable and see if it is of an array type */
2090         loop_var = estate->datums[stmt->varno];
2091         if (loop_var->dtype == PLPGSQL_DTYPE_REC ||
2092                 loop_var->dtype == PLPGSQL_DTYPE_ROW)
2093         {
2094                 /*
2095                  * Record/row variable is certainly not of array type, and might not
2096                  * be initialized at all yet, so don't try to get its type
2097                  */
2098                 loop_var_elem_type = InvalidOid;
2099         }
2100         else
2101                 loop_var_elem_type = get_element_type(exec_get_datum_type(estate,
2102                                                                                                                                   loop_var));
2103
2104         /*
2105          * Sanity-check the loop variable type.  We don't try very hard here,
2106          * and should not be too picky since it's possible that exec_assign_value
2107          * can coerce values of different types.  But it seems worthwhile to
2108          * complain if the array-ness of the loop variable is not right.
2109          */
2110         if (stmt->slice > 0 && loop_var_elem_type == InvalidOid)
2111                 ereport(ERROR,
2112                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
2113                                  errmsg("FOREACH ... SLICE loop variable must be of an array type")));
2114         if (stmt->slice == 0 && loop_var_elem_type != InvalidOid)
2115                 ereport(ERROR,
2116                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
2117                                  errmsg("FOREACH loop variable must not be of an array type")));
2118
2119         /* Create an iterator to step through the array */
2120         array_iterator = array_create_iterator(arr, stmt->slice);
2121
2122         /* Identify iterator result type */
2123         if (stmt->slice > 0)
2124         {
2125                 /* When slicing, nominal type of result is same as array type */
2126                 iterator_result_type = arrtype;
2127         }
2128         else
2129         {
2130                 /* Without slicing, results are individual array elements */
2131                 iterator_result_type = ARR_ELEMTYPE(arr);
2132         }
2133
2134         /* Iterate over the array elements or slices */
2135         while (array_iterate(array_iterator, &value, &isnull))
2136         {
2137                 found = true;                   /* looped at least once */
2138
2139                 /* Assign current element/slice to the loop variable */
2140                 exec_assign_value(estate, loop_var, value, iterator_result_type,
2141                                                   &isnull);
2142
2143                 /* In slice case, value is temporary; must free it to avoid leakage */
2144                 if (stmt->slice > 0)
2145                         pfree(DatumGetPointer(value));
2146
2147                 /*
2148                  * Execute the statements
2149                  */
2150                 rc = exec_stmts(estate, stmt->body);
2151
2152                 /* Handle the return code */
2153                 if (rc == PLPGSQL_RC_RETURN)
2154                         break;                          /* break out of the loop */
2155                 else if (rc == PLPGSQL_RC_EXIT)
2156                 {
2157                         if (estate->exitlabel == NULL)
2158                                 /* unlabelled exit, finish the current loop */
2159                                 rc = PLPGSQL_RC_OK;
2160                         else if (stmt->label != NULL &&
2161                                          strcmp(stmt->label, estate->exitlabel) == 0)
2162                         {
2163                                 /* labelled exit, matches the current stmt's label */
2164                                 estate->exitlabel = NULL;
2165                                 rc = PLPGSQL_RC_OK;
2166                         }
2167
2168                         /*
2169                          * otherwise, this is a labelled exit that does not match the
2170                          * current statement's label, if any: return RC_EXIT so that the
2171                          * EXIT continues to propagate up the stack.
2172                          */
2173                         break;
2174                 }
2175                 else if (rc == PLPGSQL_RC_CONTINUE)
2176                 {
2177                         if (estate->exitlabel == NULL)
2178                                 /* unlabelled continue, so re-run the current loop */
2179                                 rc = PLPGSQL_RC_OK;
2180                         else if (stmt->label != NULL &&
2181                                          strcmp(stmt->label, estate->exitlabel) == 0)
2182                         {
2183                                 /* label matches named continue, so re-run loop */
2184                                 estate->exitlabel = NULL;
2185                                 rc = PLPGSQL_RC_OK;
2186                         }
2187                         else
2188                         {
2189                                 /*
2190                                  * otherwise, this is a named continue that does not match the
2191                                  * current statement's label, if any: return RC_CONTINUE so
2192                                  * that the CONTINUE will propagate up the stack.
2193                                  */
2194                                 break;
2195                         }
2196                 }
2197         }
2198
2199         /* Release temporary memory, including the array value */
2200         array_free_iterator(array_iterator);
2201         pfree(arr);
2202
2203         /*
2204          * Set the FOUND variable to indicate the result of executing the loop
2205          * (namely, whether we looped one or more times). This must be set here so
2206          * that it does not interfere with the value of the FOUND variable inside
2207          * the loop processing itself.
2208          */
2209         exec_set_found(estate, found);
2210
2211         return rc;
2212 }
2213
2214
2215 /* ----------
2216  * exec_stmt_exit                       Implements EXIT and CONTINUE
2217  *
2218  * This begins the process of exiting / restarting a loop.
2219  * ----------
2220  */
2221 static int
2222 exec_stmt_exit(PLpgSQL_execstate *estate, PLpgSQL_stmt_exit *stmt)
2223 {
2224         /*
2225          * If the exit / continue has a condition, evaluate it
2226          */
2227         if (stmt->cond != NULL)
2228         {
2229                 bool            value;
2230                 bool            isnull;
2231
2232                 value = exec_eval_boolean(estate, stmt->cond, &isnull);
2233                 exec_eval_cleanup(estate);
2234                 if (isnull || value == false)
2235                         return PLPGSQL_RC_OK;
2236         }
2237
2238         estate->exitlabel = stmt->label;
2239         if (stmt->is_exit)
2240                 return PLPGSQL_RC_EXIT;
2241         else
2242                 return PLPGSQL_RC_CONTINUE;
2243 }
2244
2245
2246 /* ----------
2247  * exec_stmt_return                     Evaluate an expression and start
2248  *                                      returning from the function.
2249  * ----------
2250  */
2251 static int
2252 exec_stmt_return(PLpgSQL_execstate *estate, PLpgSQL_stmt_return *stmt)
2253 {
2254         /*
2255          * If processing a set-returning PL/pgSQL function, the final RETURN
2256          * indicates that the function is finished producing tuples.  The rest of
2257          * the work will be done at the top level.
2258          */
2259         if (estate->retisset)
2260                 return PLPGSQL_RC_RETURN;
2261
2262         /* initialize for null result (possibly a tuple) */
2263         estate->retval = (Datum) 0;
2264         estate->rettupdesc = NULL;
2265         estate->retisnull = true;
2266
2267         if (stmt->retvarno >= 0)
2268         {
2269                 PLpgSQL_datum *retvar = estate->datums[stmt->retvarno];
2270
2271                 switch (retvar->dtype)
2272                 {
2273                         case PLPGSQL_DTYPE_VAR:
2274                                 {
2275                                         PLpgSQL_var *var = (PLpgSQL_var *) retvar;
2276
2277                                         estate->retval = var->value;
2278                                         estate->retisnull = var->isnull;
2279                                         estate->rettype = var->datatype->typoid;
2280                                 }
2281                                 break;
2282
2283                         case PLPGSQL_DTYPE_REC:
2284                                 {
2285                                         PLpgSQL_rec *rec = (PLpgSQL_rec *) retvar;
2286
2287                                         if (HeapTupleIsValid(rec->tup))
2288                                         {
2289                                                 estate->retval = PointerGetDatum(rec->tup);
2290                                                 estate->rettupdesc = rec->tupdesc;
2291                                                 estate->retisnull = false;
2292                                         }
2293                                 }
2294                                 break;
2295
2296                         case PLPGSQL_DTYPE_ROW:
2297                                 {
2298                                         PLpgSQL_row *row = (PLpgSQL_row *) retvar;
2299
2300                                         Assert(row->rowtupdesc);
2301                                         estate->retval =
2302                                                 PointerGetDatum(make_tuple_from_row(estate, row,
2303                                                                                                                         row->rowtupdesc));
2304                                         if (DatumGetPointer(estate->retval) == NULL)            /* should not happen */
2305                                                 elog(ERROR, "row not compatible with its own tupdesc");
2306                                         estate->rettupdesc = row->rowtupdesc;
2307                                         estate->retisnull = false;
2308                                 }
2309                                 break;
2310
2311                         default:
2312                                 elog(ERROR, "unrecognized dtype: %d", retvar->dtype);
2313                 }
2314
2315                 return PLPGSQL_RC_RETURN;
2316         }
2317
2318         if (stmt->expr != NULL)
2319         {
2320                 if (estate->retistuple)
2321                 {
2322                         exec_run_select(estate, stmt->expr, 1, NULL);
2323                         if (estate->eval_processed > 0)
2324                         {
2325                                 estate->retval = PointerGetDatum(estate->eval_tuptable->vals[0]);
2326                                 estate->rettupdesc = estate->eval_tuptable->tupdesc;
2327                                 estate->retisnull = false;
2328                         }
2329                 }
2330                 else
2331                 {
2332                         /* Normal case for scalar results */
2333                         estate->retval = exec_eval_expr(estate, stmt->expr,
2334                                                                                         &(estate->retisnull),
2335                                                                                         &(estate->rettype));
2336                 }
2337
2338                 return PLPGSQL_RC_RETURN;
2339         }
2340
2341         /*
2342          * Special hack for function returning VOID: instead of NULL, return a
2343          * non-null VOID value.  This is of dubious importance but is kept for
2344          * backwards compatibility.  Note that the only other way to get here is
2345          * to have written "RETURN NULL" in a function returning tuple.
2346          */
2347         if (estate->fn_rettype == VOIDOID)
2348         {
2349                 estate->retval = (Datum) 0;
2350                 estate->retisnull = false;
2351                 estate->rettype = VOIDOID;
2352         }
2353
2354         return PLPGSQL_RC_RETURN;
2355 }
2356
2357 /* ----------
2358  * exec_stmt_return_next                Evaluate an expression and add it to the
2359  *                                                              list of tuples returned by the current
2360  *                                                              SRF.
2361  * ----------
2362  */
2363 static int
2364 exec_stmt_return_next(PLpgSQL_execstate *estate,
2365                                           PLpgSQL_stmt_return_next *stmt)
2366 {
2367         TupleDesc       tupdesc;
2368         int                     natts;
2369         HeapTuple       tuple = NULL;
2370         bool            free_tuple = false;
2371
2372         if (!estate->retisset)
2373                 ereport(ERROR,
2374                                 (errcode(ERRCODE_SYNTAX_ERROR),
2375                                  errmsg("cannot use RETURN NEXT in a non-SETOF function")));
2376
2377         if (estate->tuple_store == NULL)
2378                 exec_init_tuple_store(estate);
2379
2380         /* rettupdesc will be filled by exec_init_tuple_store */
2381         tupdesc = estate->rettupdesc;
2382         natts = tupdesc->natts;
2383
2384         if (stmt->retvarno >= 0)
2385         {
2386                 PLpgSQL_datum *retvar = estate->datums[stmt->retvarno];
2387
2388                 switch (retvar->dtype)
2389                 {
2390                         case PLPGSQL_DTYPE_VAR:
2391                                 {
2392                                         PLpgSQL_var *var = (PLpgSQL_var *) retvar;
2393                                         Datum           retval = var->value;
2394                                         bool            isNull = var->isnull;
2395
2396                                         if (natts != 1)
2397                                                 ereport(ERROR,
2398                                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
2399                                                 errmsg("wrong result type supplied in RETURN NEXT")));
2400
2401                                         /* coerce type if needed */
2402                                         retval = exec_simple_cast_value(retval,
2403                                                                                                         var->datatype->typoid,
2404                                                                                                  tupdesc->attrs[0]->atttypid,
2405                                                                                                 tupdesc->attrs[0]->atttypmod,
2406                                                                                                         isNull);
2407
2408                                         tuplestore_putvalues(estate->tuple_store, tupdesc,
2409                                                                                  &retval, &isNull);
2410                                 }
2411                                 break;
2412
2413                         case PLPGSQL_DTYPE_REC:
2414                                 {
2415                                         PLpgSQL_rec *rec = (PLpgSQL_rec *) retvar;
2416                                         TupleConversionMap *tupmap;
2417
2418                                         if (!HeapTupleIsValid(rec->tup))
2419                                                 ereport(ERROR,
2420                                                   (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2421                                                    errmsg("record \"%s\" is not assigned yet",
2422                                                                   rec->refname),
2423                                                 errdetail("The tuple structure of a not-yet-assigned"
2424                                                                   " record is indeterminate.")));
2425                                         tupmap = convert_tuples_by_position(rec->tupdesc,
2426                                                                                                                 tupdesc,
2427                                                                                                                 gettext_noop("wrong record type supplied in RETURN NEXT"));
2428                                         tuple = rec->tup;
2429                                         /* it might need conversion */
2430                                         if (tupmap)
2431                                         {
2432                                                 tuple = do_convert_tuple(tuple, tupmap);
2433                                                 free_conversion_map(tupmap);
2434                                         }
2435                                 }
2436                                 break;
2437
2438                         case PLPGSQL_DTYPE_ROW:
2439                                 {
2440                                         PLpgSQL_row *row = (PLpgSQL_row *) retvar;
2441
2442                                         tuple = make_tuple_from_row(estate, row, tupdesc);
2443                                         if (tuple == NULL)
2444                                                 ereport(ERROR,
2445                                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
2446                                                 errmsg("wrong record type supplied in RETURN NEXT")));
2447                                         free_tuple = true;
2448                                 }
2449                                 break;
2450
2451                         default:
2452                                 elog(ERROR, "unrecognized dtype: %d", retvar->dtype);
2453                                 break;
2454                 }
2455         }
2456         else if (stmt->expr)
2457         {
2458                 Datum           retval;
2459                 bool            isNull;
2460                 Oid                     rettype;
2461
2462                 if (natts != 1)
2463                         ereport(ERROR,
2464                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
2465                                          errmsg("wrong result type supplied in RETURN NEXT")));
2466
2467                 retval = exec_eval_expr(estate,
2468                                                                 stmt->expr,
2469                                                                 &isNull,
2470                                                                 &rettype);
2471
2472                 /* coerce type if needed */
2473                 retval = exec_simple_cast_value(retval,
2474                                                                                 rettype,
2475                                                                                 tupdesc->attrs[0]->atttypid,
2476                                                                                 tupdesc->attrs[0]->atttypmod,
2477                                                                                 isNull);
2478
2479                 tuplestore_putvalues(estate->tuple_store, tupdesc,
2480                                                          &retval, &isNull);
2481
2482                 exec_eval_cleanup(estate);
2483         }
2484         else
2485         {
2486                 ereport(ERROR,
2487                                 (errcode(ERRCODE_SYNTAX_ERROR),
2488                                  errmsg("RETURN NEXT must have a parameter")));
2489         }
2490
2491         if (HeapTupleIsValid(tuple))
2492         {
2493                 tuplestore_puttuple(estate->tuple_store, tuple);
2494
2495                 if (free_tuple)
2496                         heap_freetuple(tuple);
2497         }
2498
2499         return PLPGSQL_RC_OK;
2500 }
2501
2502 /* ----------
2503  * exec_stmt_return_query               Evaluate a query and add it to the
2504  *                                                              list of tuples returned by the current
2505  *                                                              SRF.
2506  * ----------
2507  */
2508 static int
2509 exec_stmt_return_query(PLpgSQL_execstate *estate,
2510                                            PLpgSQL_stmt_return_query *stmt)
2511 {
2512         Portal          portal;
2513         uint32          processed = 0;
2514         TupleConversionMap *tupmap;
2515
2516         if (!estate->retisset)
2517                 ereport(ERROR,
2518                                 (errcode(ERRCODE_SYNTAX_ERROR),
2519                                  errmsg("cannot use RETURN QUERY in a non-SETOF function")));
2520
2521         if (estate->tuple_store == NULL)
2522                 exec_init_tuple_store(estate);
2523
2524         if (stmt->query != NULL)
2525         {
2526                 /* static query */
2527                 exec_run_select(estate, stmt->query, 0, &portal);
2528         }
2529         else
2530         {
2531                 /* RETURN QUERY EXECUTE */
2532                 Assert(stmt->dynquery != NULL);
2533                 portal = exec_dynquery_with_params(estate, stmt->dynquery,
2534                                                                                    stmt->params, NULL, 0);
2535         }
2536
2537         tupmap = convert_tuples_by_position(portal->tupDesc,
2538                                                                                 estate->rettupdesc,
2539          gettext_noop("structure of query does not match function result type"));
2540
2541         while (true)
2542         {
2543                 int                     i;
2544
2545                 SPI_cursor_fetch(portal, true, 50);
2546                 if (SPI_processed == 0)
2547                         break;
2548
2549                 for (i = 0; i < SPI_processed; i++)
2550                 {
2551                         HeapTuple       tuple = SPI_tuptable->vals[i];
2552
2553                         if (tupmap)
2554                                 tuple = do_convert_tuple(tuple, tupmap);
2555                         tuplestore_puttuple(estate->tuple_store, tuple);
2556                         if (tupmap)
2557                                 heap_freetuple(tuple);
2558                         processed++;
2559                 }
2560
2561                 SPI_freetuptable(SPI_tuptable);
2562         }
2563
2564         if (tupmap)
2565                 free_conversion_map(tupmap);
2566
2567         SPI_freetuptable(SPI_tuptable);
2568         SPI_cursor_close(portal);
2569
2570         estate->eval_processed = processed;
2571         exec_set_found(estate, processed != 0);
2572
2573         return PLPGSQL_RC_OK;
2574 }
2575
2576 static void
2577 exec_init_tuple_store(PLpgSQL_execstate *estate)
2578 {
2579         ReturnSetInfo *rsi = estate->rsi;
2580         MemoryContext oldcxt;
2581         ResourceOwner oldowner;
2582
2583         /*
2584          * Check caller can handle a set result in the way we want
2585          */
2586         if (!rsi || !IsA(rsi, ReturnSetInfo) ||
2587                 (rsi->allowedModes & SFRM_Materialize) == 0 ||
2588                 rsi->expectedDesc == NULL)
2589                 ereport(ERROR,
2590                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2591                                  errmsg("set-valued function called in context that cannot accept a set")));
2592
2593         /*
2594          * Switch to the right memory context and resource owner for storing the
2595          * tuplestore for return set. If we're within a subtransaction opened for
2596          * an exception-block, for example, we must still create the tuplestore in
2597          * the resource owner that was active when this function was entered, and
2598          * not in the subtransaction resource owner.
2599          */
2600         oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
2601         oldowner = CurrentResourceOwner;
2602         CurrentResourceOwner = estate->tuple_store_owner;
2603
2604         estate->tuple_store =
2605                 tuplestore_begin_heap(rsi->allowedModes & SFRM_Materialize_Random,
2606                                                           false, work_mem);
2607
2608         CurrentResourceOwner = oldowner;
2609         MemoryContextSwitchTo(oldcxt);
2610
2611         estate->rettupdesc = rsi->expectedDesc;
2612 }
2613
2614 /* ----------
2615  * exec_stmt_raise                      Build a message and throw it with elog()
2616  * ----------
2617  */
2618 static int
2619 exec_stmt_raise(PLpgSQL_execstate *estate, PLpgSQL_stmt_raise *stmt)
2620 {
2621         int                     err_code = 0;
2622         char       *condname = NULL;
2623         char       *err_message = NULL;
2624         char       *err_detail = NULL;
2625         char       *err_hint = NULL;
2626         ListCell   *lc;
2627
2628         /* RAISE with no parameters: re-throw current exception */
2629         if (stmt->condname == NULL && stmt->message == NULL &&
2630                 stmt->options == NIL)
2631         {
2632                 if (estate->cur_error != NULL)
2633                         ReThrowError(estate->cur_error);
2634                 /* oops, we're not inside a handler */
2635                 ereport(ERROR,
2636                                 (errcode(ERRCODE_SYNTAX_ERROR),
2637                                  errmsg("RAISE without parameters cannot be used outside an exception handler")));
2638         }
2639
2640         if (stmt->condname)
2641         {
2642                 err_code = plpgsql_recognize_err_condition(stmt->condname, true);
2643                 condname = pstrdup(stmt->condname);
2644         }
2645
2646         if (stmt->message)
2647         {
2648                 StringInfoData ds;
2649                 ListCell   *current_param;
2650                 char       *cp;
2651
2652                 initStringInfo(&ds);
2653                 current_param = list_head(stmt->params);
2654
2655                 for (cp = stmt->message; *cp; cp++)
2656                 {
2657                         /*
2658                          * Occurrences of a single % are replaced by the next parameter's
2659                          * external representation. Double %'s are converted to one %.
2660                          */
2661                         if (cp[0] == '%')
2662                         {
2663                                 Oid                     paramtypeid;
2664                                 Datum           paramvalue;
2665                                 bool            paramisnull;
2666                                 char       *extval;
2667
2668                                 if (cp[1] == '%')
2669                                 {
2670                                         appendStringInfoChar(&ds, '%');
2671                                         cp++;
2672                                         continue;
2673                                 }
2674
2675                                 if (current_param == NULL)
2676                                         ereport(ERROR,
2677                                                         (errcode(ERRCODE_SYNTAX_ERROR),
2678                                                   errmsg("too few parameters specified for RAISE")));
2679
2680                                 paramvalue = exec_eval_expr(estate,
2681                                                                           (PLpgSQL_expr *) lfirst(current_param),
2682                                                                                         &paramisnull,
2683                                                                                         &paramtypeid);
2684
2685                                 if (paramisnull)
2686                                         extval = "<NULL>";
2687                                 else
2688                                         extval = convert_value_to_string(paramvalue, paramtypeid);
2689                                 appendStringInfoString(&ds, extval);
2690                                 current_param = lnext(current_param);
2691                                 exec_eval_cleanup(estate);
2692                         }
2693                         else
2694                                 appendStringInfoChar(&ds, cp[0]);
2695                 }
2696
2697                 /*
2698                  * If more parameters were specified than were required to process the
2699                  * format string, throw an error
2700                  */
2701                 if (current_param != NULL)
2702                         ereport(ERROR,
2703                                         (errcode(ERRCODE_SYNTAX_ERROR),
2704                                          errmsg("too many parameters specified for RAISE")));
2705
2706                 err_message = ds.data;
2707                 /* No pfree(ds.data), the pfree(err_message) does it */
2708         }
2709
2710         foreach(lc, stmt->options)
2711         {
2712                 PLpgSQL_raise_option *opt = (PLpgSQL_raise_option *) lfirst(lc);
2713                 Datum           optionvalue;
2714                 bool            optionisnull;
2715                 Oid                     optiontypeid;
2716                 char       *extval;
2717
2718                 optionvalue = exec_eval_expr(estate, opt->expr,
2719                                                                          &optionisnull,
2720                                                                          &optiontypeid);
2721                 if (optionisnull)
2722                         ereport(ERROR,
2723                                         (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2724                                          errmsg("RAISE statement option cannot be null")));
2725
2726                 extval = convert_value_to_string(optionvalue, optiontypeid);
2727
2728                 switch (opt->opt_type)
2729                 {
2730                         case PLPGSQL_RAISEOPTION_ERRCODE:
2731                                 if (err_code)
2732                                         ereport(ERROR,
2733                                                         (errcode(ERRCODE_SYNTAX_ERROR),
2734                                                          errmsg("RAISE option already specified: %s",
2735                                                                         "ERRCODE")));
2736                                 err_code = plpgsql_recognize_err_condition(extval, true);
2737                                 condname = pstrdup(extval);
2738                                 break;
2739                         case PLPGSQL_RAISEOPTION_MESSAGE:
2740                                 if (err_message)
2741                                         ereport(ERROR,
2742                                                         (errcode(ERRCODE_SYNTAX_ERROR),
2743                                                          errmsg("RAISE option already specified: %s",
2744                                                                         "MESSAGE")));
2745                                 err_message = pstrdup(extval);
2746                                 break;
2747                         case PLPGSQL_RAISEOPTION_DETAIL:
2748                                 if (err_detail)
2749                                         ereport(ERROR,
2750                                                         (errcode(ERRCODE_SYNTAX_ERROR),
2751                                                          errmsg("RAISE option already specified: %s",
2752                                                                         "DETAIL")));
2753                                 err_detail = pstrdup(extval);
2754                                 break;
2755                         case PLPGSQL_RAISEOPTION_HINT:
2756                                 if (err_hint)
2757                                         ereport(ERROR,
2758                                                         (errcode(ERRCODE_SYNTAX_ERROR),
2759                                                          errmsg("RAISE option already specified: %s",
2760                                                                         "HINT")));
2761                                 err_hint = pstrdup(extval);
2762                                 break;
2763                         default:
2764                                 elog(ERROR, "unrecognized raise option: %d", opt->opt_type);
2765                 }
2766
2767                 exec_eval_cleanup(estate);
2768         }
2769
2770         /* Default code if nothing specified */
2771         if (err_code == 0 && stmt->elog_level >= ERROR)
2772                 err_code = ERRCODE_RAISE_EXCEPTION;
2773
2774         /* Default error message if nothing specified */
2775         if (err_message == NULL)
2776         {
2777                 if (condname)
2778                 {
2779                         err_message = condname;
2780                         condname = NULL;
2781                 }
2782                 else
2783                         err_message = pstrdup(unpack_sql_state(err_code));
2784         }
2785
2786         /*
2787          * Throw the error (may or may not come back)
2788          */
2789         estate->err_text = raise_skip_msg;      /* suppress traceback of raise */
2790
2791         ereport(stmt->elog_level,
2792                         (err_code ? errcode(err_code) : 0,
2793                          errmsg_internal("%s", err_message),
2794                          (err_detail != NULL) ? errdetail("%s", err_detail) : 0,
2795                          (err_hint != NULL) ? errhint("%s", err_hint) : 0));
2796
2797         estate->err_text = NULL;        /* un-suppress... */
2798
2799         if (condname != NULL)
2800                 pfree(condname);
2801         if (err_message != NULL)
2802                 pfree(err_message);
2803         if (err_detail != NULL)
2804                 pfree(err_detail);
2805         if (err_hint != NULL)
2806                 pfree(err_hint);
2807
2808         return PLPGSQL_RC_OK;
2809 }
2810
2811
2812 /* ----------
2813  * Initialize a mostly empty execution state
2814  * ----------
2815  */
2816 static void
2817 plpgsql_estate_setup(PLpgSQL_execstate *estate,
2818                                          PLpgSQL_function *func,
2819                                          ReturnSetInfo *rsi)
2820 {
2821         /* this link will be restored at exit from plpgsql_call_handler */
2822         func->cur_estate = estate;
2823
2824         estate->func = func;
2825
2826         estate->retval = (Datum) 0;
2827         estate->retisnull = true;
2828         estate->rettype = InvalidOid;
2829
2830         estate->fn_rettype = func->fn_rettype;
2831         estate->retistuple = func->fn_retistuple;
2832         estate->retisset = func->fn_retset;
2833
2834         estate->readonly_func = func->fn_readonly;
2835
2836         estate->rettupdesc = NULL;
2837         estate->exitlabel = NULL;
2838         estate->cur_error = NULL;
2839
2840         estate->tuple_store = NULL;
2841         if (rsi)
2842         {
2843                 estate->tuple_store_cxt = rsi->econtext->ecxt_per_query_memory;
2844                 estate->tuple_store_owner = CurrentResourceOwner;
2845         }
2846         else
2847         {
2848                 estate->tuple_store_cxt = NULL;
2849                 estate->tuple_store_owner = NULL;
2850         }
2851         estate->rsi = rsi;
2852
2853         estate->found_varno = func->found_varno;
2854         estate->ndatums = func->ndatums;
2855         estate->datums = palloc(sizeof(PLpgSQL_datum *) * estate->ndatums);
2856         /* caller is expected to fill the datums array */
2857
2858         estate->eval_tuptable = NULL;
2859         estate->eval_processed = 0;
2860         estate->eval_lastoid = InvalidOid;
2861         estate->eval_econtext = NULL;
2862         estate->cur_expr = NULL;
2863
2864         estate->err_stmt = NULL;
2865         estate->err_text = NULL;
2866
2867         estate->plugin_info = NULL;
2868
2869         /*
2870          * Create an EState and ExprContext for evaluation of simple expressions.
2871          */
2872         plpgsql_create_econtext(estate);
2873
2874         /*
2875          * Let the plugin see this function before we initialize any local
2876          * PL/pgSQL variables - note that we also give the plugin a few function
2877          * pointers so it can call back into PL/pgSQL for doing things like
2878          * variable assignments and stack traces
2879          */
2880         if (*plugin_ptr)
2881         {
2882                 (*plugin_ptr)->error_callback = plpgsql_exec_error_callback;
2883                 (*plugin_ptr)->assign_expr = exec_assign_expr;
2884
2885                 if ((*plugin_ptr)->func_setup)
2886                         ((*plugin_ptr)->func_setup) (estate, func);
2887         }
2888 }
2889
2890 /* ----------
2891  * Release temporary memory used by expression/subselect evaluation
2892  *
2893  * NB: the result of the evaluation is no longer valid after this is done,
2894  * unless it is a pass-by-value datatype.
2895  *
2896  * NB: if you change this code, see also the hacks in exec_assign_value's
2897  * PLPGSQL_DTYPE_ARRAYELEM case.
2898  * ----------
2899  */
2900 static void
2901 exec_eval_cleanup(PLpgSQL_execstate *estate)
2902 {
2903         /* Clear result of a full SPI_execute */
2904         if (estate->eval_tuptable != NULL)
2905                 SPI_freetuptable(estate->eval_tuptable);
2906         estate->eval_tuptable = NULL;
2907
2908         /* Clear result of exec_eval_simple_expr (but keep the econtext) */
2909         if (estate->eval_econtext != NULL)
2910                 ResetExprContext(estate->eval_econtext);
2911 }
2912
2913
2914 /* ----------
2915  * Generate a prepared plan
2916  * ----------
2917  */
2918 static void
2919 exec_prepare_plan(PLpgSQL_execstate *estate,
2920                                   PLpgSQL_expr *expr, int cursorOptions)
2921 {
2922         SPIPlanPtr      plan;
2923
2924         /*
2925          * The grammar can't conveniently set expr->func while building the parse
2926          * tree, so make sure it's set before parser hooks need it.
2927          */
2928         expr->func = estate->func;
2929
2930         /*
2931          * Generate and save the plan
2932          */
2933         plan = SPI_prepare_params(expr->query,
2934                                                           (ParserSetupHook) plpgsql_parser_setup,
2935                                                           (void *) expr,
2936                                                           cursorOptions);
2937         if (plan == NULL)
2938         {
2939                 /* Some SPI errors deserve specific error messages */
2940                 switch (SPI_result)
2941                 {
2942                         case SPI_ERROR_COPY:
2943                                 ereport(ERROR,
2944                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2945                                                  errmsg("cannot COPY to/from client in PL/pgSQL")));
2946                         case SPI_ERROR_TRANSACTION:
2947                                 ereport(ERROR,
2948                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2949                                                  errmsg("cannot begin/end transactions in PL/pgSQL"),
2950                                                  errhint("Use a BEGIN block with an EXCEPTION clause instead.")));
2951                         default:
2952                                 elog(ERROR, "SPI_prepare_params failed for \"%s\": %s",
2953                                          expr->query, SPI_result_code_string(SPI_result));
2954                 }
2955         }
2956         expr->plan = SPI_saveplan(plan);
2957         SPI_freeplan(plan);
2958         exec_simple_check_plan(expr);
2959 }
2960
2961
2962 /* ----------
2963  * exec_stmt_execsql                    Execute an SQL statement (possibly with INTO).
2964  * ----------
2965  */
2966 static int
2967 exec_stmt_execsql(PLpgSQL_execstate *estate,
2968                                   PLpgSQL_stmt_execsql *stmt)
2969 {
2970         ParamListInfo paramLI;
2971         long            tcount;
2972         int                     rc;
2973         PLpgSQL_expr *expr = stmt->sqlstmt;
2974
2975         /*
2976          * On the first call for this statement generate the plan, and detect
2977          * whether the statement is INSERT/UPDATE/DELETE
2978          */
2979         if (expr->plan == NULL)
2980         {
2981                 ListCell   *l;
2982
2983                 exec_prepare_plan(estate, expr, 0);
2984                 stmt->mod_stmt = false;
2985                 foreach(l, expr->plan->plancache_list)
2986                 {
2987                         CachedPlanSource *plansource = (CachedPlanSource *) lfirst(l);
2988                         ListCell   *l2;
2989
2990                         foreach(l2, plansource->plan->stmt_list)
2991                         {
2992                                 PlannedStmt *p = (PlannedStmt *) lfirst(l2);
2993
2994                                 if (IsA(p, PlannedStmt) &&
2995                                         p->canSetTag)
2996                                 {
2997                                         if (p->commandType == CMD_INSERT ||
2998                                                 p->commandType == CMD_UPDATE ||
2999                                                 p->commandType == CMD_DELETE)
3000                                                 stmt->mod_stmt = true;
3001                                 }
3002                         }
3003                 }
3004         }
3005
3006         /*
3007          * Set up ParamListInfo (note this is only carrying a hook function, not
3008          * any actual data values, at this point)
3009          */
3010         paramLI = setup_param_list(estate, expr);
3011
3012         /*
3013          * If we have INTO, then we only need one row back ... but if we have INTO
3014          * STRICT, ask for two rows, so that we can verify the statement returns
3015          * only one.  INSERT/UPDATE/DELETE are always treated strictly. Without
3016          * INTO, just run the statement to completion (tcount = 0).
3017          *
3018          * We could just ask for two rows always when using INTO, but there are
3019          * some cases where demanding the extra row costs significant time, eg by
3020          * forcing completion of a sequential scan.  So don't do it unless we need
3021          * to enforce strictness.
3022          */
3023         if (stmt->into)
3024         {
3025                 if (stmt->strict || stmt->mod_stmt)
3026                         tcount = 2;
3027                 else
3028                         tcount = 1;
3029         }
3030         else
3031                 tcount = 0;
3032
3033         /*
3034          * Execute the plan
3035          */
3036         rc = SPI_execute_plan_with_paramlist(expr->plan, paramLI,
3037                                                                                  estate->readonly_func, tcount);
3038
3039         /*
3040          * Check for error, and set FOUND if appropriate (for historical reasons
3041          * we set FOUND only for certain query types).  Also Assert that we
3042          * identified the statement type the same as SPI did.
3043          */
3044         switch (rc)
3045         {
3046                 case SPI_OK_SELECT:
3047                         Assert(!stmt->mod_stmt);
3048                         exec_set_found(estate, (SPI_processed != 0));
3049                         break;
3050
3051                 case SPI_OK_INSERT:
3052                 case SPI_OK_UPDATE:
3053                 case SPI_OK_DELETE:
3054                 case SPI_OK_INSERT_RETURNING:
3055                 case SPI_OK_UPDATE_RETURNING:
3056                 case SPI_OK_DELETE_RETURNING:
3057                         Assert(stmt->mod_stmt);
3058                         exec_set_found(estate, (SPI_processed != 0));
3059                         break;
3060
3061                 case SPI_OK_SELINTO:
3062                 case SPI_OK_UTILITY:
3063                         Assert(!stmt->mod_stmt);
3064                         break;
3065
3066                 case SPI_OK_REWRITTEN:
3067                         Assert(!stmt->mod_stmt);
3068
3069                         /*
3070                          * The command was rewritten into another kind of command. It's
3071                          * not clear what FOUND would mean in that case (and SPI doesn't
3072                          * return the row count either), so just set it to false.
3073                          */
3074                         exec_set_found(estate, false);
3075                         break;
3076
3077                         /* Some SPI errors deserve specific error messages */
3078                 case SPI_ERROR_COPY:
3079                         ereport(ERROR,
3080                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3081                                          errmsg("cannot COPY to/from client in PL/pgSQL")));
3082                 case SPI_ERROR_TRANSACTION:
3083                         ereport(ERROR,
3084                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3085                                          errmsg("cannot begin/end transactions in PL/pgSQL"),
3086                         errhint("Use a BEGIN block with an EXCEPTION clause instead.")));
3087
3088                 default:
3089                         elog(ERROR, "SPI_execute_plan_with_paramlist failed executing query \"%s\": %s",
3090                                  expr->query, SPI_result_code_string(rc));
3091         }
3092
3093         /* All variants should save result info for GET DIAGNOSTICS */
3094         estate->eval_processed = SPI_processed;
3095         estate->eval_lastoid = SPI_lastoid;
3096
3097         /* Process INTO if present */
3098         if (stmt->into)
3099         {
3100                 SPITupleTable *tuptab = SPI_tuptable;
3101                 uint32          n = SPI_processed;
3102                 PLpgSQL_rec *rec = NULL;
3103                 PLpgSQL_row *row = NULL;
3104
3105                 /* If the statement did not return a tuple table, complain */
3106                 if (tuptab == NULL)
3107                         ereport(ERROR,
3108                                         (errcode(ERRCODE_SYNTAX_ERROR),
3109                                 errmsg("INTO used with a command that cannot return data")));
3110
3111                 /* Determine if we assign to a record or a row */
3112                 if (stmt->rec != NULL)
3113                         rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->dno]);
3114                 else if (stmt->row != NULL)
3115                         row = (PLpgSQL_row *) (estate->datums[stmt->row->dno]);
3116                 else
3117                         elog(ERROR, "unsupported target");
3118
3119                 /*
3120                  * If SELECT ... INTO specified STRICT, and the query didn't find
3121                  * exactly one row, throw an error.  If STRICT was not specified, then
3122                  * allow the query to find any number of rows.
3123                  */
3124                 if (n == 0)
3125                 {
3126                         if (stmt->strict)
3127                                 ereport(ERROR,
3128                                                 (errcode(ERRCODE_NO_DATA_FOUND),
3129                                                  errmsg("query returned no rows")));
3130                         /* set the target to NULL(s) */
3131                         exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
3132                 }
3133                 else
3134                 {
3135                         if (n > 1 && (stmt->strict || stmt->mod_stmt))
3136                                 ereport(ERROR,
3137                                                 (errcode(ERRCODE_TOO_MANY_ROWS),
3138                                                  errmsg("query returned more than one row")));
3139                         /* Put the first result row into the target */
3140                         exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
3141                 }
3142
3143                 /* Clean up */
3144                 SPI_freetuptable(SPI_tuptable);
3145         }
3146         else
3147         {
3148                 /* If the statement returned a tuple table, complain */
3149                 if (SPI_tuptable != NULL)
3150                         ereport(ERROR,
3151                                         (errcode(ERRCODE_SYNTAX_ERROR),
3152                                          errmsg("query has no destination for result data"),
3153                                          (rc == SPI_OK_SELECT) ? errhint("If you want to discard the results of a SELECT, use PERFORM instead.") : 0));
3154         }
3155
3156         if (paramLI)
3157                 pfree(paramLI);
3158
3159         return PLPGSQL_RC_OK;
3160 }
3161
3162
3163 /* ----------
3164  * exec_stmt_dynexecute                 Execute a dynamic SQL query
3165  *                                      (possibly with INTO).
3166  * ----------
3167  */
3168 static int
3169 exec_stmt_dynexecute(PLpgSQL_execstate *estate,
3170                                          PLpgSQL_stmt_dynexecute *stmt)
3171 {
3172         Datum           query;
3173         bool            isnull = false;
3174         Oid                     restype;
3175         char       *querystr;
3176         int                     exec_res;
3177
3178         /*
3179          * First we evaluate the string expression after the EXECUTE keyword. Its
3180          * result is the querystring we have to execute.
3181          */
3182         query = exec_eval_expr(estate, stmt->query, &isnull, &restype);
3183         if (isnull)
3184                 ereport(ERROR,
3185                                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3186                                  errmsg("query string argument of EXECUTE is null")));
3187
3188         /* Get the C-String representation */
3189         querystr = convert_value_to_string(query, restype);
3190
3191         exec_eval_cleanup(estate);
3192
3193         /*
3194          * Execute the query without preparing a saved plan.
3195          */
3196         if (stmt->params)
3197         {
3198                 PreparedParamsData *ppd;
3199
3200                 ppd = exec_eval_using_params(estate, stmt->params);
3201                 exec_res = SPI_execute_with_args(querystr,
3202                                                                                  ppd->nargs, ppd->types,
3203                                                                                  ppd->values, ppd->nulls,
3204                                                                                  estate->readonly_func, 0);
3205                 free_params_data(ppd);
3206         }
3207         else
3208                 exec_res = SPI_execute(querystr, estate->readonly_func, 0);
3209
3210         switch (exec_res)
3211         {
3212                 case SPI_OK_SELECT:
3213                 case SPI_OK_INSERT:
3214                 case SPI_OK_UPDATE:
3215                 case SPI_OK_DELETE:
3216                 case SPI_OK_INSERT_RETURNING:
3217                 case SPI_OK_UPDATE_RETURNING:
3218                 case SPI_OK_DELETE_RETURNING:
3219                 case SPI_OK_UTILITY:
3220                 case SPI_OK_REWRITTEN:
3221                         break;
3222
3223                 case 0:
3224
3225                         /*
3226                          * Also allow a zero return, which implies the querystring
3227                          * contained no commands.
3228                          */
3229                         break;
3230
3231                 case SPI_OK_SELINTO:
3232
3233                         /*
3234                          * We want to disallow SELECT INTO for now, because its behavior
3235                          * is not consistent with SELECT INTO in a normal plpgsql context.
3236                          * (We need to reimplement EXECUTE to parse the string as a
3237                          * plpgsql command, not just feed it to SPI_execute.) However,
3238                          * CREATE AS should be allowed ... and since it produces the same
3239                          * parsetree as SELECT INTO, there's no way to tell the difference
3240                          * except to look at the source text.  Wotta kluge!
3241                          */
3242                         {
3243                                 char       *ptr;
3244
3245                                 for (ptr = querystr; *ptr; ptr++)
3246                                         if (!scanner_isspace(*ptr))
3247                                                 break;
3248                                 if (*ptr == 'S' || *ptr == 's')
3249                                         ereport(ERROR,
3250                                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3251                                          errmsg("EXECUTE of SELECT ... INTO is not implemented"),
3252                                                          errhint("You might want to use EXECUTE ... INTO or EXECUTE CREATE TABLE ... AS instead.")));
3253                                 break;
3254                         }
3255
3256                         /* Some SPI errors deserve specific error messages */
3257                 case SPI_ERROR_COPY:
3258                         ereport(ERROR,
3259                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3260                                          errmsg("cannot COPY to/from client in PL/pgSQL")));
3261                 case SPI_ERROR_TRANSACTION:
3262                         ereport(ERROR,
3263                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3264                                          errmsg("cannot begin/end transactions in PL/pgSQL"),
3265                         errhint("Use a BEGIN block with an EXCEPTION clause instead.")));
3266
3267                 default:
3268                         elog(ERROR, "SPI_execute failed executing query \"%s\": %s",
3269                                  querystr, SPI_result_code_string(exec_res));
3270                         break;
3271         }
3272
3273         /* Save result info for GET DIAGNOSTICS */
3274         estate->eval_processed = SPI_processed;
3275         estate->eval_lastoid = SPI_lastoid;
3276
3277         /* Process INTO if present */
3278         if (stmt->into)
3279         {
3280                 SPITupleTable *tuptab = SPI_tuptable;
3281                 uint32          n = SPI_processed;
3282                 PLpgSQL_rec *rec = NULL;
3283                 PLpgSQL_row *row = NULL;
3284
3285                 /* If the statement did not return a tuple table, complain */
3286                 if (tuptab == NULL)
3287                         ereport(ERROR,
3288                                         (errcode(ERRCODE_SYNTAX_ERROR),
3289                                 errmsg("INTO used with a command that cannot return data")));
3290
3291                 /* Determine if we assign to a record or a row */
3292                 if (stmt->rec != NULL)
3293                         rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->dno]);
3294                 else if (stmt->row != NULL)
3295                         row = (PLpgSQL_row *) (estate->datums[stmt->row->dno]);
3296                 else
3297                         elog(ERROR, "unsupported target");
3298
3299                 /*
3300                  * If SELECT ... INTO specified STRICT, and the query didn't find
3301                  * exactly one row, throw an error.  If STRICT was not specified, then
3302                  * allow the query to find any number of rows.
3303                  */
3304                 if (n == 0)
3305                 {
3306                         if (stmt->strict)
3307                                 ereport(ERROR,
3308                                                 (errcode(ERRCODE_NO_DATA_FOUND),
3309                                                  errmsg("query returned no rows")));
3310                         /* set the target to NULL(s) */
3311                         exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
3312                 }
3313                 else
3314                 {
3315                         if (n > 1 && stmt->strict)
3316                                 ereport(ERROR,
3317                                                 (errcode(ERRCODE_TOO_MANY_ROWS),
3318                                                  errmsg("query returned more than one row")));
3319                         /* Put the first result row into the target */
3320                         exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
3321                 }
3322         }
3323         else
3324         {
3325                 /*
3326                  * It might be a good idea to raise an error if the query returned
3327                  * tuples that are being ignored, but historically we have not done
3328                  * that.
3329                  */
3330         }
3331
3332         /* Release any result from SPI_execute, as well as the querystring */
3333         SPI_freetuptable(SPI_tuptable);
3334         pfree(querystr);
3335
3336         return PLPGSQL_RC_OK;
3337 }
3338
3339
3340 /* ----------
3341  * exec_stmt_dynfors                    Execute a dynamic query, assign each
3342  *                                      tuple to a record or row and
3343  *                                      execute a group of statements
3344  *                                      for it.
3345  * ----------
3346  */
3347 static int
3348 exec_stmt_dynfors(PLpgSQL_execstate *estate, PLpgSQL_stmt_dynfors *stmt)
3349 {
3350         Portal          portal;
3351         int                     rc;
3352
3353         portal = exec_dynquery_with_params(estate, stmt->query, stmt->params,
3354                                                                            NULL, 0);
3355
3356         /*
3357          * Execute the loop
3358          */
3359         rc = exec_for_query(estate, (PLpgSQL_stmt_forq *) stmt, portal, true);
3360
3361         /*
3362          * Close the implicit cursor
3363          */
3364         SPI_cursor_close(portal);
3365
3366         return rc;
3367 }
3368
3369
3370 /* ----------
3371  * exec_stmt_open                       Execute an OPEN cursor statement
3372  * ----------
3373  */
3374 static int
3375 exec_stmt_open(PLpgSQL_execstate *estate, PLpgSQL_stmt_open *stmt)
3376 {
3377         PLpgSQL_var *curvar;
3378         char       *curname = NULL;
3379         PLpgSQL_expr *query;
3380         Portal          portal;
3381         ParamListInfo paramLI;
3382
3383         /* ----------
3384          * Get the cursor variable and if it has an assigned name, check
3385          * that it's not in use currently.
3386          * ----------
3387          */
3388         curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
3389         if (!curvar->isnull)
3390         {
3391                 curname = TextDatumGetCString(curvar->value);
3392                 if (SPI_cursor_find(curname) != NULL)
3393                         ereport(ERROR,
3394                                         (errcode(ERRCODE_DUPLICATE_CURSOR),
3395                                          errmsg("cursor \"%s\" already in use", curname)));
3396         }
3397
3398         /* ----------
3399          * Process the OPEN according to it's type.
3400          * ----------
3401          */
3402         if (stmt->query != NULL)
3403         {
3404                 /* ----------
3405                  * This is an OPEN refcursor FOR SELECT ...
3406                  *
3407                  * We just make sure the query is planned. The real work is
3408                  * done downstairs.
3409                  * ----------
3410                  */
3411                 query = stmt->query;
3412                 if (query->plan == NULL)
3413                         exec_prepare_plan(estate, query, stmt->cursor_options);
3414         }
3415         else if (stmt->dynquery != NULL)
3416         {
3417                 /* ----------
3418                  * This is an OPEN refcursor FOR EXECUTE ...
3419                  * ----------
3420                  */
3421                 portal = exec_dynquery_with_params(estate,
3422                                                                                    stmt->dynquery,
3423                                                                                    stmt->params,
3424                                                                                    curname,
3425                                                                                    stmt->cursor_options);
3426
3427                 /*
3428                  * If cursor variable was NULL, store the generated portal name in it
3429                  */
3430                 if (curname == NULL)
3431                         assign_text_var(curvar, portal->name);
3432
3433                 return PLPGSQL_RC_OK;
3434         }
3435         else
3436         {
3437                 /* ----------
3438                  * This is an OPEN cursor
3439                  *
3440                  * Note: parser should already have checked that statement supplies
3441                  * args iff cursor needs them, but we check again to be safe.
3442                  * ----------
3443                  */
3444                 if (stmt->argquery != NULL)
3445                 {
3446                         /* ----------
3447                          * OPEN CURSOR with args.  We fake a SELECT ... INTO ...
3448                          * statement to evaluate the args and put 'em into the
3449                          * internal row.
3450                          * ----------
3451                          */
3452                         PLpgSQL_stmt_execsql set_args;
3453
3454                         if (curvar->cursor_explicit_argrow < 0)
3455                                 ereport(ERROR,
3456                                                 (errcode(ERRCODE_SYNTAX_ERROR),
3457                                         errmsg("arguments given for cursor without arguments")));
3458
3459                         memset(&set_args, 0, sizeof(set_args));
3460                         set_args.cmd_type = PLPGSQL_STMT_EXECSQL;
3461                         set_args.lineno = stmt->lineno;
3462                         set_args.sqlstmt = stmt->argquery;
3463                         set_args.into = true;
3464                         /* XXX historically this has not been STRICT */
3465                         set_args.row = (PLpgSQL_row *)
3466                                 (estate->datums[curvar->cursor_explicit_argrow]);
3467
3468                         if (exec_stmt_execsql(estate, &set_args) != PLPGSQL_RC_OK)
3469                                 elog(ERROR, "open cursor failed during argument processing");
3470                 }
3471                 else
3472                 {
3473                         if (curvar->cursor_explicit_argrow >= 0)
3474                                 ereport(ERROR,
3475                                                 (errcode(ERRCODE_SYNTAX_ERROR),
3476                                                  errmsg("arguments required for cursor")));
3477                 }
3478
3479                 query = curvar->cursor_explicit_expr;
3480                 if (query->plan == NULL)
3481                         exec_prepare_plan(estate, query, curvar->cursor_options);
3482         }
3483
3484         /*
3485          * Set up ParamListInfo (note this is only carrying a hook function, not
3486          * any actual data values, at this point)
3487          */
3488         paramLI = setup_param_list(estate, query);
3489
3490         /*
3491          * Open the cursor
3492          */
3493         portal = SPI_cursor_open_with_paramlist(curname, query->plan,
3494                                                                                         paramLI,
3495                                                                                         estate->readonly_func);
3496         if (portal == NULL)
3497                 elog(ERROR, "could not open cursor: %s",
3498                          SPI_result_code_string(SPI_result));
3499
3500         /*
3501          * If cursor variable was NULL, store the generated portal name in it
3502          */
3503         if (curname == NULL)
3504                 assign_text_var(curvar, portal->name);
3505
3506         if (curname)
3507                 pfree(curname);
3508         if (paramLI)
3509                 pfree(paramLI);
3510
3511         return PLPGSQL_RC_OK;
3512 }
3513
3514
3515 /* ----------
3516  * exec_stmt_fetch                      Fetch from a cursor into a target, or just
3517  *                                                      move the current position of the cursor
3518  * ----------
3519  */
3520 static int
3521 exec_stmt_fetch(PLpgSQL_execstate *estate, PLpgSQL_stmt_fetch *stmt)
3522 {
3523         PLpgSQL_var *curvar = NULL;
3524         PLpgSQL_rec *rec = NULL;
3525         PLpgSQL_row *row = NULL;
3526         long            how_many = stmt->how_many;
3527         SPITupleTable *tuptab;
3528         Portal          portal;
3529         char       *curname;
3530         uint32          n;
3531
3532         /* ----------
3533          * Get the portal of the cursor by name
3534          * ----------
3535          */
3536         curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
3537         if (curvar->isnull)
3538                 ereport(ERROR,
3539                                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3540                                  errmsg("cursor variable \"%s\" is null", curvar->refname)));
3541         curname = TextDatumGetCString(curvar->value);
3542
3543         portal = SPI_cursor_find(curname);
3544         if (portal == NULL)
3545                 ereport(ERROR,
3546                                 (errcode(ERRCODE_UNDEFINED_CURSOR),
3547                                  errmsg("cursor \"%s\" does not exist", curname)));
3548         pfree(curname);
3549
3550         /* Calculate position for FETCH_RELATIVE or FETCH_ABSOLUTE */
3551         if (stmt->expr)
3552         {
3553                 bool            isnull;
3554
3555                 /* XXX should be doing this in LONG not INT width */
3556                 how_many = exec_eval_integer(estate, stmt->expr, &isnull);
3557
3558                 if (isnull)
3559                         ereport(ERROR,
3560                                         (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3561                                          errmsg("relative or absolute cursor position is null")));
3562
3563                 exec_eval_cleanup(estate);
3564         }
3565
3566         if (!stmt->is_move)
3567         {
3568                 /* ----------
3569                  * Determine if we fetch into a record or a row
3570                  * ----------
3571                  */
3572                 if (stmt->rec != NULL)
3573                         rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->dno]);
3574                 else if (stmt->row != NULL)
3575                         row = (PLpgSQL_row *) (estate->datums[stmt->row->dno]);
3576                 else
3577                         elog(ERROR, "unsupported target");
3578
3579                 /* ----------
3580                  * Fetch 1 tuple from the cursor
3581                  * ----------
3582                  */
3583                 SPI_scroll_cursor_fetch(portal, stmt->direction, how_many);
3584                 tuptab = SPI_tuptable;
3585                 n = SPI_processed;
3586
3587                 /* ----------
3588                  * Set the target appropriately.
3589                  * ----------
3590                  */
3591                 if (n == 0)
3592                         exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
3593                 else
3594                         exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
3595
3596                 SPI_freetuptable(tuptab);
3597         }
3598         else
3599         {
3600                 /* Move the cursor */
3601                 SPI_scroll_cursor_move(portal, stmt->direction, how_many);
3602                 n = SPI_processed;
3603         }
3604
3605         /* Set the ROW_COUNT and the global FOUND variable appropriately. */
3606         estate->eval_processed = n;
3607         exec_set_found(estate, n != 0);
3608
3609         return PLPGSQL_RC_OK;
3610 }
3611
3612 /* ----------
3613  * exec_stmt_close                      Close a cursor
3614  * ----------
3615  */
3616 static int
3617 exec_stmt_close(PLpgSQL_execstate *estate, PLpgSQL_stmt_close *stmt)
3618 {
3619         PLpgSQL_var *curvar = NULL;
3620         Portal          portal;
3621         char       *curname;
3622
3623         /* ----------
3624          * Get the portal of the cursor by name
3625          * ----------
3626          */
3627         curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
3628         if (curvar->isnull)
3629                 ereport(ERROR,
3630                                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3631                                  errmsg("cursor variable \"%s\" is null", curvar->refname)));
3632         curname = TextDatumGetCString(curvar->value);
3633
3634         portal = SPI_cursor_find(curname);
3635         if (portal == NULL)
3636                 ereport(ERROR,
3637                                 (errcode(ERRCODE_UNDEFINED_CURSOR),
3638                                  errmsg("cursor \"%s\" does not exist", curname)));
3639         pfree(curname);
3640
3641         /* ----------
3642          * And close it.
3643          * ----------
3644          */
3645         SPI_cursor_close(portal);
3646
3647         return PLPGSQL_RC_OK;
3648 }
3649
3650
3651 /* ----------
3652  * exec_assign_expr                     Put an expression's result into
3653  *                                      a variable.
3654  * ----------
3655  */
3656 static void
3657 exec_assign_expr(PLpgSQL_execstate *estate, PLpgSQL_datum *target,
3658                                  PLpgSQL_expr *expr)
3659 {
3660         Datum           value;
3661         Oid                     valtype;
3662         bool            isnull = false;
3663
3664         value = exec_eval_expr(estate, expr, &isnull, &valtype);
3665         exec_assign_value(estate, target, value, valtype, &isnull);
3666         exec_eval_cleanup(estate);
3667 }
3668
3669
3670 /* ----------
3671  * exec_assign_value                    Put a value into a target field
3672  *
3673  * Note: in some code paths, this may leak memory in the eval_econtext;
3674  * we assume that will be cleaned up later by exec_eval_cleanup.  We cannot
3675  * call exec_eval_cleanup here for fear of destroying the input Datum value.
3676  * ----------
3677  */
3678 static void
3679 exec_assign_value(PLpgSQL_execstate *estate,
3680                                   PLpgSQL_datum *target,
3681                                   Datum value, Oid valtype, bool *isNull)
3682 {
3683         switch (target->dtype)
3684         {
3685                 case PLPGSQL_DTYPE_VAR:
3686                         {
3687                                 /*
3688                                  * Target is a variable
3689                                  */
3690                                 PLpgSQL_var *var = (PLpgSQL_var *) target;
3691                                 Datum           newvalue;
3692
3693                                 newvalue = exec_cast_value(value, valtype, var->datatype->typoid,
3694                                                                                    &(var->datatype->typinput),
3695                                                                                    var->datatype->typioparam,
3696                                                                                    var->datatype->atttypmod,
3697                                                                                    *isNull);
3698
3699                                 if (*isNull && var->notnull)
3700                                         ereport(ERROR,
3701                                                         (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3702                                                          errmsg("null value cannot be assigned to variable \"%s\" declared NOT NULL",
3703                                                                         var->refname)));
3704
3705                                 /*
3706                                  * If type is by-reference, make sure we have a freshly
3707                                  * palloc'd copy; the originally passed value may not live as
3708                                  * long as the variable!  But we don't need to re-copy if
3709                                  * exec_cast_value performed a conversion; its output must
3710                                  * already be palloc'd.
3711                                  */
3712                                 if (!var->datatype->typbyval && !*isNull)
3713                                 {
3714                                         if (newvalue == value)
3715                                                 newvalue = datumCopy(newvalue,
3716                                                                                          false,
3717                                                                                          var->datatype->typlen);
3718                                 }
3719
3720                                 /*
3721                                  * Now free the old value.      (We can't do this any earlier
3722                                  * because of the possibility that we are assigning the var's
3723                                  * old value to it, eg "foo := foo".  We could optimize out
3724                                  * the assignment altogether in such cases, but it's too
3725                                  * infrequent to be worth testing for.)
3726                                  */
3727                                 free_var(var);
3728
3729                                 var->value = newvalue;
3730                                 var->isnull = *isNull;
3731                                 if (!var->datatype->typbyval && !*isNull)
3732                                         var->freeval = true;
3733                                 break;
3734                         }
3735
3736                 case PLPGSQL_DTYPE_ROW:
3737                         {
3738                                 /*
3739                                  * Target is a row variable
3740                                  */
3741                                 PLpgSQL_row *row = (PLpgSQL_row *) target;
3742
3743                                 if (*isNull)
3744                                 {
3745                                         /* If source is null, just assign nulls to the row */
3746                                         exec_move_row(estate, NULL, row, NULL, NULL);
3747                                 }
3748                                 else
3749                                 {
3750                                         HeapTupleHeader td;
3751                                         Oid                     tupType;
3752                                         int32           tupTypmod;
3753                                         TupleDesc       tupdesc;
3754                                         HeapTupleData tmptup;
3755
3756                                         /* Source must be of RECORD or composite type */
3757                                         if (!type_is_rowtype(valtype))
3758                                                 ereport(ERROR,
3759                                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
3760                                                                  errmsg("cannot assign non-composite value to a row variable")));
3761                                         /* Source is a tuple Datum, so safe to do this: */
3762                                         td = DatumGetHeapTupleHeader(value);
3763                                         /* Extract rowtype info and find a tupdesc */
3764                                         tupType = HeapTupleHeaderGetTypeId(td);
3765                                         tupTypmod = HeapTupleHeaderGetTypMod(td);
3766                                         tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
3767                                         /* Build a temporary HeapTuple control structure */
3768                                         tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
3769                                         ItemPointerSetInvalid(&(tmptup.t_self));
3770                                         tmptup.t_tableOid = InvalidOid;
3771                                         tmptup.t_data = td;
3772                                         exec_move_row(estate, NULL, row, &tmptup, tupdesc);
3773                                         ReleaseTupleDesc(tupdesc);
3774                                 }
3775                                 break;
3776                         }
3777
3778                 case PLPGSQL_DTYPE_REC:
3779                         {
3780                                 /*
3781                                  * Target is a record variable
3782                                  */
3783                                 PLpgSQL_rec *rec = (PLpgSQL_rec *) target;
3784
3785                                 if (*isNull)
3786                                 {
3787                                         /* If source is null, just assign nulls to the record */
3788                                         exec_move_row(estate, rec, NULL, NULL, NULL);
3789                                 }
3790                                 else
3791                                 {
3792                                         HeapTupleHeader td;
3793                                         Oid                     tupType;
3794                                         int32           tupTypmod;
3795                                         TupleDesc       tupdesc;
3796                                         HeapTupleData tmptup;
3797
3798                                         /* Source must be of RECORD or composite type */
3799                                         if (!type_is_rowtype(valtype))
3800                                                 ereport(ERROR,
3801                                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
3802                                                                  errmsg("cannot assign non-composite value to a record variable")));
3803
3804                                         /* Source is a tuple Datum, so safe to do this: */
3805                                         td = DatumGetHeapTupleHeader(value);
3806                                         /* Extract rowtype info and find a tupdesc */
3807                                         tupType = HeapTupleHeaderGetTypeId(td);
3808                                         tupTypmod = HeapTupleHeaderGetTypMod(td);
3809                                         tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
3810                                         /* Build a temporary HeapTuple control structure */
3811                                         tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
3812                                         ItemPointerSetInvalid(&(tmptup.t_self));
3813                                         tmptup.t_tableOid = InvalidOid;
3814                                         tmptup.t_data = td;
3815                                         exec_move_row(estate, rec, NULL, &tmptup, tupdesc);
3816                                         ReleaseTupleDesc(tupdesc);
3817                                 }
3818                                 break;
3819                         }
3820
3821                 case PLPGSQL_DTYPE_RECFIELD:
3822                         {
3823                                 /*
3824                                  * Target is a field of a record
3825                                  */
3826                                 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) target;
3827                                 PLpgSQL_rec *rec;
3828                                 int                     fno;
3829                                 HeapTuple       newtup;
3830                                 int                     natts;
3831                                 Datum      *values;
3832                                 bool       *nulls;
3833                                 bool       *replaces;
3834                                 void       *mustfree;
3835                                 bool            attisnull;
3836                                 Oid                     atttype;
3837                                 int32           atttypmod;
3838
3839                                 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
3840
3841                                 /*
3842                                  * Check that there is already a tuple in the record. We need
3843                                  * that because records don't have any predefined field
3844                                  * structure.
3845                                  */
3846                                 if (!HeapTupleIsValid(rec->tup))
3847                                         ereport(ERROR,
3848                                                   (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3849                                                    errmsg("record \"%s\" is not assigned yet",
3850                                                                   rec->refname),
3851                                                    errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
3852
3853                                 /*
3854                                  * Get the number of the records field to change and the
3855                                  * number of attributes in the tuple.  Note: disallow system
3856                                  * column names because the code below won't cope.
3857                                  */
3858                                 fno = SPI_fnumber(rec->tupdesc, recfield->fieldname);
3859                                 if (fno <= 0)
3860                                         ereport(ERROR,
3861                                                         (errcode(ERRCODE_UNDEFINED_COLUMN),
3862                                                          errmsg("record \"%s\" has no field \"%s\"",
3863                                                                         rec->refname, recfield->fieldname)));
3864                                 fno--;
3865                                 natts = rec->tupdesc->natts;
3866
3867                                 /*
3868                                  * Set up values/control arrays for heap_modify_tuple. For all
3869                                  * the attributes except the one we want to replace, use the
3870                                  * value that's in the old tuple.
3871                                  */
3872                                 values = palloc(sizeof(Datum) * natts);
3873                                 nulls = palloc(sizeof(bool) * natts);
3874                                 replaces = palloc(sizeof(bool) * natts);
3875
3876                                 memset(replaces, false, sizeof(bool) * natts);
3877                                 replaces[fno] = true;
3878
3879                                 /*
3880                                  * Now insert the new value, being careful to cast it to the
3881                                  * right type.
3882                                  */
3883                                 atttype = SPI_gettypeid(rec->tupdesc, fno + 1);
3884                                 atttypmod = rec->tupdesc->attrs[fno]->atttypmod;
3885                                 attisnull = *isNull;
3886                                 values[fno] = exec_simple_cast_value(value,
3887                                                                                                          valtype,
3888                                                                                                          atttype,
3889                                                                                                          atttypmod,
3890                                                                                                          attisnull);
3891                                 nulls[fno] = attisnull;
3892
3893                                 /*
3894                                  * Avoid leaking the result of exec_simple_cast_value, if it
3895                                  * performed a conversion to a pass-by-ref type.
3896                                  */
3897                                 if (!attisnull && values[fno] != value && !get_typbyval(atttype))
3898                                         mustfree = DatumGetPointer(values[fno]);
3899                                 else
3900                                         mustfree = NULL;
3901
3902                                 /*
3903                                  * Now call heap_modify_tuple() to create a new tuple that
3904                                  * replaces the old one in the record.
3905                                  */
3906                                 newtup = heap_modify_tuple(rec->tup, rec->tupdesc,
3907                                                                                    values, nulls, replaces);
3908
3909                                 if (rec->freetup)
3910                                         heap_freetuple(rec->tup);
3911
3912                                 rec->tup = newtup;
3913                                 rec->freetup = true;
3914
3915                                 pfree(values);
3916                                 pfree(nulls);
3917                                 pfree(replaces);
3918                                 if (mustfree)
3919                                         pfree(mustfree);
3920
3921                                 break;
3922                         }
3923
3924                 case PLPGSQL_DTYPE_ARRAYELEM:
3925                         {
3926                                 /*
3927                                  * Target is an element of an array
3928                                  */
3929                                 int                     nsubscripts;
3930                                 int                     i;
3931                                 PLpgSQL_expr *subscripts[MAXDIM];
3932                                 int                     subscriptvals[MAXDIM];
3933                                 bool            oldarrayisnull;
3934                                 Oid                     arraytypeid,
3935                                                         arrayelemtypeid;
3936                                 int32           arraytypmod;
3937                                 int16           arraytyplen,
3938                                                         elemtyplen;
3939                                 bool            elemtypbyval;
3940                                 char            elemtypalign;
3941                                 Datum           oldarraydatum,
3942                                                         coerced_value;
3943                                 ArrayType  *oldarrayval;
3944                                 ArrayType  *newarrayval;
3945                                 SPITupleTable *save_eval_tuptable;
3946
3947                                 /*
3948                                  * We need to do subscript evaluation, which might require
3949                                  * evaluating general expressions; and the caller might have
3950                                  * done that too in order to prepare the input Datum.  We
3951                                  * have to save and restore the caller's SPI_execute result,
3952                                  * if any.
3953                                  */
3954                                 save_eval_tuptable = estate->eval_tuptable;
3955                                 estate->eval_tuptable = NULL;
3956
3957                                 /*
3958                                  * To handle constructs like x[1][2] := something, we have to
3959                                  * be prepared to deal with a chain of arrayelem datums. Chase
3960                                  * back to find the base array datum, and save the subscript
3961                                  * expressions as we go.  (We are scanning right to left here,
3962                                  * but want to evaluate the subscripts left-to-right to
3963                                  * minimize surprises.)
3964                                  */
3965                                 nsubscripts = 0;
3966                                 do
3967                                 {
3968                                         PLpgSQL_arrayelem *arrayelem = (PLpgSQL_arrayelem *) target;
3969
3970                                         if (nsubscripts >= MAXDIM)
3971                                                 ereport(ERROR,
3972                                                                 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
3973                                                                  errmsg("number of array dimensions (%d) exceeds the maximum allowed (%d)",
3974                                                                                 nsubscripts + 1, MAXDIM)));
3975                                         subscripts[nsubscripts++] = arrayelem->subscript;
3976                                         target = estate->datums[arrayelem->arrayparentno];
3977                                 } while (target->dtype == PLPGSQL_DTYPE_ARRAYELEM);
3978
3979                                 /* Fetch current value of array datum */
3980                                 exec_eval_datum(estate, target,
3981                                                                 &arraytypeid, &arraytypmod,
3982                                                                 &oldarraydatum, &oldarrayisnull);
3983
3984                                 /* If target is domain over array, reduce to base type */
3985                                 arraytypeid = getBaseTypeAndTypmod(arraytypeid, &arraytypmod);
3986
3987                                 /* ... and identify the element type */
3988                                 arrayelemtypeid = get_element_type(arraytypeid);
3989                                 if (!OidIsValid(arrayelemtypeid))
3990                                         ereport(ERROR,
3991                                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
3992                                                          errmsg("subscripted object is not an array")));
3993
3994                                 get_typlenbyvalalign(arrayelemtypeid,
3995                                                                          &elemtyplen,
3996                                                                          &elemtypbyval,
3997                                                                          &elemtypalign);
3998                                 arraytyplen = get_typlen(arraytypeid);
3999
4000                                 /*
4001                                  * Evaluate the subscripts, switch into left-to-right order.
4002                                  * Like ExecEvalArrayRef(), complain if any subscript is null.
4003                                  */
4004                                 for (i = 0; i < nsubscripts; i++)
4005                                 {
4006                                         bool            subisnull;
4007
4008                                         subscriptvals[i] =
4009                                                 exec_eval_integer(estate,
4010                                                                                   subscripts[nsubscripts - 1 - i],
4011                                                                                   &subisnull);
4012                                         if (subisnull)
4013                                                 ereport(ERROR,
4014                                                                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
4015                                                                  errmsg("array subscript in assignment must not be null")));
4016
4017                                         /*
4018                                          * Clean up in case the subscript expression wasn't simple.
4019                                          * We can't do exec_eval_cleanup, but we can do this much
4020                                          * (which is safe because the integer subscript value is
4021                                          * surely pass-by-value), and we must do it in case the
4022                                          * next subscript expression isn't simple either.
4023                                          */
4024                                         if (estate->eval_tuptable != NULL)
4025                                                 SPI_freetuptable(estate->eval_tuptable);
4026                                         estate->eval_tuptable = NULL;
4027                                 }
4028
4029                                 /* Now we can restore caller's SPI_execute result if any. */
4030                                 Assert(estate->eval_tuptable == NULL);
4031                                 estate->eval_tuptable = save_eval_tuptable;
4032
4033                                 /* Coerce source value to match array element type. */
4034                                 coerced_value = exec_simple_cast_value(value,
4035                                                                                                            valtype,
4036                                                                                                            arrayelemtypeid,
4037                                                                                                            arraytypmod,
4038                                                                                                            *isNull);
4039
4040                                 /*
4041                                  * If the original array is null, cons up an empty array so
4042                                  * that the assignment can proceed; we'll end with a
4043                                  * one-element array containing just the assigned-to
4044                                  * subscript.  This only works for varlena arrays, though; for
4045                                  * fixed-length array types we skip the assignment.  We can't
4046                                  * support assignment of a null entry into a fixed-length
4047                                  * array, either, so that's a no-op too.  This is all ugly but
4048                                  * corresponds to the current behavior of ExecEvalArrayRef().
4049                                  */
4050                                 if (arraytyplen > 0 &&  /* fixed-length array? */
4051                                         (oldarrayisnull || *isNull))
4052                                         return;
4053
4054                                 if (oldarrayisnull)
4055                                         oldarrayval = construct_empty_array(arrayelemtypeid);
4056                                 else
4057                                         oldarrayval = (ArrayType *) DatumGetPointer(oldarraydatum);
4058
4059                                 /*
4060                                  * Build the modified array value.
4061                                  */
4062                                 newarrayval = array_set(oldarrayval,
4063                                                                                 nsubscripts,
4064                                                                                 subscriptvals,
4065                                                                                 coerced_value,
4066                                                                                 *isNull,
4067                                                                                 arraytyplen,
4068                                                                                 elemtyplen,
4069                                                                                 elemtypbyval,
4070                                                                                 elemtypalign);
4071
4072                                 /*
4073                                  * Avoid leaking the result of exec_simple_cast_value, if it
4074                                  * performed a conversion to a pass-by-ref type.
4075                                  */
4076                                 if (!*isNull && coerced_value != value && !elemtypbyval)
4077                                         pfree(DatumGetPointer(coerced_value));
4078
4079                                 /*
4080                                  * Assign the new array to the base variable.  It's never NULL
4081                                  * at this point.  Note that if the target is a domain,
4082                                  * coercing the base array type back up to the domain will
4083                                  * happen within exec_assign_value.
4084                                  */
4085                                 *isNull = false;
4086                                 exec_assign_value(estate, target,
4087                                                                   PointerGetDatum(newarrayval),
4088                                                                   arraytypeid, isNull);
4089
4090                                 /*
4091                                  * Avoid leaking the modified array value, too.
4092                                  */
4093                                 pfree(newarrayval);
4094                                 break;
4095                         }
4096
4097                 default:
4098                         elog(ERROR, "unrecognized dtype: %d", target->dtype);
4099         }
4100 }
4101
4102 /*
4103  * exec_eval_datum                              Get current value of a PLpgSQL_datum
4104  *
4105  * The type oid, typmod, value in Datum format, and null flag are returned.
4106  *
4107  * At present this doesn't handle PLpgSQL_expr or PLpgSQL_arrayelem datums.
4108  *
4109  * NOTE: caller must not modify the returned value, since it points right
4110  * at the stored value in the case of pass-by-reference datatypes.      In some
4111  * cases we have to palloc a return value, and in such cases we put it into
4112  * the estate's short-term memory context.
4113  */
4114 static void
4115 exec_eval_datum(PLpgSQL_execstate *estate,
4116                                 PLpgSQL_datum *datum,
4117                                 Oid *typeid,
4118                                 int32 *typetypmod,
4119                                 Datum *value,
4120                                 bool *isnull)
4121 {
4122         MemoryContext oldcontext;
4123
4124         switch (datum->dtype)
4125         {
4126                 case PLPGSQL_DTYPE_VAR:
4127                         {
4128                                 PLpgSQL_var *var = (PLpgSQL_var *) datum;
4129
4130                                 *typeid = var->datatype->typoid;
4131                                 *typetypmod = var->datatype->atttypmod;
4132                                 *value = var->value;
4133                                 *isnull = var->isnull;
4134                                 break;
4135                         }
4136
4137                 case PLPGSQL_DTYPE_ROW:
4138                         {
4139                                 PLpgSQL_row *row = (PLpgSQL_row *) datum;
4140                                 HeapTuple       tup;
4141
4142                                 if (!row->rowtupdesc)   /* should not happen */
4143                                         elog(ERROR, "row variable has no tupdesc");
4144                                 /* Make sure we have a valid type/typmod setting */
4145                                 BlessTupleDesc(row->rowtupdesc);
4146                                 oldcontext = MemoryContextSwitchTo(estate->eval_econtext->ecxt_per_tuple_memory);
4147                                 tup = make_tuple_from_row(estate, row, row->rowtupdesc);
4148                                 if (tup == NULL)        /* should not happen */
4149                                         elog(ERROR, "row not compatible with its own tupdesc");
4150                                 MemoryContextSwitchTo(oldcontext);
4151                                 *typeid = row->rowtupdesc->tdtypeid;
4152                                 *typetypmod = row->rowtupdesc->tdtypmod;
4153                                 *value = HeapTupleGetDatum(tup);
4154                                 *isnull = false;
4155                                 break;
4156                         }
4157
4158                 case PLPGSQL_DTYPE_REC:
4159                         {
4160                                 PLpgSQL_rec *rec = (PLpgSQL_rec *) datum;
4161                                 HeapTupleData worktup;
4162
4163                                 if (!HeapTupleIsValid(rec->tup))
4164                                         ereport(ERROR,
4165                                                   (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4166                                                    errmsg("record \"%s\" is not assigned yet",
4167                                                                   rec->refname),
4168                                                    errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
4169                                 Assert(rec->tupdesc != NULL);
4170                                 /* Make sure we have a valid type/typmod setting */
4171                                 BlessTupleDesc(rec->tupdesc);
4172
4173                                 /*
4174                                  * In a trigger, the NEW and OLD parameters are likely to be
4175                                  * on-disk tuples that don't have the desired Datum fields.
4176                                  * Copy the tuple body and insert the right values.
4177                                  */
4178                                 oldcontext = MemoryContextSwitchTo(estate->eval_econtext->ecxt_per_tuple_memory);
4179                                 heap_copytuple_with_tuple(rec->tup, &worktup);
4180                                 HeapTupleHeaderSetDatumLength(worktup.t_data, worktup.t_len);
4181                                 HeapTupleHeaderSetTypeId(worktup.t_data, rec->tupdesc->tdtypeid);
4182                                 HeapTupleHeaderSetTypMod(worktup.t_data, rec->tupdesc->tdtypmod);
4183                                 MemoryContextSwitchTo(oldcontext);
4184                                 *typeid = rec->tupdesc->tdtypeid;
4185                                 *typetypmod = rec->tupdesc->tdtypmod;
4186                                 *value = HeapTupleGetDatum(&worktup);
4187                                 *isnull = false;
4188                                 break;
4189                         }
4190
4191                 case PLPGSQL_DTYPE_RECFIELD:
4192                         {
4193                                 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) datum;
4194                                 PLpgSQL_rec *rec;
4195                                 int                     fno;
4196
4197                                 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
4198                                 if (!HeapTupleIsValid(rec->tup))
4199                                         ereport(ERROR,
4200                                                   (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4201                                                    errmsg("record \"%s\" is not assigned yet",
4202                                                                   rec->refname),
4203                                                    errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
4204                                 fno = SPI_fnumber(rec->tupdesc, recfield->fieldname);
4205                                 if (fno == SPI_ERROR_NOATTRIBUTE)
4206                                         ereport(ERROR,
4207                                                         (errcode(ERRCODE_UNDEFINED_COLUMN),
4208                                                          errmsg("record \"%s\" has no field \"%s\"",
4209                                                                         rec->refname, recfield->fieldname)));
4210                                 *typeid = SPI_gettypeid(rec->tupdesc, fno);
4211                                 /* XXX there's no SPI_gettypmod, for some reason */
4212                                 if (fno > 0)
4213                                         *typetypmod = rec->tupdesc->attrs[fno - 1]->atttypmod;
4214                                 else
4215                                         *typetypmod = -1;
4216                                 *value = SPI_getbinval(rec->tup, rec->tupdesc, fno, isnull);
4217                                 break;
4218                         }
4219
4220                 default:
4221                         elog(ERROR, "unrecognized dtype: %d", datum->dtype);
4222         }
4223 }
4224
4225 /*
4226  * exec_get_datum_type                          Get datatype of a PLpgSQL_datum
4227  *
4228  * This is the same logic as in exec_eval_datum, except that it can handle
4229  * some cases where exec_eval_datum has to fail; specifically, we may have
4230  * a tupdesc but no row value for a record variable.  (This currently can
4231  * happen only for a trigger's NEW/OLD records.)
4232  */
4233 Oid
4234 exec_get_datum_type(PLpgSQL_execstate *estate,
4235                                         PLpgSQL_datum *datum)
4236 {
4237         Oid                     typeid;
4238
4239         switch (datum->dtype)
4240         {
4241                 case PLPGSQL_DTYPE_VAR:
4242                         {
4243                                 PLpgSQL_var *var = (PLpgSQL_var *) datum;
4244
4245                                 typeid = var->datatype->typoid;
4246                                 break;
4247                         }
4248
4249                 case PLPGSQL_DTYPE_ROW:
4250                         {
4251                                 PLpgSQL_row *row = (PLpgSQL_row *) datum;
4252
4253                                 if (!row->rowtupdesc)   /* should not happen */
4254                                         elog(ERROR, "row variable has no tupdesc");
4255                                 /* Make sure we have a valid type/typmod setting */
4256                                 BlessTupleDesc(row->rowtupdesc);
4257                                 typeid = row->rowtupdesc->tdtypeid;
4258                                 break;
4259                         }
4260
4261                 case PLPGSQL_DTYPE_REC:
4262                         {
4263                                 PLpgSQL_rec *rec = (PLpgSQL_rec *) datum;
4264
4265                                 if (rec->tupdesc == NULL)
4266                                         ereport(ERROR,
4267                                                   (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4268                                                    errmsg("record \"%s\" is not assigned yet",
4269                                                                   rec->refname),
4270                                                    errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
4271                                 /* Make sure we have a valid type/typmod setting */
4272                                 BlessTupleDesc(rec->tupdesc);
4273                                 typeid = rec->tupdesc->tdtypeid;
4274                                 break;
4275                         }
4276
4277                 case PLPGSQL_DTYPE_RECFIELD:
4278                         {
4279                                 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) datum;
4280                                 PLpgSQL_rec *rec;
4281                                 int                     fno;
4282
4283                                 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
4284                                 if (rec->tupdesc == NULL)
4285                                         ereport(ERROR,
4286                                                   (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4287                                                    errmsg("record \"%s\" is not assigned yet",
4288                                                                   rec->refname),
4289                                                    errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
4290                                 fno = SPI_fnumber(rec->tupdesc, recfield->fieldname);
4291                                 if (fno == SPI_ERROR_NOATTRIBUTE)
4292                                         ereport(ERROR,
4293                                                         (errcode(ERRCODE_UNDEFINED_COLUMN),
4294                                                          errmsg("record \"%s\" has no field \"%s\"",
4295                                                                         rec->refname, recfield->fieldname)));
4296                                 typeid = SPI_gettypeid(rec->tupdesc, fno);
4297                                 break;
4298                         }
4299
4300                 default:
4301                         elog(ERROR, "unrecognized dtype: %d", datum->dtype);
4302                         typeid = InvalidOid;    /* keep compiler quiet */
4303                         break;
4304         }
4305
4306         return typeid;
4307 }
4308
4309 /*
4310  * exec_get_rec_fieldtype                               Get datatype of a PLpgSQL record field
4311  *
4312  * Also returns the field number to *fieldno.
4313  */
4314 Oid
4315 exec_get_rec_fieldtype(PLpgSQL_rec *rec, const char *fieldname,
4316                                            int *fieldno)
4317 {
4318         Oid                     typeid;
4319         int                     fno;
4320
4321         if (rec->tupdesc == NULL)
4322                 ereport(ERROR,
4323                                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4324                                  errmsg("record \"%s\" is not assigned yet",
4325                                                 rec->refname),
4326                                  errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
4327         fno = SPI_fnumber(rec->tupdesc, fieldname);
4328         if (fno == SPI_ERROR_NOATTRIBUTE)
4329                 ereport(ERROR,
4330                                 (errcode(ERRCODE_UNDEFINED_COLUMN),
4331                                  errmsg("record \"%s\" has no field \"%s\"",
4332                                                 rec->refname, fieldname)));
4333         typeid = SPI_gettypeid(rec->tupdesc, fno);
4334
4335         *fieldno = fno;
4336         return typeid;
4337 }
4338
4339 /* ----------
4340  * exec_eval_integer            Evaluate an expression, coerce result to int4
4341  *
4342  * Note we do not do exec_eval_cleanup here; the caller must do it at
4343  * some later point.  (We do this because the caller may be holding the
4344  * results of other, pass-by-reference, expression evaluations, such as
4345  * an array value to be subscripted.  Also see notes in exec_eval_simple_expr
4346  * about allocation of the parameter array.)
4347  * ----------
4348  */
4349 static int
4350 exec_eval_integer(PLpgSQL_execstate *estate,
4351                                   PLpgSQL_expr *expr,
4352                                   bool *isNull)
4353 {
4354         Datum           exprdatum;
4355         Oid                     exprtypeid;
4356
4357         exprdatum = exec_eval_expr(estate, expr, isNull, &exprtypeid);
4358         exprdatum = exec_simple_cast_value(exprdatum, exprtypeid,
4359                                                                            INT4OID, -1,
4360                                                                            *isNull);
4361         return DatumGetInt32(exprdatum);
4362 }
4363
4364 /* ----------
4365  * exec_eval_boolean            Evaluate an expression, coerce result to bool
4366  *
4367  * Note we do not do exec_eval_cleanup here; the caller must do it at
4368  * some later point.
4369  * ----------
4370  */
4371 static bool
4372 exec_eval_boolean(PLpgSQL_execstate *estate,
4373                                   PLpgSQL_expr *expr,
4374                                   bool *isNull)
4375 {
4376         Datum           exprdatum;
4377         Oid                     exprtypeid;
4378
4379         exprdatum = exec_eval_expr(estate, expr, isNull, &exprtypeid);
4380         exprdatum = exec_simple_cast_value(exprdatum, exprtypeid,
4381                                                                            BOOLOID, -1,
4382                                                                            *isNull);
4383         return DatumGetBool(exprdatum);
4384 }
4385
4386 /* ----------
4387  * exec_eval_expr                       Evaluate an expression and return
4388  *                                      the result Datum.
4389  *
4390  * NOTE: caller must do exec_eval_cleanup when done with the Datum.
4391  * ----------
4392  */
4393 static Datum
4394 exec_eval_expr(PLpgSQL_execstate *estate,
4395                            PLpgSQL_expr *expr,
4396                            bool *isNull,
4397                            Oid *rettype)
4398 {
4399         Datum           result = 0;
4400         int                     rc;
4401
4402         /*
4403          * If first time through, create a plan for this expression.
4404          */
4405         if (expr->plan == NULL)
4406                 exec_prepare_plan(estate, expr, 0);
4407
4408         /*
4409          * If this is a simple expression, bypass SPI and use the executor
4410          * directly
4411          */
4412         if (exec_eval_simple_expr(estate, expr, &result, isNull, rettype))
4413                 return result;
4414
4415         /*
4416          * Else do it the hard way via exec_run_select
4417          */
4418         rc = exec_run_select(estate, expr, 2, NULL);
4419         if (rc != SPI_OK_SELECT)
4420                 ereport(ERROR,
4421                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
4422                                  errmsg("query \"%s\" did not return data", expr->query)));
4423
4424         /*
4425          * Check that the expression returns exactly one column...
4426          */
4427         if (estate->eval_tuptable->tupdesc->natts != 1)
4428                 ereport(ERROR,
4429                                 (errcode(ERRCODE_SYNTAX_ERROR),
4430                                  errmsg_plural("query \"%s\" returned %d column",
4431                                                            "query \"%s\" returned %d columns",
4432                                                            estate->eval_tuptable->tupdesc->natts,
4433                                                            expr->query,
4434                                                            estate->eval_tuptable->tupdesc->natts)));
4435
4436         /*
4437          * ... and get the column's datatype.
4438          */
4439         *rettype = SPI_gettypeid(estate->eval_tuptable->tupdesc, 1);
4440
4441         /*
4442          * If there are no rows selected, the result is a NULL of that type.
4443          */
4444         if (estate->eval_processed == 0)
4445         {
4446                 *isNull = true;
4447                 return (Datum) 0;
4448         }
4449
4450         /*
4451          * Check that the expression returned no more than one row.
4452          */
4453         if (estate->eval_processed != 1)
4454                 ereport(ERROR,
4455                                 (errcode(ERRCODE_CARDINALITY_VIOLATION),
4456                                  errmsg("query \"%s\" returned more than one row",
4457                                                 expr->query)));
4458
4459         /*
4460          * Return the single result Datum.
4461          */
4462         return SPI_getbinval(estate->eval_tuptable->vals[0],
4463                                                  estate->eval_tuptable->tupdesc, 1, isNull);
4464 }
4465
4466
4467 /* ----------
4468  * exec_run_select                      Execute a select query
4469  * ----------
4470  */
4471 static int
4472 exec_run_select(PLpgSQL_execstate *estate,
4473                                 PLpgSQL_expr *expr, long maxtuples, Portal *portalP)
4474 {
4475         ParamListInfo paramLI;
4476         int                     rc;
4477
4478         /*
4479          * On the first call for this expression generate the plan
4480          */
4481         if (expr->plan == NULL)
4482                 exec_prepare_plan(estate, expr, 0);
4483
4484         /*
4485          * Set up ParamListInfo (note this is only carrying a hook function, not
4486          * any actual data values, at this point)
4487          */
4488         paramLI = setup_param_list(estate, expr);
4489
4490         /*
4491          * If a portal was requested, put the query into the portal
4492          */
4493         if (portalP != NULL)
4494         {
4495                 *portalP = SPI_cursor_open_with_paramlist(NULL, expr->plan,
4496                                                                                                   paramLI,
4497                                                                                                   estate->readonly_func);
4498                 if (*portalP == NULL)
4499                         elog(ERROR, "could not open implicit cursor for query \"%s\": %s",
4500                                  expr->query, SPI_result_code_string(SPI_result));
4501                 if (paramLI)
4502                         pfree(paramLI);
4503                 return SPI_OK_CURSOR;
4504         }
4505
4506         /*
4507          * Execute the query
4508          */
4509         rc = SPI_execute_plan_with_paramlist(expr->plan, paramLI,
4510                                                                                  estate->readonly_func, maxtuples);
4511         if (rc != SPI_OK_SELECT)
4512                 ereport(ERROR,
4513                                 (errcode(ERRCODE_SYNTAX_ERROR),
4514                                  errmsg("query \"%s\" is not a SELECT", expr->query)));
4515
4516         /* Save query results for eventual cleanup */
4517         Assert(estate->eval_tuptable == NULL);
4518         estate->eval_tuptable = SPI_tuptable;
4519         estate->eval_processed = SPI_processed;
4520         estate->eval_lastoid = SPI_lastoid;
4521
4522         if (paramLI)
4523                 pfree(paramLI);
4524
4525         return rc;
4526 }
4527
4528
4529 /*
4530  * exec_for_query --- execute body of FOR loop for each row from a portal
4531  *
4532  * Used by exec_stmt_fors, exec_stmt_forc and exec_stmt_dynfors
4533  */
4534 static int
4535 exec_for_query(PLpgSQL_execstate *estate, PLpgSQL_stmt_forq *stmt,
4536                            Portal portal, bool prefetch_ok)
4537 {
4538         PLpgSQL_rec *rec = NULL;
4539         PLpgSQL_row *row = NULL;
4540         SPITupleTable *tuptab;
4541         bool            found = false;
4542         int                     rc = PLPGSQL_RC_OK;
4543         int                     n;
4544
4545         /*
4546          * Determine if we assign to a record or a row
4547          */
4548         if (stmt->rec != NULL)
4549                 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->dno]);
4550         else if (stmt->row != NULL)
4551                 row = (PLpgSQL_row *) (estate->datums[stmt->row->dno]);
4552         else
4553                 elog(ERROR, "unsupported target");
4554
4555         /*
4556          * Make sure the portal doesn't get closed by the user statements we
4557          * execute.
4558          */
4559         PinPortal(portal);
4560
4561         /*
4562          * Fetch the initial tuple(s).  If prefetching is allowed then we grab a
4563          * few more rows to avoid multiple trips through executor startup
4564          * overhead.
4565          */
4566         SPI_cursor_fetch(portal, true, prefetch_ok ? 10 : 1);
4567         tuptab = SPI_tuptable;
4568         n = SPI_processed;
4569
4570         /*
4571          * If the query didn't return any rows, set the target to NULL and fall
4572          * through with found = false.
4573          */
4574         if (n <= 0)
4575                 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
4576         else
4577                 found = true;                   /* processed at least one tuple */
4578
4579         /*
4580          * Now do the loop
4581          */
4582         while (n > 0)
4583         {
4584                 int                     i;
4585
4586                 for (i = 0; i < n; i++)
4587                 {
4588                         /*
4589                          * Assign the tuple to the target
4590                          */
4591                         exec_move_row(estate, rec, row, tuptab->vals[i], tuptab->tupdesc);
4592
4593                         /*
4594                          * Execute the statements
4595                          */
4596                         rc = exec_stmts(estate, stmt->body);
4597
4598                         if (rc != PLPGSQL_RC_OK)
4599                         {
4600                                 if (rc == PLPGSQL_RC_EXIT)
4601                                 {
4602                                         if (estate->exitlabel == NULL)
4603                                         {
4604                                                 /* unlabelled exit, so exit the current loop */
4605                                                 rc = PLPGSQL_RC_OK;
4606                                         }
4607                                         else if (stmt->label != NULL &&
4608                                                          strcmp(stmt->label, estate->exitlabel) == 0)
4609                                         {
4610                                                 /* label matches this loop, so exit loop */
4611                                                 estate->exitlabel = NULL;
4612                                                 rc = PLPGSQL_RC_OK;
4613                                         }
4614
4615                                         /*
4616                                          * otherwise, we processed a labelled exit that does not
4617                                          * match the current statement's label, if any; return
4618                                          * RC_EXIT so that the EXIT continues to recurse upward.
4619                                          */
4620                                 }
4621                                 else if (rc == PLPGSQL_RC_CONTINUE)
4622                                 {
4623                                         if (estate->exitlabel == NULL)
4624                                         {
4625                                                 /* unlabelled continue, so re-run the current loop */
4626                                                 rc = PLPGSQL_RC_OK;
4627                                                 continue;
4628                                         }
4629                                         else if (stmt->label != NULL &&
4630                                                          strcmp(stmt->label, estate->exitlabel) == 0)
4631                                         {
4632                                                 /* label matches this loop, so re-run loop */
4633                                                 estate->exitlabel = NULL;
4634                                                 rc = PLPGSQL_RC_OK;
4635                                                 continue;
4636                                         }
4637
4638                                         /*
4639                                          * otherwise, we process a labelled continue that does not
4640                                          * match the current statement's label, if any; return
4641                                          * RC_CONTINUE so that the CONTINUE will propagate up the
4642                                          * stack.
4643                                          */
4644                                 }
4645
4646                                 /*
4647                                  * We're aborting the loop.  Need a goto to get out of two
4648                                  * levels of loop...
4649                                  */
4650                                 goto loop_exit;
4651                         }
4652                 }
4653
4654                 SPI_freetuptable(tuptab);
4655
4656                 /*
4657                  * Fetch more tuples.  If prefetching is allowed, grab 50 at a time.
4658                  */
4659                 SPI_cursor_fetch(portal, true, prefetch_ok ? 50 : 1);
4660                 tuptab = SPI_tuptable;
4661                 n = SPI_processed;
4662         }
4663
4664 loop_exit:
4665
4666         /*
4667          * Release last group of tuples (if any)
4668          */
4669         SPI_freetuptable(tuptab);
4670
4671         UnpinPortal(portal);
4672
4673         /*
4674          * Set the FOUND variable to indicate the result of executing the loop
4675          * (namely, whether we looped one or more times). This must be set last so
4676          * that it does not interfere with the value of the FOUND variable inside
4677          * the loop processing itself.
4678          */
4679         exec_set_found(estate, found);
4680
4681         return rc;
4682 }
4683
4684
4685 /* ----------
4686  * exec_eval_simple_expr -              Evaluate a simple expression returning
4687  *                                                              a Datum by directly calling ExecEvalExpr().
4688  *
4689  * If successful, store results into *result, *isNull, *rettype and return
4690  * TRUE.  If the expression cannot be handled by simple evaluation,
4691  * return FALSE.
4692  *
4693  * Because we only store one execution tree for a simple expression, we
4694  * can't handle recursion cases.  So, if we see the tree is already busy
4695  * with an evaluation in the current xact, we just return FALSE and let the
4696  * caller run the expression the hard way.  (Other alternatives such as
4697  * creating a new tree for a recursive call either introduce memory leaks,
4698  * or add enough bookkeeping to be doubtful wins anyway.)  Another case that
4699  * is covered by the expr_simple_in_use test is where a previous execution
4700  * of the tree was aborted by an error: the tree may contain bogus state
4701  * so we dare not re-use it.
4702  *
4703  * It is possible though unlikely for a simple expression to become non-simple
4704  * (consider for example redefining a trivial view).  We must handle that for
4705  * correctness; fortunately it's normally inexpensive to do
4706  * RevalidateCachedPlan on a simple expression.  We do not consider the other
4707  * direction (non-simple expression becoming simple) because we'll still give
4708  * correct results if that happens, and it's unlikely to be worth the cycles
4709  * to check.
4710  *
4711  * Note: if pass-by-reference, the result is in the eval_econtext's
4712  * temporary memory context.  It will be freed when exec_eval_cleanup
4713  * is done.
4714  * ----------
4715  */
4716 static bool
4717 exec_eval_simple_expr(PLpgSQL_execstate *estate,
4718                                           PLpgSQL_expr *expr,
4719                                           Datum *result,
4720                                           bool *isNull,
4721                                           Oid *rettype)
4722 {
4723         ExprContext *econtext = estate->eval_econtext;
4724         LocalTransactionId curlxid = MyProc->lxid;
4725         CachedPlanSource *plansource;
4726         CachedPlan *cplan;
4727         ParamListInfo paramLI;
4728         PLpgSQL_expr *save_cur_expr;
4729         MemoryContext oldcontext;
4730
4731         /*
4732          * Forget it if expression wasn't simple before.
4733          */
4734         if (expr->expr_simple_expr == NULL)
4735                 return false;
4736
4737         /*
4738          * If expression is in use in current xact, don't touch it.
4739          */
4740         if (expr->expr_simple_in_use && expr->expr_simple_lxid == curlxid)
4741                 return false;
4742
4743         /*
4744          * Revalidate cached plan, so that we will notice if it became stale. (We
4745          * also need to hold a refcount while using the plan.)  Note that even if
4746          * replanning occurs, the length of plancache_list can't change, since it
4747          * is a property of the raw parsetree generated from the query text.
4748          */
4749         Assert(list_length(expr->plan->plancache_list) == 1);
4750         plansource = (CachedPlanSource *) linitial(expr->plan->plancache_list);
4751         cplan = RevalidateCachedPlan(plansource, true);
4752         if (cplan->generation != expr->expr_simple_generation)
4753         {
4754                 /* It got replanned ... is it still simple? */
4755                 exec_simple_check_plan(expr);
4756                 if (expr->expr_simple_expr == NULL)
4757                 {
4758                         /* Ooops, release refcount and fail */
4759                         ReleaseCachedPlan(cplan, true);
4760                         return false;
4761                 }
4762         }
4763
4764         /*
4765          * Pass back previously-determined result type.
4766          */
4767         *rettype = expr->expr_simple_type;
4768
4769         /*
4770          * Prepare the expression for execution, if it's not been done already in
4771          * the current transaction.  (This will be forced to happen if we called
4772          * exec_simple_check_plan above.)
4773          */
4774         if (expr->expr_simple_lxid != curlxid)
4775         {
4776                 oldcontext = MemoryContextSwitchTo(simple_eval_estate->es_query_cxt);
4777                 expr->expr_simple_state = ExecInitExpr(expr->expr_simple_expr, NULL);
4778                 expr->expr_simple_in_use = false;
4779                 expr->expr_simple_lxid = curlxid;
4780                 MemoryContextSwitchTo(oldcontext);
4781         }
4782
4783         /*
4784          * We have to do some of the things SPI_execute_plan would do, in
4785          * particular advance the snapshot if we are in a non-read-only function.
4786          * Without this, stable functions within the expression would fail to see
4787          * updates made so far by our own function.
4788          */
4789         SPI_push();
4790
4791         oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
4792         if (!estate->readonly_func)
4793         {
4794                 CommandCounterIncrement();
4795                 PushActiveSnapshot(GetTransactionSnapshot());
4796         }
4797
4798         /*
4799          * Create the param list in econtext's temporary memory context. We won't
4800          * need to free it explicitly, since it will go away at the next reset of
4801          * that context.
4802          *
4803          * XXX think about avoiding repeated palloc's for param lists?  It should
4804          * be possible --- this routine isn't re-entrant anymore.
4805          *
4806          * Just for paranoia's sake, save and restore the prior value of
4807          * estate->cur_expr, which setup_param_list() sets.
4808          */
4809         save_cur_expr = estate->cur_expr;
4810
4811         paramLI = setup_param_list(estate, expr);
4812         econtext->ecxt_param_list_info = paramLI;
4813
4814         /*
4815          * Mark expression as busy for the duration of the ExecEvalExpr call.
4816          */
4817         expr->expr_simple_in_use = true;
4818
4819         /*
4820          * Finally we can call the executor to evaluate the expression
4821          */
4822         *result = ExecEvalExpr(expr->expr_simple_state,
4823                                                    econtext,
4824                                                    isNull,
4825                                                    NULL);
4826
4827         /* Assorted cleanup */
4828         expr->expr_simple_in_use = false;
4829
4830         estate->cur_expr = save_cur_expr;
4831
4832         if (!estate->readonly_func)
4833                 PopActiveSnapshot();
4834
4835         MemoryContextSwitchTo(oldcontext);
4836
4837         SPI_pop();
4838
4839         /*
4840          * Now we can release our refcount on the cached plan.
4841          */
4842         ReleaseCachedPlan(cplan, true);
4843
4844         /*
4845          * That's it.
4846          */
4847         return true;
4848 }
4849
4850
4851 /*
4852  * Create a ParamListInfo to pass to SPI
4853  *
4854  * The ParamListInfo array is initially all zeroes, in particular the
4855  * ptype values are all InvalidOid.  This causes the executor to call the
4856  * paramFetch hook each time it wants a value.  We thus evaluate only the
4857  * parameters actually demanded.
4858  *
4859  * The result is a locally palloc'd array that should be pfree'd after use;
4860  * but note it can be NULL.
4861  */
4862 static ParamListInfo
4863 setup_param_list(PLpgSQL_execstate *estate, PLpgSQL_expr *expr)
4864 {
4865         ParamListInfo paramLI;
4866
4867         /*
4868          * Could we re-use these arrays instead of palloc'ing a new one each time?
4869          * However, we'd have to zero the array each time anyway, since new values
4870          * might have been assigned to the variables.
4871          */
4872         if (estate->ndatums > 0)
4873         {
4874                 /* sizeof(ParamListInfoData) includes the first array element */
4875                 paramLI = (ParamListInfo)
4876                         palloc0(sizeof(ParamListInfoData) +
4877                                         (estate->ndatums - 1) *sizeof(ParamExternData));
4878                 paramLI->paramFetch = plpgsql_param_fetch;
4879                 paramLI->paramFetchArg = (void *) estate;
4880                 paramLI->parserSetup = (ParserSetupHook) plpgsql_parser_setup;
4881                 paramLI->parserSetupArg = (void *) expr;
4882                 paramLI->numParams = estate->ndatums;
4883
4884                 /*
4885                  * Set up link to active expr where the hook functions can find it.
4886                  * Callers must save and restore cur_expr if there is any chance that
4887                  * they are interrupting an active use of parameters.
4888                  */
4889                 estate->cur_expr = expr;
4890
4891                 /*
4892                  * Also make sure this is set before parser hooks need it.      There is
4893                  * no need to save and restore, since the value is always correct once
4894                  * set.
4895                  */
4896                 expr->func = estate->func;
4897         }
4898         else
4899                 paramLI = NULL;
4900         return paramLI;
4901 }
4902
4903 /*
4904  * plpgsql_param_fetch          paramFetch callback for dynamic parameter fetch
4905  */
4906 static void
4907 plpgsql_param_fetch(ParamListInfo params, int paramid)
4908 {
4909         int                     dno;
4910         PLpgSQL_execstate *estate;
4911         PLpgSQL_expr *expr;
4912         PLpgSQL_datum *datum;
4913         ParamExternData *prm;
4914         int32           prmtypmod;
4915
4916         /* paramid's are 1-based, but dnos are 0-based */
4917         dno = paramid - 1;
4918         Assert(dno >= 0 && dno < params->numParams);
4919
4920         /* fetch back the hook data */
4921         estate = (PLpgSQL_execstate *) params->paramFetchArg;
4922         expr = estate->cur_expr;
4923         Assert(params->numParams == estate->ndatums);
4924
4925         /*
4926          * Do nothing if asked for a value that's not supposed to be used by this
4927          * SQL expression.      This avoids unwanted evaluations when functions such
4928          * as copyParamList try to materialize all the values.
4929          */
4930         if (!bms_is_member(dno, expr->paramnos))
4931                 return;
4932
4933         /* OK, evaluate the value and store into the appropriate paramlist slot */
4934         datum = estate->datums[dno];
4935         prm = &params->params[dno];
4936         exec_eval_datum(estate, datum,
4937                                         &prm->ptype, &prmtypmod,
4938                                         &prm->value, &prm->isnull);
4939 }
4940
4941
4942 /* ----------
4943  * exec_move_row                        Move one tuple's values into a record or row
4944  * ----------
4945  */
4946 static void
4947 exec_move_row(PLpgSQL_execstate *estate,
4948                           PLpgSQL_rec *rec,
4949                           PLpgSQL_row *row,
4950                           HeapTuple tup, TupleDesc tupdesc)
4951 {
4952         /*
4953          * Record is simple - just copy the tuple and its descriptor into the
4954          * record variable
4955          */
4956         if (rec != NULL)
4957         {
4958                 /*
4959                  * Copy input first, just in case it is pointing at variable's value
4960                  */
4961                 if (HeapTupleIsValid(tup))
4962                         tup = heap_copytuple(tup);
4963                 else if (tupdesc)
4964                 {
4965                         /* If we have a tupdesc but no data, form an all-nulls tuple */
4966                         bool       *nulls;
4967
4968                         nulls = (bool *) palloc(tupdesc->natts * sizeof(bool));
4969                         memset(nulls, true, tupdesc->natts * sizeof(bool));
4970
4971                         tup = heap_form_tuple(tupdesc, NULL, nulls);
4972
4973                         pfree(nulls);
4974                 }
4975
4976                 if (tupdesc)
4977                         tupdesc = CreateTupleDescCopy(tupdesc);
4978
4979                 /* Free the old value ... */
4980                 if (rec->freetup)
4981                 {
4982                         heap_freetuple(rec->tup);
4983                         rec->freetup = false;
4984                 }
4985                 if (rec->freetupdesc)
4986                 {
4987                         FreeTupleDesc(rec->tupdesc);
4988                         rec->freetupdesc = false;
4989                 }
4990
4991                 /* ... and install the new */
4992                 if (HeapTupleIsValid(tup))
4993                 {
4994                         rec->tup = tup;
4995                         rec->freetup = true;
4996                 }
4997                 else
4998                         rec->tup = NULL;
4999
5000                 if (tupdesc)
5001                 {
5002                         rec->tupdesc = tupdesc;
5003                         rec->freetupdesc = true;
5004                 }
5005                 else
5006                         rec->tupdesc = NULL;
5007
5008                 return;
5009         }
5010
5011         /*
5012          * Row is a bit more complicated in that we assign the individual
5013          * attributes of the tuple to the variables the row points to.
5014          *
5015          * NOTE: this code used to demand row->nfields ==
5016          * HeapTupleHeaderGetNatts(tup->t_data), but that's wrong.  The tuple
5017          * might have more fields than we expected if it's from an
5018          * inheritance-child table of the current table, or it might have fewer if
5019          * the table has had columns added by ALTER TABLE. Ignore extra columns
5020          * and assume NULL for missing columns, the same as heap_getattr would do.
5021          * We also have to skip over dropped columns in either the source or
5022          * destination.
5023          *
5024          * If we have no tuple data at all, we'll assign NULL to all columns of
5025          * the row variable.
5026          */
5027         if (row != NULL)
5028         {
5029                 int                     td_natts = tupdesc ? tupdesc->natts : 0;
5030                 int                     t_natts;
5031                 int                     fnum;
5032                 int                     anum;
5033
5034                 if (HeapTupleIsValid(tup))
5035                         t_natts = HeapTupleHeaderGetNatts(tup->t_data);
5036                 else
5037                         t_natts = 0;
5038
5039                 anum = 0;
5040                 for (fnum = 0; fnum < row->nfields; fnum++)
5041                 {
5042                         PLpgSQL_var *var;
5043                         Datum           value;
5044                         bool            isnull;
5045                         Oid                     valtype;
5046
5047                         if (row->varnos[fnum] < 0)
5048                                 continue;               /* skip dropped column in row struct */
5049
5050                         var = (PLpgSQL_var *) (estate->datums[row->varnos[fnum]]);
5051
5052                         while (anum < td_natts && tupdesc->attrs[anum]->attisdropped)
5053                                 anum++;                 /* skip dropped column in tuple */
5054
5055                         if (anum < td_natts)
5056                         {
5057                                 if (anum < t_natts)
5058                                         value = SPI_getbinval(tup, tupdesc, anum + 1, &isnull);
5059                                 else
5060                                 {
5061                                         value = (Datum) 0;
5062                                         isnull = true;
5063                                 }
5064                                 valtype = SPI_gettypeid(tupdesc, anum + 1);
5065                                 anum++;
5066                         }
5067                         else
5068                         {
5069                                 value = (Datum) 0;
5070                                 isnull = true;
5071
5072                                 /*
5073                                  * InvalidOid is OK because exec_assign_value doesn't care
5074                                  * about the type of a source NULL
5075                                  */
5076                                 valtype = InvalidOid;
5077                         }
5078
5079                         exec_assign_value(estate, (PLpgSQL_datum *) var,
5080                                                           value, valtype, &isnull);
5081                 }
5082
5083                 return;
5084         }
5085
5086         elog(ERROR, "unsupported target");
5087 }
5088
5089 /* ----------
5090  * make_tuple_from_row          Make a tuple from the values of a row object
5091  *
5092  * A NULL return indicates rowtype mismatch; caller must raise suitable error
5093  * ----------
5094  */
5095 static HeapTuple
5096 make_tuple_from_row(PLpgSQL_execstate *estate,
5097                                         PLpgSQL_row *row,
5098                                         TupleDesc tupdesc)
5099 {
5100         int                     natts = tupdesc->natts;
5101         HeapTuple       tuple;
5102         Datum      *dvalues;
5103         bool       *nulls;
5104         int                     i;
5105
5106         if (natts != row->nfields)
5107                 return NULL;
5108
5109         dvalues = (Datum *) palloc0(natts * sizeof(Datum));
5110         nulls = (bool *) palloc(natts * sizeof(bool));
5111
5112         for (i = 0; i < natts; i++)
5113         {
5114                 Oid                     fieldtypeid;
5115                 int32           fieldtypmod;
5116
5117                 if (tupdesc->attrs[i]->attisdropped)
5118                 {
5119                         nulls[i] = true;        /* leave the column as null */
5120                         continue;
5121                 }
5122                 if (row->varnos[i] < 0) /* should not happen */
5123                         elog(ERROR, "dropped rowtype entry for non-dropped column");
5124
5125                 exec_eval_datum(estate, estate->datums[row->varnos[i]],
5126                                                 &fieldtypeid, &fieldtypmod,
5127                                                 &dvalues[i], &nulls[i]);
5128                 if (fieldtypeid != tupdesc->attrs[i]->atttypid)
5129                         return NULL;
5130                 /* XXX should we insist on typmod match, too? */
5131         }
5132
5133         tuple = heap_form_tuple(tupdesc, dvalues, nulls);
5134
5135         pfree(dvalues);
5136         pfree(nulls);
5137
5138         return tuple;
5139 }
5140
5141 /* ----------
5142  * convert_value_to_string                      Convert a non-null Datum to C string
5143  *
5144  * Note: callers generally assume that the result is a palloc'd string and
5145  * should be pfree'd.  This is not all that safe an assumption ...
5146  *
5147  * Note: not caching the conversion function lookup is bad for performance.
5148  * ----------
5149  */
5150 static char *
5151 convert_value_to_string(Datum value, Oid valtype)
5152 {
5153         Oid                     typoutput;
5154         bool            typIsVarlena;
5155
5156         getTypeOutputInfo(valtype, &typoutput, &typIsVarlena);
5157         return OidOutputFunctionCall(typoutput, value);
5158 }
5159
5160 /* ----------
5161  * exec_cast_value                      Cast a value if required
5162  * ----------
5163  */
5164 static Datum
5165 exec_cast_value(Datum value, Oid valtype,
5166                                 Oid reqtype,
5167                                 FmgrInfo *reqinput,
5168                                 Oid reqtypioparam,
5169                                 int32 reqtypmod,
5170                                 bool isnull)
5171 {
5172         /*
5173          * If the type of the queries return value isn't that of the variable,
5174          * convert it.
5175          */
5176         if (valtype != reqtype || reqtypmod != -1)
5177         {
5178                 if (!isnull)
5179                 {
5180                         char       *extval;
5181
5182                         extval = convert_value_to_string(value, valtype);
5183                         value = InputFunctionCall(reqinput, extval,
5184                                                                           reqtypioparam, reqtypmod);
5185                         pfree(extval);
5186                 }
5187                 else
5188                 {
5189                         value = InputFunctionCall(reqinput, NULL,
5190                                                                           reqtypioparam, reqtypmod);
5191                 }
5192         }
5193
5194         return value;
5195 }
5196
5197 /* ----------
5198  * exec_simple_cast_value                       Cast a value if required
5199  *
5200  * As above, but need not supply details about target type.  Note that this
5201  * is slower than exec_cast_value with cached type info, and so should be
5202  * avoided in heavily used code paths.
5203  * ----------
5204  */
5205 static Datum
5206 exec_simple_cast_value(Datum value, Oid valtype,
5207                                            Oid reqtype, int32 reqtypmod,
5208                                            bool isnull)
5209 {
5210         if (valtype != reqtype || reqtypmod != -1)
5211         {
5212                 Oid                     typinput;
5213                 Oid                     typioparam;
5214                 FmgrInfo        finfo_input;
5215
5216                 getTypeInputInfo(reqtype, &typinput, &typioparam);
5217
5218                 fmgr_info(typinput, &finfo_input);
5219
5220                 value = exec_cast_value(value,
5221                                                                 valtype,
5222                                                                 reqtype,
5223                                                                 &finfo_input,
5224                                                                 typioparam,
5225                                                                 reqtypmod,
5226                                                                 isnull);
5227         }
5228
5229         return value;
5230 }
5231
5232
5233 /* ----------
5234  * exec_simple_check_node -             Recursively check if an expression
5235  *                                                              is made only of simple things we can
5236  *                                                              hand out directly to ExecEvalExpr()
5237  *                                                              instead of calling SPI.
5238  * ----------
5239  */
5240 static bool
5241 exec_simple_check_node(Node *node)
5242 {
5243         if (node == NULL)
5244                 return TRUE;
5245
5246         switch (nodeTag(node))
5247         {
5248                 case T_Const:
5249                         return TRUE;
5250
5251                 case T_Param:
5252                         return TRUE;
5253
5254                 case T_ArrayRef:
5255                         {
5256                                 ArrayRef   *expr = (ArrayRef *) node;
5257
5258                                 if (!exec_simple_check_node((Node *) expr->refupperindexpr))
5259                                         return FALSE;
5260                                 if (!exec_simple_check_node((Node *) expr->reflowerindexpr))
5261                                         return FALSE;
5262                                 if (!exec_simple_check_node((Node *) expr->refexpr))
5263                                         return FALSE;
5264                                 if (!exec_simple_check_node((Node *) expr->refassgnexpr))
5265                                         return FALSE;
5266
5267                                 return TRUE;
5268                         }
5269
5270                 case T_FuncExpr:
5271                         {
5272                                 FuncExpr   *expr = (FuncExpr *) node;
5273
5274                                 if (expr->funcretset)
5275                                         return FALSE;
5276                                 if (!exec_simple_check_node((Node *) expr->args))
5277                                         return FALSE;
5278
5279                                 return TRUE;
5280                         }
5281
5282                 case T_OpExpr:
5283                         {
5284                                 OpExpr     *expr = (OpExpr *) node;
5285
5286                                 if (expr->opretset)
5287                                         return FALSE;
5288                                 if (!exec_simple_check_node((Node *) expr->args))
5289                                         return FALSE;
5290
5291                                 return TRUE;
5292                         }
5293
5294                 case T_DistinctExpr:
5295                         {
5296                                 DistinctExpr *expr = (DistinctExpr *) node;
5297
5298                                 if (expr->opretset)
5299                                         return FALSE;
5300                                 if (!exec_simple_check_node((Node *) expr->args))
5301                                         return FALSE;
5302
5303                                 return TRUE;
5304                         }
5305
5306                 case T_ScalarArrayOpExpr:
5307                         {
5308                                 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
5309
5310                                 if (!exec_simple_check_node((Node *) expr->args))
5311                                         return FALSE;
5312
5313                                 return TRUE;
5314                         }
5315
5316                 case T_BoolExpr:
5317                         {
5318                                 BoolExpr   *expr = (BoolExpr *) node;
5319
5320                                 if (!exec_simple_check_node((Node *) expr->args))
5321                                         return FALSE;
5322
5323                                 return TRUE;
5324                         }
5325
5326                 case T_FieldSelect:
5327                         return exec_simple_check_node((Node *) ((FieldSelect *) node)->arg);
5328
5329                 case T_FieldStore:
5330                         {
5331                                 FieldStore *expr = (FieldStore *) node;
5332
5333                                 if (!exec_simple_check_node((Node *) expr->arg))
5334                                         return FALSE;
5335                                 if (!exec_simple_check_node((Node *) expr->newvals))
5336                                         return FALSE;
5337
5338                                 return TRUE;
5339                         }
5340
5341                 case T_RelabelType:
5342                         return exec_simple_check_node((Node *) ((RelabelType *) node)->arg);
5343
5344                 case T_CoerceViaIO:
5345                         return exec_simple_check_node((Node *) ((CoerceViaIO *) node)->arg);
5346
5347                 case T_ArrayCoerceExpr:
5348                         return exec_simple_check_node((Node *) ((ArrayCoerceExpr *) node)->arg);
5349
5350                 case T_ConvertRowtypeExpr:
5351                         return exec_simple_check_node((Node *) ((ConvertRowtypeExpr *) node)->arg);
5352
5353                 case T_CollateExpr:
5354                         return exec_simple_check_node((Node *) ((CollateExpr *) node)->arg);
5355
5356                 case T_CaseExpr:
5357                         {
5358                                 CaseExpr   *expr = (CaseExpr *) node;
5359
5360                                 if (!exec_simple_check_node((Node *) expr->arg))
5361                                         return FALSE;
5362                                 if (!exec_simple_check_node((Node *) expr->args))
5363                                         return FALSE;
5364                                 if (!exec_simple_check_node((Node *) expr->defresult))
5365                                         return FALSE;
5366
5367                                 return TRUE;
5368                         }
5369
5370                 case T_CaseWhen:
5371                         {
5372                                 CaseWhen   *when = (CaseWhen *) node;
5373
5374                                 if (!exec_simple_check_node((Node *) when->expr))
5375                                         return FALSE;
5376                                 if (!exec_simple_check_node((Node *) when->result))
5377                                         return FALSE;
5378
5379                                 return TRUE;
5380                         }
5381
5382                 case T_CaseTestExpr:
5383                         return TRUE;
5384
5385                 case T_ArrayExpr:
5386                         {
5387                                 ArrayExpr  *expr = (ArrayExpr *) node;
5388
5389                                 if (!exec_simple_check_node((Node *) expr->elements))
5390                                         return FALSE;
5391
5392                                 return TRUE;
5393                         }
5394
5395                 case T_RowExpr:
5396                         {
5397                                 RowExpr    *expr = (RowExpr *) node;
5398
5399                                 if (!exec_simple_check_node((Node *) expr->args))
5400                                         return FALSE;
5401
5402                                 return TRUE;
5403                         }
5404
5405                 case T_RowCompareExpr:
5406                         {
5407                                 RowCompareExpr *expr = (RowCompareExpr *) node;
5408
5409                                 if (!exec_simple_check_node((Node *) expr->largs))
5410                                         return FALSE;
5411                                 if (!exec_simple_check_node((Node *) expr->rargs))
5412                                         return FALSE;
5413
5414                                 return TRUE;
5415                         }
5416
5417                 case T_CoalesceExpr:
5418                         {
5419                                 CoalesceExpr *expr = (CoalesceExpr *) node;
5420
5421                                 if (!exec_simple_check_node((Node *) expr->args))
5422                                         return FALSE;
5423
5424                                 return TRUE;
5425                         }
5426
5427                 case T_MinMaxExpr:
5428                         {
5429                                 MinMaxExpr *expr = (MinMaxExpr *) node;
5430
5431                                 if (!exec_simple_check_node((Node *) expr->args))
5432                                         return FALSE;
5433
5434                                 return TRUE;
5435                         }
5436
5437                 case T_XmlExpr:
5438                         {
5439                                 XmlExpr    *expr = (XmlExpr *) node;
5440
5441                                 if (!exec_simple_check_node((Node *) expr->named_args))
5442                                         return FALSE;
5443                                 if (!exec_simple_check_node((Node *) expr->args))
5444                                         return FALSE;
5445
5446                                 return TRUE;
5447                         }
5448
5449                 case T_NullIfExpr:
5450                         {
5451                                 NullIfExpr *expr = (NullIfExpr *) node;
5452
5453                                 if (expr->opretset)
5454                                         return FALSE;
5455                                 if (!exec_simple_check_node((Node *) expr->args))
5456                                         return FALSE;
5457
5458                                 return TRUE;
5459                         }
5460
5461                 case T_NullTest:
5462                         return exec_simple_check_node((Node *) ((NullTest *) node)->arg);
5463
5464                 case T_BooleanTest:
5465                         return exec_simple_check_node((Node *) ((BooleanTest *) node)->arg);
5466
5467                 case T_CoerceToDomain:
5468                         return exec_simple_check_node((Node *) ((CoerceToDomain *) node)->arg);
5469
5470                 case T_CoerceToDomainValue:
5471                         return TRUE;
5472
5473                 case T_List:
5474                         {
5475                                 List       *expr = (List *) node;
5476                                 ListCell   *l;
5477
5478                                 foreach(l, expr)
5479                                 {
5480                                         if (!exec_simple_check_node(lfirst(l)))
5481                                                 return FALSE;
5482                                 }
5483
5484                                 return TRUE;
5485                         }
5486
5487                 default:
5488                         return FALSE;
5489         }
5490 }
5491
5492
5493 /* ----------
5494  * exec_simple_check_plan -             Check if a plan is simple enough to
5495  *                                                              be evaluated by ExecEvalExpr() instead
5496  *                                                              of SPI.
5497  * ----------
5498  */
5499 static void
5500 exec_simple_check_plan(PLpgSQL_expr *expr)
5501 {
5502         CachedPlanSource *plansource;
5503         PlannedStmt *stmt;
5504         Plan       *plan;
5505         TargetEntry *tle;
5506
5507         /*
5508          * Initialize to "not simple", and remember the plan generation number we
5509          * last checked.  (If the query produces more or less than one parsetree
5510          * we just leave expr_simple_generation set to 0.)
5511          */
5512         expr->expr_simple_expr = NULL;
5513         expr->expr_simple_generation = 0;
5514
5515         /*
5516          * 1. We can only evaluate queries that resulted in one single execution
5517          * plan
5518          */
5519         if (list_length(expr->plan->plancache_list) != 1)
5520                 return;
5521         plansource = (CachedPlanSource *) linitial(expr->plan->plancache_list);
5522         expr->expr_simple_generation = plansource->generation;
5523         if (list_length(plansource->plan->stmt_list) != 1)
5524                 return;
5525
5526         stmt = (PlannedStmt *) linitial(plansource->plan->stmt_list);
5527
5528         /*
5529          * 2. It must be a RESULT plan --> no scan's required
5530          */
5531         if (!IsA(stmt, PlannedStmt))
5532                 return;
5533         if (stmt->commandType != CMD_SELECT || stmt->intoClause)
5534                 return;
5535         plan = stmt->planTree;
5536         if (!IsA(plan, Result))
5537                 return;
5538
5539         /*
5540          * 3. Can't have any subplan or qual clause, either
5541          */
5542         if (plan->lefttree != NULL ||
5543                 plan->righttree != NULL ||
5544                 plan->initPlan != NULL ||
5545                 plan->qual != NULL ||
5546                 ((Result *) plan)->resconstantqual != NULL)
5547                 return;
5548
5549         /*
5550          * 4. The plan must have a single attribute as result
5551          */
5552         if (list_length(plan->targetlist) != 1)
5553                 return;
5554
5555         tle = (TargetEntry *) linitial(plan->targetlist);
5556
5557         /*
5558          * 5. Check that all the nodes in the expression are non-scary.
5559          */
5560         if (!exec_simple_check_node((Node *) tle->expr))
5561                 return;
5562
5563         /*
5564          * Yes - this is a simple expression.  Mark it as such, and initialize
5565          * state to "not valid in current transaction".
5566          */
5567         expr->expr_simple_expr = tle->expr;
5568         expr->expr_simple_state = NULL;
5569         expr->expr_simple_in_use = false;
5570         expr->expr_simple_lxid = InvalidLocalTransactionId;
5571         /* Also stash away the expression result type */
5572         expr->expr_simple_type = exprType((Node *) tle->expr);
5573 }
5574
5575 /* ----------
5576  * exec_set_found                       Set the global found variable
5577  *                                      to true/false
5578  * ----------
5579  */
5580 static void
5581 exec_set_found(PLpgSQL_execstate *estate, bool state)
5582 {
5583         PLpgSQL_var *var;
5584
5585         var = (PLpgSQL_var *) (estate->datums[estate->found_varno]);
5586         var->value = PointerGetDatum(state);
5587         var->isnull = false;
5588 }
5589
5590 /*
5591  * plpgsql_create_econtext --- create an eval_econtext for the current function
5592  *
5593  * We may need to create a new simple_eval_estate too, if there's not one
5594  * already for the current transaction.  The EState will be cleaned up at
5595  * transaction end.
5596  */
5597 static void
5598 plpgsql_create_econtext(PLpgSQL_execstate *estate)
5599 {
5600         SimpleEcontextStackEntry *entry;
5601
5602         /*
5603          * Create an EState for evaluation of simple expressions, if there's not
5604          * one already in the current transaction.      The EState is made a child of
5605          * TopTransactionContext so it will have the right lifespan.
5606          */
5607         if (simple_eval_estate == NULL)
5608         {
5609                 MemoryContext oldcontext;
5610
5611                 oldcontext = MemoryContextSwitchTo(TopTransactionContext);
5612                 simple_eval_estate = CreateExecutorState();
5613                 MemoryContextSwitchTo(oldcontext);
5614         }
5615
5616         /*
5617          * Create a child econtext for the current function.
5618          */
5619         estate->eval_econtext = CreateExprContext(simple_eval_estate);
5620
5621         /*
5622          * Make a stack entry so we can clean up the econtext at subxact end.
5623          * Stack entries are kept in TopTransactionContext for simplicity.
5624          */
5625         entry = (SimpleEcontextStackEntry *)
5626                 MemoryContextAlloc(TopTransactionContext,
5627                                                    sizeof(SimpleEcontextStackEntry));
5628
5629         entry->stack_econtext = estate->eval_econtext;
5630         entry->xact_subxid = GetCurrentSubTransactionId();
5631
5632         entry->next = simple_econtext_stack;
5633         simple_econtext_stack = entry;
5634 }
5635
5636 /*
5637  * plpgsql_destroy_econtext --- destroy function's econtext
5638  *
5639  * We check that it matches the top stack entry, and destroy the stack
5640  * entry along with the context.
5641  */
5642 static void
5643 plpgsql_destroy_econtext(PLpgSQL_execstate *estate)
5644 {
5645         SimpleEcontextStackEntry *next;
5646
5647         Assert(simple_econtext_stack != NULL);
5648         Assert(simple_econtext_stack->stack_econtext == estate->eval_econtext);
5649
5650         next = simple_econtext_stack->next;
5651         pfree(simple_econtext_stack);
5652         simple_econtext_stack = next;
5653
5654         FreeExprContext(estate->eval_econtext, true);
5655         estate->eval_econtext = NULL;
5656 }
5657
5658 /*
5659  * plpgsql_xact_cb --- post-transaction-commit-or-abort cleanup
5660  *
5661  * If a simple-expression EState was created in the current transaction,
5662  * it has to be cleaned up.
5663  */
5664 void
5665 plpgsql_xact_cb(XactEvent event, void *arg)
5666 {
5667         /*
5668          * If we are doing a clean transaction shutdown, free the EState (so that
5669          * any remaining resources will be released correctly). In an abort, we
5670          * expect the regular abort recovery procedures to release everything of
5671          * interest.
5672          */
5673         if (event != XACT_EVENT_ABORT)
5674         {
5675                 /* Shouldn't be any econtext stack entries left at commit */
5676                 Assert(simple_econtext_stack == NULL);
5677
5678                 if (simple_eval_estate)
5679                         FreeExecutorState(simple_eval_estate);
5680                 simple_eval_estate = NULL;
5681         }
5682         else
5683         {
5684                 simple_econtext_stack = NULL;
5685                 simple_eval_estate = NULL;
5686         }
5687 }
5688
5689 /*
5690  * plpgsql_subxact_cb --- post-subtransaction-commit-or-abort cleanup
5691  *
5692  * Make sure any simple-expression econtexts created in the current
5693  * subtransaction get cleaned up.  We have to do this explicitly because
5694  * no other code knows which child econtexts of simple_eval_estate belong
5695  * to which level of subxact.
5696  */
5697 void
5698 plpgsql_subxact_cb(SubXactEvent event, SubTransactionId mySubid,
5699                                    SubTransactionId parentSubid, void *arg)
5700 {
5701         if (event == SUBXACT_EVENT_START_SUB)
5702                 return;
5703
5704         while (simple_econtext_stack != NULL &&
5705                    simple_econtext_stack->xact_subxid == mySubid)
5706         {
5707                 SimpleEcontextStackEntry *next;
5708
5709                 FreeExprContext(simple_econtext_stack->stack_econtext,
5710                                                 (event == SUBXACT_EVENT_COMMIT_SUB));
5711                 next = simple_econtext_stack->next;
5712                 pfree(simple_econtext_stack);
5713                 simple_econtext_stack = next;
5714         }
5715 }
5716
5717 /*
5718  * free_var --- pfree any pass-by-reference value of the variable.
5719  *
5720  * This should always be followed by some assignment to var->value,
5721  * as it leaves a dangling pointer.
5722  */
5723 static void
5724 free_var(PLpgSQL_var *var)
5725 {
5726         if (var->freeval)
5727         {
5728                 pfree(DatumGetPointer(var->value));
5729                 var->freeval = false;
5730         }
5731 }
5732
5733 /*
5734  * free old value of a text variable and assign new value from C string
5735  */
5736 static void
5737 assign_text_var(PLpgSQL_var *var, const char *str)
5738 {
5739         free_var(var);
5740         var->value = CStringGetTextDatum(str);
5741         var->isnull = false;
5742         var->freeval = true;
5743 }
5744
5745 /*
5746  * exec_eval_using_params --- evaluate params of USING clause
5747  */
5748 static PreparedParamsData *
5749 exec_eval_using_params(PLpgSQL_execstate *estate, List *params)
5750 {
5751         PreparedParamsData *ppd;
5752         int                     nargs;
5753         int                     i;
5754         ListCell   *lc;
5755
5756         ppd = (PreparedParamsData *) palloc(sizeof(PreparedParamsData));
5757         nargs = list_length(params);
5758
5759         ppd->nargs = nargs;
5760         ppd->types = (Oid *) palloc(nargs * sizeof(Oid));
5761         ppd->values = (Datum *) palloc(nargs * sizeof(Datum));
5762         ppd->nulls = (char *) palloc(nargs * sizeof(char));
5763         ppd->freevals = (bool *) palloc(nargs * sizeof(bool));
5764
5765         i = 0;
5766         foreach(lc, params)
5767         {
5768                 PLpgSQL_expr *param = (PLpgSQL_expr *) lfirst(lc);
5769                 bool            isnull;
5770
5771                 ppd->values[i] = exec_eval_expr(estate, param,
5772                                                                                 &isnull,
5773                                                                                 &ppd->types[i]);
5774                 ppd->nulls[i] = isnull ? 'n' : ' ';
5775                 ppd->freevals[i] = false;
5776
5777                 if (ppd->types[i] == UNKNOWNOID)
5778                 {
5779                         /*
5780                          * Treat 'unknown' parameters as text, since that's what most
5781                          * people would expect. SPI_execute_with_args can coerce unknown
5782                          * constants in a more intelligent way, but not unknown Params.
5783                          * This code also takes care of copying into the right context.
5784                          * Note we assume 'unknown' has the representation of C-string.
5785                          */
5786                         ppd->types[i] = TEXTOID;
5787                         if (!isnull)
5788                         {
5789                                 ppd->values[i] = CStringGetTextDatum(DatumGetCString(ppd->values[i]));
5790                                 ppd->freevals[i] = true;
5791                         }
5792                 }
5793                 /* pass-by-ref non null values must be copied into plpgsql context */
5794                 else if (!isnull)
5795                 {
5796                         int16           typLen;
5797                         bool            typByVal;
5798
5799                         get_typlenbyval(ppd->types[i], &typLen, &typByVal);
5800                         if (!typByVal)
5801                         {
5802                                 ppd->values[i] = datumCopy(ppd->values[i], typByVal, typLen);
5803                                 ppd->freevals[i] = true;
5804                         }
5805                 }
5806
5807                 exec_eval_cleanup(estate);
5808
5809                 i++;
5810         }
5811
5812         return ppd;
5813 }
5814
5815 /*
5816  * free_params_data --- pfree all pass-by-reference values used in USING clause
5817  */
5818 static void
5819 free_params_data(PreparedParamsData *ppd)
5820 {
5821         int                     i;
5822
5823         for (i = 0; i < ppd->nargs; i++)
5824         {
5825                 if (ppd->freevals[i])
5826                         pfree(DatumGetPointer(ppd->values[i]));
5827         }
5828
5829         pfree(ppd->types);
5830         pfree(ppd->values);
5831         pfree(ppd->nulls);
5832         pfree(ppd->freevals);
5833
5834         pfree(ppd);
5835 }
5836
5837 /*
5838  * Open portal for dynamic query
5839  */
5840 static Portal
5841 exec_dynquery_with_params(PLpgSQL_execstate *estate,
5842                                                   PLpgSQL_expr *dynquery,
5843                                                   List *params,
5844                                                   const char *portalname,
5845                                                   int cursorOptions)
5846 {
5847         Portal          portal;
5848         Datum           query;
5849         bool            isnull;
5850         Oid                     restype;
5851         char       *querystr;
5852
5853         /*
5854          * Evaluate the string expression after the EXECUTE keyword. Its result is
5855          * the querystring we have to execute.
5856          */
5857         query = exec_eval_expr(estate, dynquery, &isnull, &restype);
5858         if (isnull)
5859                 ereport(ERROR,
5860                                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
5861                                  errmsg("query string argument of EXECUTE is null")));
5862
5863         /* Get the C-String representation */
5864         querystr = convert_value_to_string(query, restype);
5865
5866         exec_eval_cleanup(estate);
5867
5868         /*
5869          * Open an implicit cursor for the query.  We use
5870          * SPI_cursor_open_with_args even when there are no params, because this
5871          * avoids making and freeing one copy of the plan.
5872          */
5873         if (params)
5874         {
5875                 PreparedParamsData *ppd;
5876
5877                 ppd = exec_eval_using_params(estate, params);
5878                 portal = SPI_cursor_open_with_args(portalname,
5879                                                                                    querystr,
5880                                                                                    ppd->nargs, ppd->types,
5881                                                                                    ppd->values, ppd->nulls,
5882                                                                                    estate->readonly_func,
5883                                                                                    cursorOptions);
5884                 free_params_data(ppd);
5885         }
5886         else
5887         {
5888                 portal = SPI_cursor_open_with_args(portalname,
5889                                                                                    querystr,
5890                                                                                    0, NULL,
5891                                                                                    NULL, NULL,
5892                                                                                    estate->readonly_func,
5893                                                                                    cursorOptions);
5894         }
5895
5896         if (portal == NULL)
5897                 elog(ERROR, "could not open implicit cursor for query \"%s\": %s",
5898                          querystr, SPI_result_code_string(SPI_result));
5899         pfree(querystr);
5900
5901         return portal;
5902 }