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