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