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