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