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