]> granicus.if.org Git - postgresql/blob - src/pl/plpgsql/src/pl_exec.c
11cb47b5225d987b815d652adc77247b63e2022c
[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-2014, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        src/pl/plpgsql/src/pl_exec.c
12  *
13  *-------------------------------------------------------------------------
14  */
15
16 #include "plpgsql.h"
17
18 #include <ctype.h>
19
20 #include "access/htup_details.h"
21 #include "access/transam.h"
22 #include "access/tupconvert.h"
23 #include "catalog/pg_proc.h"
24 #include "catalog/pg_type.h"
25 #include "executor/spi.h"
26 #include "funcapi.h"
27 #include "miscadmin.h"
28 #include "nodes/nodeFuncs.h"
29 #include "parser/scansup.h"
30 #include "storage/proc.h"
31 #include "tcop/tcopprot.h"
32 #include "utils/array.h"
33 #include "utils/builtins.h"
34 #include "utils/datum.h"
35 #include "utils/lsyscache.h"
36 #include "utils/memutils.h"
37 #include "utils/rel.h"
38 #include "utils/snapmgr.h"
39 #include "utils/typcache.h"
40
41
42 static const char *const raise_skip_msg = "RAISE";
43
44 typedef struct
45 {
46         int                     nargs;                  /* number of arguments */
47         Oid                *types;                      /* types of arguments */
48         Datum      *values;                     /* evaluated argument values */
49         char       *nulls;                      /* null markers (' '/'n' style) */
50         bool       *freevals;           /* which arguments are pfree-able */
51 } PreparedParamsData;
52
53 /*
54  * All plpgsql function executions within a single transaction share the same
55  * executor EState for evaluating "simple" expressions.  Each function call
56  * creates its own "eval_econtext" ExprContext within this estate for
57  * per-evaluation workspace.  eval_econtext is freed at normal function exit,
58  * and the EState is freed at transaction end (in case of error, we assume
59  * that the abort mechanisms clean it all up).  Furthermore, any exception
60  * block within a function has to have its own eval_econtext separate from
61  * the containing function's, so that we can clean up ExprContext callbacks
62  * properly at subtransaction exit.  We maintain a stack that tracks the
63  * individual econtexts so that we can clean up correctly at subxact exit.
64  *
65  * This arrangement is a bit tedious to maintain, but it's worth the trouble
66  * so that we don't have to re-prepare simple expressions on each trip through
67  * a function.  (We assume the case to optimize is many repetitions of a
68  * function within a transaction.)
69  *
70  * However, there's no value in trying to amortize simple expression setup
71  * across multiple executions of a DO block (inline code block), since there
72  * can never be any.  If we use the shared EState for a DO block, the expr
73  * state trees are effectively leaked till end of transaction, and that can
74  * add up if the user keeps on submitting DO blocks.  Therefore, each DO block
75  * has its own simple-expression EState, which is cleaned up at exit from
76  * plpgsql_inline_handler().  DO blocks still use the simple_econtext_stack,
77  * though, so that subxact abort cleanup does the right thing.
78  */
79 typedef struct SimpleEcontextStackEntry
80 {
81         ExprContext *stack_econtext;    /* a stacked econtext */
82         SubTransactionId xact_subxid;           /* ID for current subxact */
83         struct SimpleEcontextStackEntry *next;          /* next stack entry up */
84 } SimpleEcontextStackEntry;
85
86 static EState *shared_simple_eval_estate = NULL;
87 static SimpleEcontextStackEntry *simple_econtext_stack = NULL;
88
89 /************************************************************
90  * Local function forward declarations
91  ************************************************************/
92 static void plpgsql_exec_error_callback(void *arg);
93 static PLpgSQL_datum *copy_plpgsql_datum(PLpgSQL_datum *datum);
94
95 static int exec_stmt_block(PLpgSQL_execstate *estate,
96                                 PLpgSQL_stmt_block *block);
97 static int exec_stmts(PLpgSQL_execstate *estate,
98                    List *stmts);
99 static int exec_stmt(PLpgSQL_execstate *estate,
100                   PLpgSQL_stmt *stmt);
101 static int exec_stmt_assign(PLpgSQL_execstate *estate,
102                                  PLpgSQL_stmt_assign *stmt);
103 static int exec_stmt_perform(PLpgSQL_execstate *estate,
104                                   PLpgSQL_stmt_perform *stmt);
105 static int exec_stmt_getdiag(PLpgSQL_execstate *estate,
106                                   PLpgSQL_stmt_getdiag *stmt);
107 static int exec_stmt_if(PLpgSQL_execstate *estate,
108                          PLpgSQL_stmt_if *stmt);
109 static int exec_stmt_case(PLpgSQL_execstate *estate,
110                            PLpgSQL_stmt_case *stmt);
111 static int exec_stmt_loop(PLpgSQL_execstate *estate,
112                            PLpgSQL_stmt_loop *stmt);
113 static int exec_stmt_while(PLpgSQL_execstate *estate,
114                                 PLpgSQL_stmt_while *stmt);
115 static int exec_stmt_fori(PLpgSQL_execstate *estate,
116                            PLpgSQL_stmt_fori *stmt);
117 static int exec_stmt_fors(PLpgSQL_execstate *estate,
118                            PLpgSQL_stmt_fors *stmt);
119 static int exec_stmt_forc(PLpgSQL_execstate *estate,
120                            PLpgSQL_stmt_forc *stmt);
121 static int exec_stmt_foreach_a(PLpgSQL_execstate *estate,
122                                         PLpgSQL_stmt_foreach_a *stmt);
123 static int exec_stmt_open(PLpgSQL_execstate *estate,
124                            PLpgSQL_stmt_open *stmt);
125 static int exec_stmt_fetch(PLpgSQL_execstate *estate,
126                                 PLpgSQL_stmt_fetch *stmt);
127 static int exec_stmt_close(PLpgSQL_execstate *estate,
128                                 PLpgSQL_stmt_close *stmt);
129 static int exec_stmt_exit(PLpgSQL_execstate *estate,
130                            PLpgSQL_stmt_exit *stmt);
131 static int exec_stmt_return(PLpgSQL_execstate *estate,
132                                  PLpgSQL_stmt_return *stmt);
133 static int exec_stmt_return_next(PLpgSQL_execstate *estate,
134                                           PLpgSQL_stmt_return_next *stmt);
135 static int exec_stmt_return_query(PLpgSQL_execstate *estate,
136                                            PLpgSQL_stmt_return_query *stmt);
137 static int exec_stmt_raise(PLpgSQL_execstate *estate,
138                                 PLpgSQL_stmt_raise *stmt);
139 static int exec_stmt_execsql(PLpgSQL_execstate *estate,
140                                   PLpgSQL_stmt_execsql *stmt);
141 static int exec_stmt_dynexecute(PLpgSQL_execstate *estate,
142                                          PLpgSQL_stmt_dynexecute *stmt);
143 static int exec_stmt_dynfors(PLpgSQL_execstate *estate,
144                                   PLpgSQL_stmt_dynfors *stmt);
145
146 static void plpgsql_estate_setup(PLpgSQL_execstate *estate,
147                                          PLpgSQL_function *func,
148                                          ReturnSetInfo *rsi,
149                                          EState *simple_eval_estate);
150 static void exec_eval_cleanup(PLpgSQL_execstate *estate);
151
152 static void exec_prepare_plan(PLpgSQL_execstate *estate,
153                                   PLpgSQL_expr *expr, int cursorOptions);
154 static bool exec_simple_check_node(Node *node);
155 static void exec_simple_check_plan(PLpgSQL_expr *expr);
156 static void exec_simple_recheck_plan(PLpgSQL_expr *expr, CachedPlan *cplan);
157 static bool exec_eval_simple_expr(PLpgSQL_execstate *estate,
158                                           PLpgSQL_expr *expr,
159                                           Datum *result,
160                                           bool *isNull,
161                                           Oid *rettype);
162
163 static void exec_assign_expr(PLpgSQL_execstate *estate,
164                                  PLpgSQL_datum *target,
165                                  PLpgSQL_expr *expr);
166 static void exec_assign_c_string(PLpgSQL_execstate *estate,
167                                          PLpgSQL_datum *target,
168                                          const char *str);
169 static void exec_assign_value(PLpgSQL_execstate *estate,
170                                   PLpgSQL_datum *target,
171                                   Datum value, Oid valtype, bool *isNull);
172 static void exec_eval_datum(PLpgSQL_execstate *estate,
173                                 PLpgSQL_datum *datum,
174                                 Oid *typeid,
175                                 int32 *typetypmod,
176                                 Datum *value,
177                                 bool *isnull);
178 static int exec_eval_integer(PLpgSQL_execstate *estate,
179                                   PLpgSQL_expr *expr,
180                                   bool *isNull);
181 static bool exec_eval_boolean(PLpgSQL_execstate *estate,
182                                   PLpgSQL_expr *expr,
183                                   bool *isNull);
184 static Datum exec_eval_expr(PLpgSQL_execstate *estate,
185                            PLpgSQL_expr *expr,
186                            bool *isNull,
187                            Oid *rettype);
188 static int exec_run_select(PLpgSQL_execstate *estate,
189                                 PLpgSQL_expr *expr, long maxtuples, Portal *portalP);
190 static int exec_for_query(PLpgSQL_execstate *estate, PLpgSQL_stmt_forq *stmt,
191                            Portal portal, bool prefetch_ok);
192 static ParamListInfo setup_param_list(PLpgSQL_execstate *estate,
193                                  PLpgSQL_expr *expr);
194 static void plpgsql_param_fetch(ParamListInfo params, int paramid);
195 static void exec_move_row(PLpgSQL_execstate *estate,
196                           PLpgSQL_rec *rec,
197                           PLpgSQL_row *row,
198                           HeapTuple tup, TupleDesc tupdesc);
199 static HeapTuple make_tuple_from_row(PLpgSQL_execstate *estate,
200                                         PLpgSQL_row *row,
201                                         TupleDesc tupdesc);
202 static HeapTuple get_tuple_from_datum(Datum value);
203 static TupleDesc get_tupdesc_from_datum(Datum value);
204 static void exec_move_row_from_datum(PLpgSQL_execstate *estate,
205                                                  PLpgSQL_rec *rec,
206                                                  PLpgSQL_row *row,
207                                                  Datum value);
208 static char *convert_value_to_string(PLpgSQL_execstate *estate,
209                                                 Datum value, Oid valtype);
210 static Datum exec_cast_value(PLpgSQL_execstate *estate,
211                                 Datum value, Oid valtype,
212                                 Oid reqtype,
213                                 FmgrInfo *reqinput,
214                                 Oid reqtypioparam,
215                                 int32 reqtypmod,
216                                 bool isnull);
217 static Datum exec_simple_cast_value(PLpgSQL_execstate *estate,
218                                            Datum value, Oid valtype,
219                                            Oid reqtype, int32 reqtypmod,
220                                            bool isnull);
221 static void exec_init_tuple_store(PLpgSQL_execstate *estate);
222 static void exec_set_found(PLpgSQL_execstate *estate, bool state);
223 static void plpgsql_create_econtext(PLpgSQL_execstate *estate);
224 static void plpgsql_destroy_econtext(PLpgSQL_execstate *estate);
225 static void free_var(PLpgSQL_var *var);
226 static void assign_text_var(PLpgSQL_var *var, const char *str);
227 static PreparedParamsData *exec_eval_using_params(PLpgSQL_execstate *estate,
228                                            List *params);
229 static void free_params_data(PreparedParamsData *ppd);
230 static Portal exec_dynquery_with_params(PLpgSQL_execstate *estate,
231                                                   PLpgSQL_expr *dynquery, List *params,
232                                                   const char *portalname, int cursorOptions);
233
234 static char *format_expr_params(PLpgSQL_execstate *estate,
235                                    const PLpgSQL_expr *expr);
236 static char *format_preparedparamsdata(PLpgSQL_execstate *estate,
237                                                   const PreparedParamsData *ppd);
238
239
240 /* ----------
241  * plpgsql_exec_function        Called by the call handler for
242  *                              function execution.
243  *
244  * This is also used to execute inline code blocks (DO blocks).  The only
245  * difference that this code is aware of is that for a DO block, we want
246  * to use a private simple_eval_estate, which is created and passed in by
247  * the caller.  For regular functions, pass NULL, which implies using
248  * shared_simple_eval_estate.
249  * ----------
250  */
251 Datum
252 plpgsql_exec_function(PLpgSQL_function *func, FunctionCallInfo fcinfo,
253                                           EState *simple_eval_estate)
254 {
255         PLpgSQL_execstate estate;
256         ErrorContextCallback plerrcontext;
257         int                     i;
258         int                     rc;
259
260         /*
261          * Setup the execution state
262          */
263         plpgsql_estate_setup(&estate, func, (ReturnSetInfo *) fcinfo->resultinfo,
264                                                  simple_eval_estate);
265
266         /*
267          * Setup error traceback support for ereport()
268          */
269         plerrcontext.callback = plpgsql_exec_error_callback;
270         plerrcontext.arg = &estate;
271         plerrcontext.previous = error_context_stack;
272         error_context_stack = &plerrcontext;
273
274         /*
275          * Make local execution copies of all the datums
276          */
277         estate.err_text = gettext_noop("during initialization of execution state");
278         for (i = 0; i < estate.ndatums; i++)
279                 estate.datums[i] = copy_plpgsql_datum(func->datums[i]);
280
281         /*
282          * Store the actual call argument values into the appropriate variables
283          */
284         estate.err_text = gettext_noop("while storing call arguments into local variables");
285         for (i = 0; i < func->fn_nargs; i++)
286         {
287                 int                     n = func->fn_argvarnos[i];
288
289                 switch (estate.datums[n]->dtype)
290                 {
291                         case PLPGSQL_DTYPE_VAR:
292                                 {
293                                         PLpgSQL_var *var = (PLpgSQL_var *) estate.datums[n];
294
295                                         var->value = fcinfo->arg[i];
296                                         var->isnull = fcinfo->argnull[i];
297                                         var->freeval = false;
298                                 }
299                                 break;
300
301                         case PLPGSQL_DTYPE_ROW:
302                                 {
303                                         PLpgSQL_row *row = (PLpgSQL_row *) estate.datums[n];
304
305                                         if (!fcinfo->argnull[i])
306                                         {
307                                                 /* Assign row value from composite datum */
308                                                 exec_move_row_from_datum(&estate, NULL, row,
309                                                                                                  fcinfo->arg[i]);
310                                         }
311                                         else
312                                         {
313                                                 /* If arg is null, treat it as an empty row */
314                                                 exec_move_row(&estate, NULL, row, NULL, NULL);
315                                         }
316                                         /* clean up after exec_move_row() */
317                                         exec_eval_cleanup(&estate);
318                                 }
319                                 break;
320
321                         default:
322                                 elog(ERROR, "unrecognized dtype: %d", func->datums[i]->dtype);
323                 }
324         }
325
326         estate.err_text = gettext_noop("during function entry");
327
328         /*
329          * Set the magic variable FOUND to false
330          */
331         exec_set_found(&estate, false);
332
333         /*
334          * Let the instrumentation plugin peek at this function
335          */
336         if (*plugin_ptr && (*plugin_ptr)->func_beg)
337                 ((*plugin_ptr)->func_beg) (&estate, func);
338
339         /*
340          * Now call the toplevel block of statements
341          */
342         estate.err_text = NULL;
343         estate.err_stmt = (PLpgSQL_stmt *) (func->action);
344         rc = exec_stmt_block(&estate, func->action);
345         if (rc != PLPGSQL_RC_RETURN)
346         {
347                 estate.err_stmt = NULL;
348                 estate.err_text = NULL;
349
350                 /*
351                  * Provide a more helpful message if a CONTINUE or RAISE has been used
352                  * outside the context it can work in.
353                  */
354                 if (rc == PLPGSQL_RC_CONTINUE)
355                         ereport(ERROR,
356                                         (errcode(ERRCODE_SYNTAX_ERROR),
357                                          errmsg("CONTINUE cannot be used outside a loop")));
358                 else
359                         ereport(ERROR,
360                            (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
361                                 errmsg("control reached end of function without RETURN")));
362         }
363
364         /*
365          * We got a return value - process it
366          */
367         estate.err_stmt = NULL;
368         estate.err_text = gettext_noop("while casting return value to function's return type");
369
370         fcinfo->isnull = estate.retisnull;
371
372         if (estate.retisset)
373         {
374                 ReturnSetInfo *rsi = estate.rsi;
375
376                 /* Check caller can handle a set result */
377                 if (!rsi || !IsA(rsi, ReturnSetInfo) ||
378                         (rsi->allowedModes & SFRM_Materialize) == 0)
379                         ereport(ERROR,
380                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
381                                          errmsg("set-valued function called in context that cannot accept a set")));
382                 rsi->returnMode = SFRM_Materialize;
383
384                 /* If we produced any tuples, send back the result */
385                 if (estate.tuple_store)
386                 {
387                         rsi->setResult = estate.tuple_store;
388                         if (estate.rettupdesc)
389                         {
390                                 MemoryContext oldcxt;
391
392                                 oldcxt = MemoryContextSwitchTo(estate.tuple_store_cxt);
393                                 rsi->setDesc = CreateTupleDescCopy(estate.rettupdesc);
394                                 MemoryContextSwitchTo(oldcxt);
395                         }
396                 }
397                 estate.retval = (Datum) 0;
398                 fcinfo->isnull = true;
399         }
400         else if (!estate.retisnull)
401         {
402                 if (estate.retistuple)
403                 {
404                         /*
405                          * We have to check that the returned tuple actually matches the
406                          * expected result type.  XXX would be better to cache the tupdesc
407                          * instead of repeating get_call_result_type()
408                          */
409                         HeapTuple       rettup = (HeapTuple) DatumGetPointer(estate.retval);
410                         TupleDesc       tupdesc;
411                         TupleConversionMap *tupmap;
412
413                         switch (get_call_result_type(fcinfo, NULL, &tupdesc))
414                         {
415                                 case TYPEFUNC_COMPOSITE:
416                                         /* got the expected result rowtype, now check it */
417                                         tupmap = convert_tuples_by_position(estate.rettupdesc,
418                                                                                                                 tupdesc,
419                                                                                                                 gettext_noop("returned record type does not match expected record type"));
420                                         /* it might need conversion */
421                                         if (tupmap)
422                                                 rettup = do_convert_tuple(rettup, tupmap);
423                                         /* no need to free map, we're about to return anyway */
424                                         break;
425                                 case TYPEFUNC_RECORD:
426
427                                         /*
428                                          * Failed to determine actual type of RECORD.  We could
429                                          * raise an error here, but what this means in practice is
430                                          * that the caller is expecting any old generic rowtype,
431                                          * so we don't really need to be restrictive. Pass back
432                                          * the generated result type, instead.
433                                          */
434                                         tupdesc = estate.rettupdesc;
435                                         if (tupdesc == NULL)            /* shouldn't happen */
436                                                 elog(ERROR, "return type must be a row type");
437                                         break;
438                                 default:
439                                         /* shouldn't get here if retistuple is true ... */
440                                         elog(ERROR, "return type must be a row type");
441                                         break;
442                         }
443
444                         /*
445                          * Copy tuple to upper executor memory, as a tuple Datum. Make
446                          * sure it is labeled with the caller-supplied tuple type.
447                          */
448                         estate.retval = PointerGetDatum(SPI_returntuple(rettup, tupdesc));
449                 }
450                 else
451                 {
452                         /* Cast value to proper type */
453                         estate.retval = exec_cast_value(&estate,
454                                                                                         estate.retval,
455                                                                                         estate.rettype,
456                                                                                         func->fn_rettype,
457                                                                                         &(func->fn_retinput),
458                                                                                         func->fn_rettypioparam,
459                                                                                         -1,
460                                                                                         fcinfo->isnull);
461
462                         /*
463                          * If the function's return type isn't by value, copy the value
464                          * into upper executor memory context.
465                          */
466                         if (!fcinfo->isnull && !func->fn_retbyval)
467                         {
468                                 Size            len;
469                                 void       *tmp;
470
471                                 len = datumGetSize(estate.retval, false, func->fn_rettyplen);
472                                 tmp = SPI_palloc(len);
473                                 memcpy(tmp, DatumGetPointer(estate.retval), len);
474                                 estate.retval = PointerGetDatum(tmp);
475                         }
476                 }
477         }
478
479         estate.err_text = gettext_noop("during function exit");
480
481         /*
482          * Let the instrumentation plugin peek at this function
483          */
484         if (*plugin_ptr && (*plugin_ptr)->func_end)
485                 ((*plugin_ptr)->func_end) (&estate, func);
486
487         /* Clean up any leftover temporary memory */
488         plpgsql_destroy_econtext(&estate);
489         exec_eval_cleanup(&estate);
490
491         /*
492          * Pop the error context stack
493          */
494         error_context_stack = plerrcontext.previous;
495
496         /*
497          * Return the function's result
498          */
499         return estate.retval;
500 }
501
502
503 /* ----------
504  * plpgsql_exec_trigger         Called by the call handler for
505  *                              trigger execution.
506  * ----------
507  */
508 HeapTuple
509 plpgsql_exec_trigger(PLpgSQL_function *func,
510                                          TriggerData *trigdata)
511 {
512         PLpgSQL_execstate estate;
513         ErrorContextCallback plerrcontext;
514         int                     i;
515         int                     rc;
516         PLpgSQL_var *var;
517         PLpgSQL_rec *rec_new,
518                            *rec_old;
519         HeapTuple       rettup;
520
521         /*
522          * Setup the execution state
523          */
524         plpgsql_estate_setup(&estate, func, NULL, NULL);
525
526         /*
527          * Setup error traceback support for ereport()
528          */
529         plerrcontext.callback = plpgsql_exec_error_callback;
530         plerrcontext.arg = &estate;
531         plerrcontext.previous = error_context_stack;
532         error_context_stack = &plerrcontext;
533
534         /*
535          * Make local execution copies of all the datums
536          */
537         estate.err_text = gettext_noop("during initialization of execution state");
538         for (i = 0; i < estate.ndatums; i++)
539                 estate.datums[i] = copy_plpgsql_datum(func->datums[i]);
540
541         /*
542          * Put the OLD and NEW tuples into record variables
543          *
544          * We make the tupdescs available in both records even though only one may
545          * have a value.  This allows parsing of record references to succeed in
546          * functions that are used for multiple trigger types.  For example, we
547          * might have a test like "if (TG_OP = 'INSERT' and NEW.foo = 'xyz')",
548          * which should parse regardless of the current trigger type.
549          */
550         rec_new = (PLpgSQL_rec *) (estate.datums[func->new_varno]);
551         rec_new->freetup = false;
552         rec_new->tupdesc = trigdata->tg_relation->rd_att;
553         rec_new->freetupdesc = false;
554         rec_old = (PLpgSQL_rec *) (estate.datums[func->old_varno]);
555         rec_old->freetup = false;
556         rec_old->tupdesc = trigdata->tg_relation->rd_att;
557         rec_old->freetupdesc = false;
558
559         if (!TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
560         {
561                 /*
562                  * Per-statement triggers don't use OLD/NEW variables
563                  */
564                 rec_new->tup = NULL;
565                 rec_old->tup = NULL;
566         }
567         else if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
568         {
569                 rec_new->tup = trigdata->tg_trigtuple;
570                 rec_old->tup = NULL;
571         }
572         else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
573         {
574                 rec_new->tup = trigdata->tg_newtuple;
575                 rec_old->tup = trigdata->tg_trigtuple;
576         }
577         else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
578         {
579                 rec_new->tup = NULL;
580                 rec_old->tup = trigdata->tg_trigtuple;
581         }
582         else
583                 elog(ERROR, "unrecognized trigger action: not INSERT, DELETE, or UPDATE");
584
585         /*
586          * Assign the special tg_ variables
587          */
588
589         var = (PLpgSQL_var *) (estate.datums[func->tg_op_varno]);
590         if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
591                 var->value = CStringGetTextDatum("INSERT");
592         else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
593                 var->value = CStringGetTextDatum("UPDATE");
594         else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
595                 var->value = CStringGetTextDatum("DELETE");
596         else if (TRIGGER_FIRED_BY_TRUNCATE(trigdata->tg_event))
597                 var->value = CStringGetTextDatum("TRUNCATE");
598         else
599                 elog(ERROR, "unrecognized trigger action: not INSERT, DELETE, UPDATE, or TRUNCATE");
600         var->isnull = false;
601         var->freeval = true;
602
603         var = (PLpgSQL_var *) (estate.datums[func->tg_name_varno]);
604         var->value = DirectFunctionCall1(namein,
605                                                           CStringGetDatum(trigdata->tg_trigger->tgname));
606         var->isnull = false;
607         var->freeval = true;
608
609         var = (PLpgSQL_var *) (estate.datums[func->tg_when_varno]);
610         if (TRIGGER_FIRED_BEFORE(trigdata->tg_event))
611                 var->value = CStringGetTextDatum("BEFORE");
612         else if (TRIGGER_FIRED_AFTER(trigdata->tg_event))
613                 var->value = CStringGetTextDatum("AFTER");
614         else if (TRIGGER_FIRED_INSTEAD(trigdata->tg_event))
615                 var->value = CStringGetTextDatum("INSTEAD OF");
616         else
617                 elog(ERROR, "unrecognized trigger execution time: not BEFORE, AFTER, or INSTEAD OF");
618         var->isnull = false;
619         var->freeval = true;
620
621         var = (PLpgSQL_var *) (estate.datums[func->tg_level_varno]);
622         if (TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
623                 var->value = CStringGetTextDatum("ROW");
624         else if (TRIGGER_FIRED_FOR_STATEMENT(trigdata->tg_event))
625                 var->value = CStringGetTextDatum("STATEMENT");
626         else
627                 elog(ERROR, "unrecognized trigger event type: not ROW or STATEMENT");
628         var->isnull = false;
629         var->freeval = true;
630
631         var = (PLpgSQL_var *) (estate.datums[func->tg_relid_varno]);
632         var->value = ObjectIdGetDatum(trigdata->tg_relation->rd_id);
633         var->isnull = false;
634         var->freeval = false;
635
636         var = (PLpgSQL_var *) (estate.datums[func->tg_relname_varno]);
637         var->value = DirectFunctionCall1(namein,
638                         CStringGetDatum(RelationGetRelationName(trigdata->tg_relation)));
639         var->isnull = false;
640         var->freeval = true;
641
642         var = (PLpgSQL_var *) (estate.datums[func->tg_table_name_varno]);
643         var->value = DirectFunctionCall1(namein,
644                         CStringGetDatum(RelationGetRelationName(trigdata->tg_relation)));
645         var->isnull = false;
646         var->freeval = true;
647
648         var = (PLpgSQL_var *) (estate.datums[func->tg_table_schema_varno]);
649         var->value = DirectFunctionCall1(namein,
650                                                                          CStringGetDatum(
651                                                                                                          get_namespace_name(
652                                                                                                                 RelationGetNamespace(
653                                                                                                    trigdata->tg_relation))));
654         var->isnull = false;
655         var->freeval = true;
656
657         var = (PLpgSQL_var *) (estate.datums[func->tg_nargs_varno]);
658         var->value = Int16GetDatum(trigdata->tg_trigger->tgnargs);
659         var->isnull = false;
660         var->freeval = false;
661
662         var = (PLpgSQL_var *) (estate.datums[func->tg_argv_varno]);
663         if (trigdata->tg_trigger->tgnargs > 0)
664         {
665                 /*
666                  * For historical reasons, tg_argv[] subscripts start at zero not one.
667                  * So we can't use construct_array().
668                  */
669                 int                     nelems = trigdata->tg_trigger->tgnargs;
670                 Datum      *elems;
671                 int                     dims[1];
672                 int                     lbs[1];
673
674                 elems = palloc(sizeof(Datum) * nelems);
675                 for (i = 0; i < nelems; i++)
676                         elems[i] = CStringGetTextDatum(trigdata->tg_trigger->tgargs[i]);
677                 dims[0] = nelems;
678                 lbs[0] = 0;
679
680                 var->value = PointerGetDatum(construct_md_array(elems, NULL,
681                                                                                                                 1, dims, lbs,
682                                                                                                                 TEXTOID,
683                                                                                                                 -1, false, 'i'));
684                 var->isnull = false;
685                 var->freeval = true;
686         }
687         else
688         {
689                 var->value = (Datum) 0;
690                 var->isnull = true;
691                 var->freeval = false;
692         }
693
694         estate.err_text = gettext_noop("during function entry");
695
696         /*
697          * Set the magic variable FOUND to false
698          */
699         exec_set_found(&estate, false);
700
701         /*
702          * Let the instrumentation plugin peek at this function
703          */
704         if (*plugin_ptr && (*plugin_ptr)->func_beg)
705                 ((*plugin_ptr)->func_beg) (&estate, func);
706
707         /*
708          * Now call the toplevel block of statements
709          */
710         estate.err_text = NULL;
711         estate.err_stmt = (PLpgSQL_stmt *) (func->action);
712         rc = exec_stmt_block(&estate, func->action);
713         if (rc != PLPGSQL_RC_RETURN)
714         {
715                 estate.err_stmt = NULL;
716                 estate.err_text = NULL;
717
718                 /*
719                  * Provide a more helpful message if a CONTINUE or RAISE has been used
720                  * outside the context it can work in.
721                  */
722                 if (rc == PLPGSQL_RC_CONTINUE)
723                         ereport(ERROR,
724                                         (errcode(ERRCODE_SYNTAX_ERROR),
725                                          errmsg("CONTINUE cannot be used outside a loop")));
726                 else
727                         ereport(ERROR,
728                            (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
729                                 errmsg("control reached end of trigger procedure without RETURN")));
730         }
731
732         estate.err_stmt = NULL;
733         estate.err_text = gettext_noop("during function exit");
734
735         if (estate.retisset)
736                 ereport(ERROR,
737                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
738                                  errmsg("trigger procedure cannot return a set")));
739
740         /*
741          * Check that the returned tuple structure has the same attributes, the
742          * relation that fired the trigger has. A per-statement trigger always
743          * needs to return NULL, so we ignore any return value the function itself
744          * produces (XXX: is this a good idea?)
745          *
746          * XXX This way it is possible, that the trigger returns a tuple where
747          * attributes don't have the correct atttypmod's length. It's up to the
748          * trigger's programmer to ensure that this doesn't happen. Jan
749          */
750         if (estate.retisnull || !TRIGGER_FIRED_FOR_ROW(trigdata->tg_event))
751                 rettup = NULL;
752         else
753         {
754                 TupleConversionMap *tupmap;
755
756                 rettup = (HeapTuple) DatumGetPointer(estate.retval);
757                 /* check rowtype compatibility */
758                 tupmap = convert_tuples_by_position(estate.rettupdesc,
759                                                                                         trigdata->tg_relation->rd_att,
760                                                                                         gettext_noop("returned row structure does not match the structure of the triggering table"));
761                 /* it might need conversion */
762                 if (tupmap)
763                         rettup = do_convert_tuple(rettup, tupmap);
764                 /* no need to free map, we're about to return anyway */
765
766                 /* Copy tuple to upper executor memory */
767                 rettup = SPI_copytuple(rettup);
768         }
769
770         /*
771          * Let the instrumentation plugin peek at this function
772          */
773         if (*plugin_ptr && (*plugin_ptr)->func_end)
774                 ((*plugin_ptr)->func_end) (&estate, func);
775
776         /* Clean up any leftover temporary memory */
777         plpgsql_destroy_econtext(&estate);
778         exec_eval_cleanup(&estate);
779
780         /*
781          * Pop the error context stack
782          */
783         error_context_stack = plerrcontext.previous;
784
785         /*
786          * Return the trigger's result
787          */
788         return rettup;
789 }
790
791 void
792 plpgsql_exec_event_trigger(PLpgSQL_function *func, EventTriggerData *trigdata)
793 {
794         PLpgSQL_execstate estate;
795         ErrorContextCallback plerrcontext;
796         int                     i;
797         int                     rc;
798         PLpgSQL_var *var;
799
800         /*
801          * Setup the execution state
802          */
803         plpgsql_estate_setup(&estate, func, NULL, NULL);
804
805         /*
806          * Setup error traceback support for ereport()
807          */
808         plerrcontext.callback = plpgsql_exec_error_callback;
809         plerrcontext.arg = &estate;
810         plerrcontext.previous = error_context_stack;
811         error_context_stack = &plerrcontext;
812
813         /*
814          * Make local execution copies of all the datums
815          */
816         estate.err_text = gettext_noop("during initialization of execution state");
817         for (i = 0; i < estate.ndatums; i++)
818                 estate.datums[i] = copy_plpgsql_datum(func->datums[i]);
819
820         /*
821          * Assign the special tg_ variables
822          */
823         var = (PLpgSQL_var *) (estate.datums[func->tg_event_varno]);
824         var->value = CStringGetTextDatum(trigdata->event);
825         var->isnull = false;
826         var->freeval = true;
827
828         var = (PLpgSQL_var *) (estate.datums[func->tg_tag_varno]);
829         var->value = CStringGetTextDatum(trigdata->tag);
830         var->isnull = false;
831         var->freeval = true;
832
833         /*
834          * Let the instrumentation plugin peek at this function
835          */
836         if (*plugin_ptr && (*plugin_ptr)->func_beg)
837                 ((*plugin_ptr)->func_beg) (&estate, func);
838
839         /*
840          * Now call the toplevel block of statements
841          */
842         estate.err_text = NULL;
843         estate.err_stmt = (PLpgSQL_stmt *) (func->action);
844         rc = exec_stmt_block(&estate, func->action);
845         if (rc != PLPGSQL_RC_RETURN)
846         {
847                 estate.err_stmt = NULL;
848                 estate.err_text = NULL;
849
850                 /*
851                  * Provide a more helpful message if a CONTINUE or RAISE has been used
852                  * outside the context it can work in.
853                  */
854                 if (rc == PLPGSQL_RC_CONTINUE)
855                         ereport(ERROR,
856                                         (errcode(ERRCODE_SYNTAX_ERROR),
857                                          errmsg("CONTINUE cannot be used outside a loop")));
858                 else
859                         ereport(ERROR,
860                            (errcode(ERRCODE_S_R_E_FUNCTION_EXECUTED_NO_RETURN_STATEMENT),
861                                 errmsg("control reached end of trigger procedure without RETURN")));
862         }
863
864         estate.err_stmt = NULL;
865         estate.err_text = gettext_noop("during function exit");
866
867         /*
868          * Let the instrumentation plugin peek at this function
869          */
870         if (*plugin_ptr && (*plugin_ptr)->func_end)
871                 ((*plugin_ptr)->func_end) (&estate, func);
872
873         /* Clean up any leftover temporary memory */
874         plpgsql_destroy_econtext(&estate);
875         exec_eval_cleanup(&estate);
876
877         /*
878          * Pop the error context stack
879          */
880         error_context_stack = plerrcontext.previous;
881
882         return;
883 }
884
885 /*
886  * error context callback to let us supply a call-stack traceback
887  */
888 static void
889 plpgsql_exec_error_callback(void *arg)
890 {
891         PLpgSQL_execstate *estate = (PLpgSQL_execstate *) arg;
892
893         /* if we are doing RAISE, don't report its location */
894         if (estate->err_text == raise_skip_msg)
895                 return;
896
897         if (estate->err_text != NULL)
898         {
899                 /*
900                  * We don't expend the cycles to run gettext() on err_text unless we
901                  * actually need it.  Therefore, places that set up err_text should
902                  * use gettext_noop() to ensure the strings get recorded in the
903                  * message dictionary.
904                  *
905                  * If both err_text and err_stmt are set, use the err_text as
906                  * description, but report the err_stmt's line number.  When err_stmt
907                  * is not set, we're in function entry/exit, or some such place not
908                  * attached to a specific line number.
909                  */
910                 if (estate->err_stmt != NULL)
911                 {
912                         /*
913                          * translator: last %s is a phrase such as "during statement block
914                          * local variable initialization"
915                          */
916                         errcontext("PL/pgSQL function %s line %d %s",
917                                            estate->func->fn_signature,
918                                            estate->err_stmt->lineno,
919                                            _(estate->err_text));
920                 }
921                 else
922                 {
923                         /*
924                          * translator: last %s is a phrase such as "while storing call
925                          * arguments into local variables"
926                          */
927                         errcontext("PL/pgSQL function %s %s",
928                                            estate->func->fn_signature,
929                                            _(estate->err_text));
930                 }
931         }
932         else if (estate->err_stmt != NULL)
933         {
934                 /* translator: last %s is a plpgsql statement type name */
935                 errcontext("PL/pgSQL function %s line %d at %s",
936                                    estate->func->fn_signature,
937                                    estate->err_stmt->lineno,
938                                    plpgsql_stmt_typename(estate->err_stmt));
939         }
940         else
941                 errcontext("PL/pgSQL function %s",
942                                    estate->func->fn_signature);
943 }
944
945
946 /* ----------
947  * Support function for initializing local execution variables
948  * ----------
949  */
950 static PLpgSQL_datum *
951 copy_plpgsql_datum(PLpgSQL_datum *datum)
952 {
953         PLpgSQL_datum *result;
954
955         switch (datum->dtype)
956         {
957                 case PLPGSQL_DTYPE_VAR:
958                         {
959                                 PLpgSQL_var *new = palloc(sizeof(PLpgSQL_var));
960
961                                 memcpy(new, datum, sizeof(PLpgSQL_var));
962                                 /* Ensure the value is null (possibly not needed?) */
963                                 new->value = 0;
964                                 new->isnull = true;
965                                 new->freeval = false;
966
967                                 result = (PLpgSQL_datum *) new;
968                         }
969                         break;
970
971                 case PLPGSQL_DTYPE_REC:
972                         {
973                                 PLpgSQL_rec *new = palloc(sizeof(PLpgSQL_rec));
974
975                                 memcpy(new, datum, sizeof(PLpgSQL_rec));
976                                 /* Ensure the value is null (possibly not needed?) */
977                                 new->tup = NULL;
978                                 new->tupdesc = NULL;
979                                 new->freetup = false;
980                                 new->freetupdesc = false;
981
982                                 result = (PLpgSQL_datum *) new;
983                         }
984                         break;
985
986                 case PLPGSQL_DTYPE_ROW:
987                 case PLPGSQL_DTYPE_RECFIELD:
988                 case PLPGSQL_DTYPE_ARRAYELEM:
989
990                         /*
991                          * These datum records are read-only at runtime, so no need to
992                          * copy them (well, ARRAYELEM contains some cached type data, but
993                          * we'd just as soon centralize the caching anyway)
994                          */
995                         result = datum;
996                         break;
997
998                 default:
999                         elog(ERROR, "unrecognized dtype: %d", datum->dtype);
1000                         result = NULL;          /* keep compiler quiet */
1001                         break;
1002         }
1003
1004         return result;
1005 }
1006
1007
1008 static bool
1009 exception_matches_conditions(ErrorData *edata, PLpgSQL_condition *cond)
1010 {
1011         for (; cond != NULL; cond = cond->next)
1012         {
1013                 int                     sqlerrstate = cond->sqlerrstate;
1014
1015                 /*
1016                  * OTHERS matches everything *except* query-canceled; if you're
1017                  * foolish enough, you can match that explicitly.
1018                  */
1019                 if (sqlerrstate == 0)
1020                 {
1021                         if (edata->sqlerrcode != ERRCODE_QUERY_CANCELED)
1022                                 return true;
1023                 }
1024                 /* Exact match? */
1025                 else if (edata->sqlerrcode == sqlerrstate)
1026                         return true;
1027                 /* Category match? */
1028                 else if (ERRCODE_IS_CATEGORY(sqlerrstate) &&
1029                                  ERRCODE_TO_CATEGORY(edata->sqlerrcode) == sqlerrstate)
1030                         return true;
1031         }
1032         return false;
1033 }
1034
1035
1036 /* ----------
1037  * exec_stmt_block                      Execute a block of statements
1038  * ----------
1039  */
1040 static int
1041 exec_stmt_block(PLpgSQL_execstate *estate, PLpgSQL_stmt_block *block)
1042 {
1043         volatile int rc = -1;
1044         int                     i;
1045         int                     n;
1046
1047         /*
1048          * First initialize all variables declared in this block
1049          */
1050         estate->err_text = gettext_noop("during statement block local variable initialization");
1051
1052         for (i = 0; i < block->n_initvars; i++)
1053         {
1054                 n = block->initvarnos[i];
1055
1056                 switch (estate->datums[n]->dtype)
1057                 {
1058                         case PLPGSQL_DTYPE_VAR:
1059                                 {
1060                                         PLpgSQL_var *var = (PLpgSQL_var *) (estate->datums[n]);
1061
1062                                         /* free any old value, in case re-entering block */
1063                                         free_var(var);
1064
1065                                         /* Initially it contains a NULL */
1066                                         var->value = (Datum) 0;
1067                                         var->isnull = true;
1068
1069                                         if (var->default_val == NULL)
1070                                         {
1071                                                 /*
1072                                                  * If needed, give the datatype a chance to reject
1073                                                  * NULLs, by assigning a NULL to the variable. We
1074                                                  * claim the value is of type UNKNOWN, not the var's
1075                                                  * datatype, else coercion will be skipped. (Do this
1076                                                  * before the notnull check to be consistent with
1077                                                  * exec_assign_value.)
1078                                                  */
1079                                                 if (!var->datatype->typinput.fn_strict)
1080                                                 {
1081                                                         bool            valIsNull = true;
1082
1083                                                         exec_assign_value(estate,
1084                                                                                           (PLpgSQL_datum *) var,
1085                                                                                           (Datum) 0,
1086                                                                                           UNKNOWNOID,
1087                                                                                           &valIsNull);
1088                                                 }
1089                                                 if (var->notnull)
1090                                                         ereport(ERROR,
1091                                                                         (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1092                                                                          errmsg("variable \"%s\" declared NOT NULL cannot default to NULL",
1093                                                                                         var->refname)));
1094                                         }
1095                                         else
1096                                         {
1097                                                 exec_assign_expr(estate, (PLpgSQL_datum *) var,
1098                                                                                  var->default_val);
1099                                         }
1100                                 }
1101                                 break;
1102
1103                         case PLPGSQL_DTYPE_REC:
1104                                 {
1105                                         PLpgSQL_rec *rec = (PLpgSQL_rec *) (estate->datums[n]);
1106
1107                                         if (rec->freetup)
1108                                         {
1109                                                 heap_freetuple(rec->tup);
1110                                                 rec->freetup = false;
1111                                         }
1112                                         if (rec->freetupdesc)
1113                                         {
1114                                                 FreeTupleDesc(rec->tupdesc);
1115                                                 rec->freetupdesc = false;
1116                                         }
1117                                         rec->tup = NULL;
1118                                         rec->tupdesc = NULL;
1119                                 }
1120                                 break;
1121
1122                         case PLPGSQL_DTYPE_RECFIELD:
1123                         case PLPGSQL_DTYPE_ARRAYELEM:
1124                                 break;
1125
1126                         default:
1127                                 elog(ERROR, "unrecognized dtype: %d",
1128                                          estate->datums[n]->dtype);
1129                 }
1130         }
1131
1132         if (block->exceptions)
1133         {
1134                 /*
1135                  * Execute the statements in the block's body inside a sub-transaction
1136                  */
1137                 MemoryContext oldcontext = CurrentMemoryContext;
1138                 ResourceOwner oldowner = CurrentResourceOwner;
1139                 ExprContext *old_eval_econtext = estate->eval_econtext;
1140                 ErrorData  *save_cur_error = estate->cur_error;
1141
1142                 estate->err_text = gettext_noop("during statement block entry");
1143
1144                 BeginInternalSubTransaction(NULL);
1145                 /* Want to run statements inside function's memory context */
1146                 MemoryContextSwitchTo(oldcontext);
1147
1148                 PG_TRY();
1149                 {
1150                         /*
1151                          * We need to run the block's statements with a new eval_econtext
1152                          * that belongs to the current subtransaction; if we try to use
1153                          * the outer econtext then ExprContext shutdown callbacks will be
1154                          * called at the wrong times.
1155                          */
1156                         plpgsql_create_econtext(estate);
1157
1158                         estate->err_text = NULL;
1159
1160                         /* Run the block's statements */
1161                         rc = exec_stmts(estate, block->body);
1162
1163                         estate->err_text = gettext_noop("during statement block exit");
1164
1165                         /*
1166                          * If the block ended with RETURN, we may need to copy the return
1167                          * value out of the subtransaction eval_context.  This is
1168                          * currently only needed for scalar result types --- rowtype
1169                          * values will always exist in the function's own memory context.
1170                          */
1171                         if (rc == PLPGSQL_RC_RETURN &&
1172                                 !estate->retisset &&
1173                                 !estate->retisnull &&
1174                                 estate->rettupdesc == NULL)
1175                         {
1176                                 int16           resTypLen;
1177                                 bool            resTypByVal;
1178
1179                                 get_typlenbyval(estate->rettype, &resTypLen, &resTypByVal);
1180                                 estate->retval = datumCopy(estate->retval,
1181                                                                                    resTypByVal, resTypLen);
1182                         }
1183
1184                         /* Commit the inner transaction, return to outer xact context */
1185                         ReleaseCurrentSubTransaction();
1186                         MemoryContextSwitchTo(oldcontext);
1187                         CurrentResourceOwner = oldowner;
1188
1189                         /*
1190                          * Revert to outer eval_econtext.  (The inner one was
1191                          * automatically cleaned up during subxact exit.)
1192                          */
1193                         estate->eval_econtext = old_eval_econtext;
1194
1195                         /*
1196                          * AtEOSubXact_SPI() should not have popped any SPI context, but
1197                          * just in case it did, make sure we remain connected.
1198                          */
1199                         SPI_restore_connection();
1200                 }
1201                 PG_CATCH();
1202                 {
1203                         ErrorData  *edata;
1204                         ListCell   *e;
1205
1206                         estate->err_text = gettext_noop("during exception cleanup");
1207
1208                         /* Save error info */
1209                         MemoryContextSwitchTo(oldcontext);
1210                         edata = CopyErrorData();
1211                         FlushErrorState();
1212
1213                         /* Abort the inner transaction */
1214                         RollbackAndReleaseCurrentSubTransaction();
1215                         MemoryContextSwitchTo(oldcontext);
1216                         CurrentResourceOwner = oldowner;
1217
1218                         /* Revert to outer eval_econtext */
1219                         estate->eval_econtext = old_eval_econtext;
1220
1221                         /*
1222                          * If AtEOSubXact_SPI() popped any SPI context of the subxact, it
1223                          * will have left us in a disconnected state.  We need this hack
1224                          * to return to connected state.
1225                          */
1226                         SPI_restore_connection();
1227
1228                         /*
1229                          * Must clean up the econtext too.  However, any tuple table made
1230                          * in the subxact will have been thrown away by SPI during subxact
1231                          * abort, so we don't need to (and mustn't try to) free the
1232                          * eval_tuptable.
1233                          */
1234                         estate->eval_tuptable = NULL;
1235                         exec_eval_cleanup(estate);
1236
1237                         /* Look for a matching exception handler */
1238                         foreach(e, block->exceptions->exc_list)
1239                         {
1240                                 PLpgSQL_exception *exception = (PLpgSQL_exception *) lfirst(e);
1241
1242                                 if (exception_matches_conditions(edata, exception->conditions))
1243                                 {
1244                                         /*
1245                                          * Initialize the magic SQLSTATE and SQLERRM variables for
1246                                          * the exception block. We needn't do this until we have
1247                                          * found a matching exception.
1248                                          */
1249                                         PLpgSQL_var *state_var;
1250                                         PLpgSQL_var *errm_var;
1251
1252                                         state_var = (PLpgSQL_var *)
1253                                                 estate->datums[block->exceptions->sqlstate_varno];
1254                                         errm_var = (PLpgSQL_var *)
1255                                                 estate->datums[block->exceptions->sqlerrm_varno];
1256
1257                                         assign_text_var(state_var,
1258                                                                         unpack_sql_state(edata->sqlerrcode));
1259                                         assign_text_var(errm_var, edata->message);
1260
1261                                         /*
1262                                          * Also set up cur_error so the error data is accessible
1263                                          * inside the handler.
1264                                          */
1265                                         estate->cur_error = edata;
1266
1267                                         estate->err_text = NULL;
1268
1269                                         rc = exec_stmts(estate, exception->action);
1270
1271                                         free_var(state_var);
1272                                         state_var->value = (Datum) 0;
1273                                         state_var->isnull = true;
1274                                         free_var(errm_var);
1275                                         errm_var->value = (Datum) 0;
1276                                         errm_var->isnull = true;
1277
1278                                         break;
1279                                 }
1280                         }
1281
1282                         /*
1283                          * Restore previous state of cur_error, whether or not we executed
1284                          * a handler.  This is needed in case an error got thrown from
1285                          * some inner block's exception handler.
1286                          */
1287                         estate->cur_error = save_cur_error;
1288
1289                         /* If no match found, re-throw the error */
1290                         if (e == NULL)
1291                                 ReThrowError(edata);
1292                         else
1293                                 FreeErrorData(edata);
1294                 }
1295                 PG_END_TRY();
1296
1297                 Assert(save_cur_error == estate->cur_error);
1298         }
1299         else
1300         {
1301                 /*
1302                  * Just execute the statements in the block's body
1303                  */
1304                 estate->err_text = NULL;
1305
1306                 rc = exec_stmts(estate, block->body);
1307         }
1308
1309         estate->err_text = NULL;
1310
1311         /*
1312          * Handle the return code.
1313          */
1314         switch (rc)
1315         {
1316                 case PLPGSQL_RC_OK:
1317                 case PLPGSQL_RC_RETURN:
1318                 case PLPGSQL_RC_CONTINUE:
1319                         return rc;
1320
1321                 case PLPGSQL_RC_EXIT:
1322
1323                         /*
1324                          * This is intentionally different from the handling of RC_EXIT
1325                          * for loops: to match a block, we require a match by label.
1326                          */
1327                         if (estate->exitlabel == NULL)
1328                                 return PLPGSQL_RC_EXIT;
1329                         if (block->label == NULL)
1330                                 return PLPGSQL_RC_EXIT;
1331                         if (strcmp(block->label, estate->exitlabel) != 0)
1332                                 return PLPGSQL_RC_EXIT;
1333                         estate->exitlabel = NULL;
1334                         return PLPGSQL_RC_OK;
1335
1336                 default:
1337                         elog(ERROR, "unrecognized rc: %d", rc);
1338         }
1339
1340         return PLPGSQL_RC_OK;
1341 }
1342
1343
1344 /* ----------
1345  * exec_stmts                   Iterate over a list of statements
1346  *                              as long as their return code is OK
1347  * ----------
1348  */
1349 static int
1350 exec_stmts(PLpgSQL_execstate *estate, List *stmts)
1351 {
1352         ListCell   *s;
1353
1354         if (stmts == NIL)
1355         {
1356                 /*
1357                  * Ensure we do a CHECK_FOR_INTERRUPTS() even though there is no
1358                  * statement.  This prevents hangup in a tight loop if, for instance,
1359                  * there is a LOOP construct with an empty body.
1360                  */
1361                 CHECK_FOR_INTERRUPTS();
1362                 return PLPGSQL_RC_OK;
1363         }
1364
1365         foreach(s, stmts)
1366         {
1367                 PLpgSQL_stmt *stmt = (PLpgSQL_stmt *) lfirst(s);
1368                 int                     rc = exec_stmt(estate, stmt);
1369
1370                 if (rc != PLPGSQL_RC_OK)
1371                         return rc;
1372         }
1373
1374         return PLPGSQL_RC_OK;
1375 }
1376
1377
1378 /* ----------
1379  * exec_stmt                    Distribute one statement to the statements
1380  *                              type specific execution function.
1381  * ----------
1382  */
1383 static int
1384 exec_stmt(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
1385 {
1386         PLpgSQL_stmt *save_estmt;
1387         int                     rc = -1;
1388
1389         save_estmt = estate->err_stmt;
1390         estate->err_stmt = stmt;
1391
1392         /* Let the plugin know that we are about to execute this statement */
1393         if (*plugin_ptr && (*plugin_ptr)->stmt_beg)
1394                 ((*plugin_ptr)->stmt_beg) (estate, stmt);
1395
1396         CHECK_FOR_INTERRUPTS();
1397
1398         switch ((enum PLpgSQL_stmt_types) stmt->cmd_type)
1399         {
1400                 case PLPGSQL_STMT_BLOCK:
1401                         rc = exec_stmt_block(estate, (PLpgSQL_stmt_block *) stmt);
1402                         break;
1403
1404                 case PLPGSQL_STMT_ASSIGN:
1405                         rc = exec_stmt_assign(estate, (PLpgSQL_stmt_assign *) stmt);
1406                         break;
1407
1408                 case PLPGSQL_STMT_PERFORM:
1409                         rc = exec_stmt_perform(estate, (PLpgSQL_stmt_perform *) stmt);
1410                         break;
1411
1412                 case PLPGSQL_STMT_GETDIAG:
1413                         rc = exec_stmt_getdiag(estate, (PLpgSQL_stmt_getdiag *) stmt);
1414                         break;
1415
1416                 case PLPGSQL_STMT_IF:
1417                         rc = exec_stmt_if(estate, (PLpgSQL_stmt_if *) stmt);
1418                         break;
1419
1420                 case PLPGSQL_STMT_CASE:
1421                         rc = exec_stmt_case(estate, (PLpgSQL_stmt_case *) stmt);
1422                         break;
1423
1424                 case PLPGSQL_STMT_LOOP:
1425                         rc = exec_stmt_loop(estate, (PLpgSQL_stmt_loop *) stmt);
1426                         break;
1427
1428                 case PLPGSQL_STMT_WHILE:
1429                         rc = exec_stmt_while(estate, (PLpgSQL_stmt_while *) stmt);
1430                         break;
1431
1432                 case PLPGSQL_STMT_FORI:
1433                         rc = exec_stmt_fori(estate, (PLpgSQL_stmt_fori *) stmt);
1434                         break;
1435
1436                 case PLPGSQL_STMT_FORS:
1437                         rc = exec_stmt_fors(estate, (PLpgSQL_stmt_fors *) stmt);
1438                         break;
1439
1440                 case PLPGSQL_STMT_FORC:
1441                         rc = exec_stmt_forc(estate, (PLpgSQL_stmt_forc *) stmt);
1442                         break;
1443
1444                 case PLPGSQL_STMT_FOREACH_A:
1445                         rc = exec_stmt_foreach_a(estate, (PLpgSQL_stmt_foreach_a *) stmt);
1446                         break;
1447
1448                 case PLPGSQL_STMT_EXIT:
1449                         rc = exec_stmt_exit(estate, (PLpgSQL_stmt_exit *) stmt);
1450                         break;
1451
1452                 case PLPGSQL_STMT_RETURN:
1453                         rc = exec_stmt_return(estate, (PLpgSQL_stmt_return *) stmt);
1454                         break;
1455
1456                 case PLPGSQL_STMT_RETURN_NEXT:
1457                         rc = exec_stmt_return_next(estate, (PLpgSQL_stmt_return_next *) stmt);
1458                         break;
1459
1460                 case PLPGSQL_STMT_RETURN_QUERY:
1461                         rc = exec_stmt_return_query(estate, (PLpgSQL_stmt_return_query *) stmt);
1462                         break;
1463
1464                 case PLPGSQL_STMT_RAISE:
1465                         rc = exec_stmt_raise(estate, (PLpgSQL_stmt_raise *) stmt);
1466                         break;
1467
1468                 case PLPGSQL_STMT_EXECSQL:
1469                         rc = exec_stmt_execsql(estate, (PLpgSQL_stmt_execsql *) stmt);
1470                         break;
1471
1472                 case PLPGSQL_STMT_DYNEXECUTE:
1473                         rc = exec_stmt_dynexecute(estate, (PLpgSQL_stmt_dynexecute *) stmt);
1474                         break;
1475
1476                 case PLPGSQL_STMT_DYNFORS:
1477                         rc = exec_stmt_dynfors(estate, (PLpgSQL_stmt_dynfors *) stmt);
1478                         break;
1479
1480                 case PLPGSQL_STMT_OPEN:
1481                         rc = exec_stmt_open(estate, (PLpgSQL_stmt_open *) stmt);
1482                         break;
1483
1484                 case PLPGSQL_STMT_FETCH:
1485                         rc = exec_stmt_fetch(estate, (PLpgSQL_stmt_fetch *) stmt);
1486                         break;
1487
1488                 case PLPGSQL_STMT_CLOSE:
1489                         rc = exec_stmt_close(estate, (PLpgSQL_stmt_close *) stmt);
1490                         break;
1491
1492                 default:
1493                         estate->err_stmt = save_estmt;
1494                         elog(ERROR, "unrecognized cmdtype: %d", stmt->cmd_type);
1495         }
1496
1497         /* Let the plugin know that we have finished executing this statement */
1498         if (*plugin_ptr && (*plugin_ptr)->stmt_end)
1499                 ((*plugin_ptr)->stmt_end) (estate, stmt);
1500
1501         estate->err_stmt = save_estmt;
1502
1503         return rc;
1504 }
1505
1506
1507 /* ----------
1508  * exec_stmt_assign                     Evaluate an expression and
1509  *                                      put the result into a variable.
1510  * ----------
1511  */
1512 static int
1513 exec_stmt_assign(PLpgSQL_execstate *estate, PLpgSQL_stmt_assign *stmt)
1514 {
1515         Assert(stmt->varno >= 0);
1516
1517         exec_assign_expr(estate, estate->datums[stmt->varno], stmt->expr);
1518
1519         return PLPGSQL_RC_OK;
1520 }
1521
1522 /* ----------
1523  * exec_stmt_perform            Evaluate query and discard result (but set
1524  *                                                      FOUND depending on whether at least one row
1525  *                                                      was returned).
1526  * ----------
1527  */
1528 static int
1529 exec_stmt_perform(PLpgSQL_execstate *estate, PLpgSQL_stmt_perform *stmt)
1530 {
1531         PLpgSQL_expr *expr = stmt->expr;
1532
1533         (void) exec_run_select(estate, expr, 0, NULL);
1534         exec_set_found(estate, (estate->eval_processed != 0));
1535         exec_eval_cleanup(estate);
1536
1537         return PLPGSQL_RC_OK;
1538 }
1539
1540 /* ----------
1541  * exec_stmt_getdiag                                    Put internal PG information into
1542  *                                                                              specified variables.
1543  * ----------
1544  */
1545 static int
1546 exec_stmt_getdiag(PLpgSQL_execstate *estate, PLpgSQL_stmt_getdiag *stmt)
1547 {
1548         ListCell   *lc;
1549
1550         /*
1551          * GET STACKED DIAGNOSTICS is only valid inside an exception handler.
1552          *
1553          * Note: we trust the grammar to have disallowed the relevant item kinds
1554          * if not is_stacked, otherwise we'd dump core below.
1555          */
1556         if (stmt->is_stacked && estate->cur_error == NULL)
1557                 ereport(ERROR,
1558                 (errcode(ERRCODE_STACKED_DIAGNOSTICS_ACCESSED_WITHOUT_ACTIVE_HANDLER),
1559                  errmsg("GET STACKED DIAGNOSTICS cannot be used outside an exception handler")));
1560
1561         foreach(lc, stmt->diag_items)
1562         {
1563                 PLpgSQL_diag_item *diag_item = (PLpgSQL_diag_item *) lfirst(lc);
1564                 PLpgSQL_datum *var = estate->datums[diag_item->target];
1565                 bool            isnull = false;
1566
1567                 switch (diag_item->kind)
1568                 {
1569                         case PLPGSQL_GETDIAG_ROW_COUNT:
1570                                 exec_assign_value(estate, var,
1571                                                                   UInt32GetDatum(estate->eval_processed),
1572                                                                   INT4OID, &isnull);
1573                                 break;
1574
1575                         case PLPGSQL_GETDIAG_RESULT_OID:
1576                                 exec_assign_value(estate, var,
1577                                                                   ObjectIdGetDatum(estate->eval_lastoid),
1578                                                                   OIDOID, &isnull);
1579                                 break;
1580
1581                         case PLPGSQL_GETDIAG_ERROR_CONTEXT:
1582                                 exec_assign_c_string(estate, var,
1583                                                                          estate->cur_error->context);
1584                                 break;
1585
1586                         case PLPGSQL_GETDIAG_ERROR_DETAIL:
1587                                 exec_assign_c_string(estate, var,
1588                                                                          estate->cur_error->detail);
1589                                 break;
1590
1591                         case PLPGSQL_GETDIAG_ERROR_HINT:
1592                                 exec_assign_c_string(estate, var,
1593                                                                          estate->cur_error->hint);
1594                                 break;
1595
1596                         case PLPGSQL_GETDIAG_RETURNED_SQLSTATE:
1597                                 exec_assign_c_string(estate, var,
1598                                                         unpack_sql_state(estate->cur_error->sqlerrcode));
1599                                 break;
1600
1601                         case PLPGSQL_GETDIAG_COLUMN_NAME:
1602                                 exec_assign_c_string(estate, var,
1603                                                                          estate->cur_error->column_name);
1604                                 break;
1605
1606                         case PLPGSQL_GETDIAG_CONSTRAINT_NAME:
1607                                 exec_assign_c_string(estate, var,
1608                                                                          estate->cur_error->constraint_name);
1609                                 break;
1610
1611                         case PLPGSQL_GETDIAG_DATATYPE_NAME:
1612                                 exec_assign_c_string(estate, var,
1613                                                                          estate->cur_error->datatype_name);
1614                                 break;
1615
1616                         case PLPGSQL_GETDIAG_MESSAGE_TEXT:
1617                                 exec_assign_c_string(estate, var,
1618                                                                          estate->cur_error->message);
1619                                 break;
1620
1621                         case PLPGSQL_GETDIAG_TABLE_NAME:
1622                                 exec_assign_c_string(estate, var,
1623                                                                          estate->cur_error->table_name);
1624                                 break;
1625
1626                         case PLPGSQL_GETDIAG_SCHEMA_NAME:
1627                                 exec_assign_c_string(estate, var,
1628                                                                          estate->cur_error->schema_name);
1629                                 break;
1630
1631                         case PLPGSQL_GETDIAG_CONTEXT:
1632                                 {
1633                                         char       *contextstackstr = GetErrorContextStack();
1634
1635                                         exec_assign_c_string(estate, var, contextstackstr);
1636
1637                                         pfree(contextstackstr);
1638                                 }
1639                                 break;
1640
1641                         default:
1642                                 elog(ERROR, "unrecognized diagnostic item kind: %d",
1643                                          diag_item->kind);
1644                 }
1645         }
1646
1647         return PLPGSQL_RC_OK;
1648 }
1649
1650 /* ----------
1651  * exec_stmt_if                         Evaluate a bool expression and
1652  *                                      execute the true or false body
1653  *                                      conditionally.
1654  * ----------
1655  */
1656 static int
1657 exec_stmt_if(PLpgSQL_execstate *estate, PLpgSQL_stmt_if *stmt)
1658 {
1659         bool            value;
1660         bool            isnull;
1661         ListCell   *lc;
1662
1663         value = exec_eval_boolean(estate, stmt->cond, &isnull);
1664         exec_eval_cleanup(estate);
1665         if (!isnull && value)
1666                 return exec_stmts(estate, stmt->then_body);
1667
1668         foreach(lc, stmt->elsif_list)
1669         {
1670                 PLpgSQL_if_elsif *elif = (PLpgSQL_if_elsif *) lfirst(lc);
1671
1672                 value = exec_eval_boolean(estate, elif->cond, &isnull);
1673                 exec_eval_cleanup(estate);
1674                 if (!isnull && value)
1675                         return exec_stmts(estate, elif->stmts);
1676         }
1677
1678         return exec_stmts(estate, stmt->else_body);
1679 }
1680
1681
1682 /*-----------
1683  * exec_stmt_case
1684  *-----------
1685  */
1686 static int
1687 exec_stmt_case(PLpgSQL_execstate *estate, PLpgSQL_stmt_case *stmt)
1688 {
1689         PLpgSQL_var *t_var = NULL;
1690         bool            isnull;
1691         ListCell   *l;
1692
1693         if (stmt->t_expr != NULL)
1694         {
1695                 /* simple case */
1696                 Datum           t_val;
1697                 Oid                     t_oid;
1698
1699                 t_val = exec_eval_expr(estate, stmt->t_expr, &isnull, &t_oid);
1700
1701                 t_var = (PLpgSQL_var *) estate->datums[stmt->t_varno];
1702
1703                 /*
1704                  * When expected datatype is different from real, change it. Note that
1705                  * what we're modifying here is an execution copy of the datum, so
1706                  * this doesn't affect the originally stored function parse tree.
1707                  */
1708                 if (t_var->datatype->typoid != t_oid)
1709                         t_var->datatype = plpgsql_build_datatype(t_oid,
1710                                                                                                          -1,
1711                                                                                    estate->func->fn_input_collation);
1712
1713                 /* now we can assign to the variable */
1714                 exec_assign_value(estate,
1715                                                   (PLpgSQL_datum *) t_var,
1716                                                   t_val,
1717                                                   t_oid,
1718                                                   &isnull);
1719
1720                 exec_eval_cleanup(estate);
1721         }
1722
1723         /* Now search for a successful WHEN clause */
1724         foreach(l, stmt->case_when_list)
1725         {
1726                 PLpgSQL_case_when *cwt = (PLpgSQL_case_when *) lfirst(l);
1727                 bool            value;
1728
1729                 value = exec_eval_boolean(estate, cwt->expr, &isnull);
1730                 exec_eval_cleanup(estate);
1731                 if (!isnull && value)
1732                 {
1733                         /* Found it */
1734
1735                         /* We can now discard any value we had for the temp variable */
1736                         if (t_var != NULL)
1737                         {
1738                                 free_var(t_var);
1739                                 t_var->value = (Datum) 0;
1740                                 t_var->isnull = true;
1741                         }
1742
1743                         /* Evaluate the statement(s), and we're done */
1744                         return exec_stmts(estate, cwt->stmts);
1745                 }
1746         }
1747
1748         /* We can now discard any value we had for the temp variable */
1749         if (t_var != NULL)
1750         {
1751                 free_var(t_var);
1752                 t_var->value = (Datum) 0;
1753                 t_var->isnull = true;
1754         }
1755
1756         /* SQL2003 mandates this error if there was no ELSE clause */
1757         if (!stmt->have_else)
1758                 ereport(ERROR,
1759                                 (errcode(ERRCODE_CASE_NOT_FOUND),
1760                                  errmsg("case not found"),
1761                                  errhint("CASE statement is missing ELSE part.")));
1762
1763         /* Evaluate the ELSE statements, and we're done */
1764         return exec_stmts(estate, stmt->else_stmts);
1765 }
1766
1767
1768 /* ----------
1769  * exec_stmt_loop                       Loop over statements until
1770  *                                      an exit occurs.
1771  * ----------
1772  */
1773 static int
1774 exec_stmt_loop(PLpgSQL_execstate *estate, PLpgSQL_stmt_loop *stmt)
1775 {
1776         for (;;)
1777         {
1778                 int                     rc = exec_stmts(estate, stmt->body);
1779
1780                 switch (rc)
1781                 {
1782                         case PLPGSQL_RC_OK:
1783                                 break;
1784
1785                         case PLPGSQL_RC_EXIT:
1786                                 if (estate->exitlabel == NULL)
1787                                         return PLPGSQL_RC_OK;
1788                                 if (stmt->label == NULL)
1789                                         return PLPGSQL_RC_EXIT;
1790                                 if (strcmp(stmt->label, estate->exitlabel) != 0)
1791                                         return PLPGSQL_RC_EXIT;
1792                                 estate->exitlabel = NULL;
1793                                 return PLPGSQL_RC_OK;
1794
1795                         case PLPGSQL_RC_CONTINUE:
1796                                 if (estate->exitlabel == NULL)
1797                                         /* anonymous continue, so re-run the loop */
1798                                         break;
1799                                 else if (stmt->label != NULL &&
1800                                                  strcmp(stmt->label, estate->exitlabel) == 0)
1801                                         /* label matches named continue, so re-run loop */
1802                                         estate->exitlabel = NULL;
1803                                 else
1804                                         /* label doesn't match named continue, so propagate upward */
1805                                         return PLPGSQL_RC_CONTINUE;
1806                                 break;
1807
1808                         case PLPGSQL_RC_RETURN:
1809                                 return rc;
1810
1811                         default:
1812                                 elog(ERROR, "unrecognized rc: %d", rc);
1813                 }
1814         }
1815 }
1816
1817
1818 /* ----------
1819  * exec_stmt_while                      Loop over statements as long
1820  *                                      as an expression evaluates to
1821  *                                      true or an exit occurs.
1822  * ----------
1823  */
1824 static int
1825 exec_stmt_while(PLpgSQL_execstate *estate, PLpgSQL_stmt_while *stmt)
1826 {
1827         for (;;)
1828         {
1829                 int                     rc;
1830                 bool            value;
1831                 bool            isnull;
1832
1833                 value = exec_eval_boolean(estate, stmt->cond, &isnull);
1834                 exec_eval_cleanup(estate);
1835
1836                 if (isnull || !value)
1837                         break;
1838
1839                 rc = exec_stmts(estate, stmt->body);
1840
1841                 switch (rc)
1842                 {
1843                         case PLPGSQL_RC_OK:
1844                                 break;
1845
1846                         case PLPGSQL_RC_EXIT:
1847                                 if (estate->exitlabel == NULL)
1848                                         return PLPGSQL_RC_OK;
1849                                 if (stmt->label == NULL)
1850                                         return PLPGSQL_RC_EXIT;
1851                                 if (strcmp(stmt->label, estate->exitlabel) != 0)
1852                                         return PLPGSQL_RC_EXIT;
1853                                 estate->exitlabel = NULL;
1854                                 return PLPGSQL_RC_OK;
1855
1856                         case PLPGSQL_RC_CONTINUE:
1857                                 if (estate->exitlabel == NULL)
1858                                         /* anonymous continue, so re-run loop */
1859                                         break;
1860                                 else if (stmt->label != NULL &&
1861                                                  strcmp(stmt->label, estate->exitlabel) == 0)
1862                                         /* label matches named continue, so re-run loop */
1863                                         estate->exitlabel = NULL;
1864                                 else
1865                                         /* label doesn't match named continue, propagate upward */
1866                                         return PLPGSQL_RC_CONTINUE;
1867                                 break;
1868
1869                         case PLPGSQL_RC_RETURN:
1870                                 return rc;
1871
1872                         default:
1873                                 elog(ERROR, "unrecognized rc: %d", rc);
1874                 }
1875         }
1876
1877         return PLPGSQL_RC_OK;
1878 }
1879
1880
1881 /* ----------
1882  * exec_stmt_fori                       Iterate an integer variable
1883  *                                      from a lower to an upper value
1884  *                                      incrementing or decrementing by the BY value
1885  * ----------
1886  */
1887 static int
1888 exec_stmt_fori(PLpgSQL_execstate *estate, PLpgSQL_stmt_fori *stmt)
1889 {
1890         PLpgSQL_var *var;
1891         Datum           value;
1892         bool            isnull;
1893         Oid                     valtype;
1894         int32           loop_value;
1895         int32           end_value;
1896         int32           step_value;
1897         bool            found = false;
1898         int                     rc = PLPGSQL_RC_OK;
1899
1900         var = (PLpgSQL_var *) (estate->datums[stmt->var->dno]);
1901
1902         /*
1903          * Get the value of the lower bound
1904          */
1905         value = exec_eval_expr(estate, stmt->lower, &isnull, &valtype);
1906         value = exec_cast_value(estate, value, valtype, var->datatype->typoid,
1907                                                         &(var->datatype->typinput),
1908                                                         var->datatype->typioparam,
1909                                                         var->datatype->atttypmod, isnull);
1910         if (isnull)
1911                 ereport(ERROR,
1912                                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1913                                  errmsg("lower bound of FOR loop cannot be null")));
1914         loop_value = DatumGetInt32(value);
1915         exec_eval_cleanup(estate);
1916
1917         /*
1918          * Get the value of the upper bound
1919          */
1920         value = exec_eval_expr(estate, stmt->upper, &isnull, &valtype);
1921         value = exec_cast_value(estate, value, valtype, var->datatype->typoid,
1922                                                         &(var->datatype->typinput),
1923                                                         var->datatype->typioparam,
1924                                                         var->datatype->atttypmod, isnull);
1925         if (isnull)
1926                 ereport(ERROR,
1927                                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1928                                  errmsg("upper bound of FOR loop cannot be null")));
1929         end_value = DatumGetInt32(value);
1930         exec_eval_cleanup(estate);
1931
1932         /*
1933          * Get the step value
1934          */
1935         if (stmt->step)
1936         {
1937                 value = exec_eval_expr(estate, stmt->step, &isnull, &valtype);
1938                 value = exec_cast_value(estate, value, valtype, var->datatype->typoid,
1939                                                                 &(var->datatype->typinput),
1940                                                                 var->datatype->typioparam,
1941                                                                 var->datatype->atttypmod, isnull);
1942                 if (isnull)
1943                         ereport(ERROR,
1944                                         (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
1945                                          errmsg("BY value of FOR loop cannot be null")));
1946                 step_value = DatumGetInt32(value);
1947                 exec_eval_cleanup(estate);
1948                 if (step_value <= 0)
1949                         ereport(ERROR,
1950                                         (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1951                                   errmsg("BY value of FOR loop must be greater than zero")));
1952         }
1953         else
1954                 step_value = 1;
1955
1956         /*
1957          * Now do the loop
1958          */
1959         for (;;)
1960         {
1961                 /*
1962                  * Check against upper bound
1963                  */
1964                 if (stmt->reverse)
1965                 {
1966                         if (loop_value < end_value)
1967                                 break;
1968                 }
1969                 else
1970                 {
1971                         if (loop_value > end_value)
1972                                 break;
1973                 }
1974
1975                 found = true;                   /* looped at least once */
1976
1977                 /*
1978                  * Assign current value to loop var
1979                  */
1980                 var->value = Int32GetDatum(loop_value);
1981                 var->isnull = false;
1982
1983                 /*
1984                  * Execute the statements
1985                  */
1986                 rc = exec_stmts(estate, stmt->body);
1987
1988                 if (rc == PLPGSQL_RC_RETURN)
1989                         break;                          /* break out of the loop */
1990                 else if (rc == PLPGSQL_RC_EXIT)
1991                 {
1992                         if (estate->exitlabel == NULL)
1993                                 /* unlabelled exit, finish the current loop */
1994                                 rc = PLPGSQL_RC_OK;
1995                         else if (stmt->label != NULL &&
1996                                          strcmp(stmt->label, estate->exitlabel) == 0)
1997                         {
1998                                 /* labelled exit, matches the current stmt's label */
1999                                 estate->exitlabel = NULL;
2000                                 rc = PLPGSQL_RC_OK;
2001                         }
2002
2003                         /*
2004                          * otherwise, this is a labelled exit that does not match the
2005                          * current statement's label, if any: return RC_EXIT so that the
2006                          * EXIT continues to propagate up the stack.
2007                          */
2008                         break;
2009                 }
2010                 else if (rc == PLPGSQL_RC_CONTINUE)
2011                 {
2012                         if (estate->exitlabel == NULL)
2013                                 /* unlabelled continue, so re-run the current loop */
2014                                 rc = PLPGSQL_RC_OK;
2015                         else if (stmt->label != NULL &&
2016                                          strcmp(stmt->label, estate->exitlabel) == 0)
2017                         {
2018                                 /* label matches named continue, so re-run loop */
2019                                 estate->exitlabel = NULL;
2020                                 rc = PLPGSQL_RC_OK;
2021                         }
2022                         else
2023                         {
2024                                 /*
2025                                  * otherwise, this is a named continue that does not match the
2026                                  * current statement's label, if any: return RC_CONTINUE so
2027                                  * that the CONTINUE will propagate up the stack.
2028                                  */
2029                                 break;
2030                         }
2031                 }
2032
2033                 /*
2034                  * Increase/decrease loop value, unless it would overflow, in which
2035                  * case exit the loop.
2036                  */
2037                 if (stmt->reverse)
2038                 {
2039                         if ((int32) (loop_value - step_value) > loop_value)
2040                                 break;
2041                         loop_value -= step_value;
2042                 }
2043                 else
2044                 {
2045                         if ((int32) (loop_value + step_value) < loop_value)
2046                                 break;
2047                         loop_value += step_value;
2048                 }
2049         }
2050
2051         /*
2052          * Set the FOUND variable to indicate the result of executing the loop
2053          * (namely, whether we looped one or more times). This must be set here so
2054          * that it does not interfere with the value of the FOUND variable inside
2055          * the loop processing itself.
2056          */
2057         exec_set_found(estate, found);
2058
2059         return rc;
2060 }
2061
2062
2063 /* ----------
2064  * exec_stmt_fors                       Execute a query, assign each
2065  *                                      tuple to a record or row and
2066  *                                      execute a group of statements
2067  *                                      for it.
2068  * ----------
2069  */
2070 static int
2071 exec_stmt_fors(PLpgSQL_execstate *estate, PLpgSQL_stmt_fors *stmt)
2072 {
2073         Portal          portal;
2074         int                     rc;
2075
2076         /*
2077          * Open the implicit cursor for the statement using exec_run_select
2078          */
2079         exec_run_select(estate, stmt->query, 0, &portal);
2080
2081         /*
2082          * Execute the loop
2083          */
2084         rc = exec_for_query(estate, (PLpgSQL_stmt_forq *) stmt, portal, true);
2085
2086         /*
2087          * Close the implicit cursor
2088          */
2089         SPI_cursor_close(portal);
2090
2091         return rc;
2092 }
2093
2094
2095 /* ----------
2096  * exec_stmt_forc                       Execute a loop for each row from a cursor.
2097  * ----------
2098  */
2099 static int
2100 exec_stmt_forc(PLpgSQL_execstate *estate, PLpgSQL_stmt_forc *stmt)
2101 {
2102         PLpgSQL_var *curvar;
2103         char       *curname = NULL;
2104         PLpgSQL_expr *query;
2105         ParamListInfo paramLI;
2106         Portal          portal;
2107         int                     rc;
2108
2109         /* ----------
2110          * Get the cursor variable and if it has an assigned name, check
2111          * that it's not in use currently.
2112          * ----------
2113          */
2114         curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
2115         if (!curvar->isnull)
2116         {
2117                 curname = TextDatumGetCString(curvar->value);
2118                 if (SPI_cursor_find(curname) != NULL)
2119                         ereport(ERROR,
2120                                         (errcode(ERRCODE_DUPLICATE_CURSOR),
2121                                          errmsg("cursor \"%s\" already in use", curname)));
2122         }
2123
2124         /* ----------
2125          * Open the cursor just like an OPEN command
2126          *
2127          * Note: parser should already have checked that statement supplies
2128          * args iff cursor needs them, but we check again to be safe.
2129          * ----------
2130          */
2131         if (stmt->argquery != NULL)
2132         {
2133                 /* ----------
2134                  * OPEN CURSOR with args.  We fake a SELECT ... INTO ...
2135                  * statement to evaluate the args and put 'em into the
2136                  * internal row.
2137                  * ----------
2138                  */
2139                 PLpgSQL_stmt_execsql set_args;
2140
2141                 if (curvar->cursor_explicit_argrow < 0)
2142                         ereport(ERROR,
2143                                         (errcode(ERRCODE_SYNTAX_ERROR),
2144                                          errmsg("arguments given for cursor without arguments")));
2145
2146                 memset(&set_args, 0, sizeof(set_args));
2147                 set_args.cmd_type = PLPGSQL_STMT_EXECSQL;
2148                 set_args.lineno = stmt->lineno;
2149                 set_args.sqlstmt = stmt->argquery;
2150                 set_args.into = true;
2151                 /* XXX historically this has not been STRICT */
2152                 set_args.row = (PLpgSQL_row *)
2153                         (estate->datums[curvar->cursor_explicit_argrow]);
2154
2155                 if (exec_stmt_execsql(estate, &set_args) != PLPGSQL_RC_OK)
2156                         elog(ERROR, "open cursor failed during argument processing");
2157         }
2158         else
2159         {
2160                 if (curvar->cursor_explicit_argrow >= 0)
2161                         ereport(ERROR,
2162                                         (errcode(ERRCODE_SYNTAX_ERROR),
2163                                          errmsg("arguments required for cursor")));
2164         }
2165
2166         query = curvar->cursor_explicit_expr;
2167         Assert(query);
2168
2169         if (query->plan == NULL)
2170                 exec_prepare_plan(estate, query, curvar->cursor_options);
2171
2172         /*
2173          * Set up ParamListInfo (hook function and possibly data values)
2174          */
2175         paramLI = setup_param_list(estate, query);
2176
2177         /*
2178          * Open the cursor (the paramlist will get copied into the portal)
2179          */
2180         portal = SPI_cursor_open_with_paramlist(curname, query->plan,
2181                                                                                         paramLI,
2182                                                                                         estate->readonly_func);
2183         if (portal == NULL)
2184                 elog(ERROR, "could not open cursor: %s",
2185                          SPI_result_code_string(SPI_result));
2186
2187         /* don't need paramlist any more */
2188         if (paramLI)
2189                 pfree(paramLI);
2190
2191         /*
2192          * If cursor variable was NULL, store the generated portal name in it
2193          */
2194         if (curname == NULL)
2195                 assign_text_var(curvar, portal->name);
2196
2197         /*
2198          * Execute the loop.  We can't prefetch because the cursor is accessible
2199          * to the user, for instance via UPDATE WHERE CURRENT OF within the loop.
2200          */
2201         rc = exec_for_query(estate, (PLpgSQL_stmt_forq *) stmt, portal, false);
2202
2203         /* ----------
2204          * Close portal, and restore cursor variable if it was initially NULL.
2205          * ----------
2206          */
2207         SPI_cursor_close(portal);
2208
2209         if (curname == NULL)
2210         {
2211                 free_var(curvar);
2212                 curvar->value = (Datum) 0;
2213                 curvar->isnull = true;
2214         }
2215
2216         if (curname)
2217                 pfree(curname);
2218
2219         return rc;
2220 }
2221
2222
2223 /* ----------
2224  * exec_stmt_foreach_a                  Loop over elements or slices of an array
2225  *
2226  * When looping over elements, the loop variable is the same type that the
2227  * array stores (eg: integer), when looping through slices, the loop variable
2228  * is an array of size and dimensions to match the size of the slice.
2229  * ----------
2230  */
2231 static int
2232 exec_stmt_foreach_a(PLpgSQL_execstate *estate, PLpgSQL_stmt_foreach_a *stmt)
2233 {
2234         ArrayType  *arr;
2235         Oid                     arrtype;
2236         PLpgSQL_datum *loop_var;
2237         Oid                     loop_var_elem_type;
2238         bool            found = false;
2239         int                     rc = PLPGSQL_RC_OK;
2240         ArrayIterator array_iterator;
2241         Oid                     iterator_result_type;
2242         Datum           value;
2243         bool            isnull;
2244
2245         /* get the value of the array expression */
2246         value = exec_eval_expr(estate, stmt->expr, &isnull, &arrtype);
2247         if (isnull)
2248                 ereport(ERROR,
2249                                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2250                                  errmsg("FOREACH expression must not be null")));
2251
2252         /* check the type of the expression - must be an array */
2253         if (!OidIsValid(get_element_type(arrtype)))
2254                 ereport(ERROR,
2255                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
2256                                  errmsg("FOREACH expression must yield an array, not type %s",
2257                                                 format_type_be(arrtype))));
2258
2259         /*
2260          * We must copy the array, else it will disappear in exec_eval_cleanup.
2261          * This is annoying, but cleanup will certainly happen while running the
2262          * loop body, so we have little choice.
2263          */
2264         arr = DatumGetArrayTypePCopy(value);
2265
2266         /* Clean up any leftover temporary memory */
2267         exec_eval_cleanup(estate);
2268
2269         /* Slice dimension must be less than or equal to array dimension */
2270         if (stmt->slice < 0 || stmt->slice > ARR_NDIM(arr))
2271                 ereport(ERROR,
2272                                 (errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
2273                            errmsg("slice dimension (%d) is out of the valid range 0..%d",
2274                                           stmt->slice, ARR_NDIM(arr))));
2275
2276         /* Set up the loop variable and see if it is of an array type */
2277         loop_var = estate->datums[stmt->varno];
2278         if (loop_var->dtype == PLPGSQL_DTYPE_REC ||
2279                 loop_var->dtype == PLPGSQL_DTYPE_ROW)
2280         {
2281                 /*
2282                  * Record/row variable is certainly not of array type, and might not
2283                  * be initialized at all yet, so don't try to get its type
2284                  */
2285                 loop_var_elem_type = InvalidOid;
2286         }
2287         else
2288                 loop_var_elem_type = get_element_type(exec_get_datum_type(estate,
2289                                                                                                                                   loop_var));
2290
2291         /*
2292          * Sanity-check the loop variable type.  We don't try very hard here, and
2293          * should not be too picky since it's possible that exec_assign_value can
2294          * coerce values of different types.  But it seems worthwhile to complain
2295          * if the array-ness of the loop variable is not right.
2296          */
2297         if (stmt->slice > 0 && loop_var_elem_type == InvalidOid)
2298                 ereport(ERROR,
2299                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
2300                 errmsg("FOREACH ... SLICE loop variable must be of an array type")));
2301         if (stmt->slice == 0 && loop_var_elem_type != InvalidOid)
2302                 ereport(ERROR,
2303                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
2304                           errmsg("FOREACH loop variable must not be of an array type")));
2305
2306         /* Create an iterator to step through the array */
2307         array_iterator = array_create_iterator(arr, stmt->slice);
2308
2309         /* Identify iterator result type */
2310         if (stmt->slice > 0)
2311         {
2312                 /* When slicing, nominal type of result is same as array type */
2313                 iterator_result_type = arrtype;
2314         }
2315         else
2316         {
2317                 /* Without slicing, results are individual array elements */
2318                 iterator_result_type = ARR_ELEMTYPE(arr);
2319         }
2320
2321         /* Iterate over the array elements or slices */
2322         while (array_iterate(array_iterator, &value, &isnull))
2323         {
2324                 found = true;                   /* looped at least once */
2325
2326                 /* Assign current element/slice to the loop variable */
2327                 exec_assign_value(estate, loop_var, value, iterator_result_type,
2328                                                   &isnull);
2329
2330                 /* In slice case, value is temporary; must free it to avoid leakage */
2331                 if (stmt->slice > 0)
2332                         pfree(DatumGetPointer(value));
2333
2334                 /*
2335                  * Execute the statements
2336                  */
2337                 rc = exec_stmts(estate, stmt->body);
2338
2339                 /* Handle the return code */
2340                 if (rc == PLPGSQL_RC_RETURN)
2341                         break;                          /* break out of the loop */
2342                 else if (rc == PLPGSQL_RC_EXIT)
2343                 {
2344                         if (estate->exitlabel == NULL)
2345                                 /* unlabelled exit, finish the current loop */
2346                                 rc = PLPGSQL_RC_OK;
2347                         else if (stmt->label != NULL &&
2348                                          strcmp(stmt->label, estate->exitlabel) == 0)
2349                         {
2350                                 /* labelled exit, matches the current stmt's label */
2351                                 estate->exitlabel = NULL;
2352                                 rc = PLPGSQL_RC_OK;
2353                         }
2354
2355                         /*
2356                          * otherwise, this is a labelled exit that does not match the
2357                          * current statement's label, if any: return RC_EXIT so that the
2358                          * EXIT continues to propagate up the stack.
2359                          */
2360                         break;
2361                 }
2362                 else if (rc == PLPGSQL_RC_CONTINUE)
2363                 {
2364                         if (estate->exitlabel == NULL)
2365                                 /* unlabelled continue, so re-run the current loop */
2366                                 rc = PLPGSQL_RC_OK;
2367                         else if (stmt->label != NULL &&
2368                                          strcmp(stmt->label, estate->exitlabel) == 0)
2369                         {
2370                                 /* label matches named continue, so re-run loop */
2371                                 estate->exitlabel = NULL;
2372                                 rc = PLPGSQL_RC_OK;
2373                         }
2374                         else
2375                         {
2376                                 /*
2377                                  * otherwise, this is a named continue that does not match the
2378                                  * current statement's label, if any: return RC_CONTINUE so
2379                                  * that the CONTINUE will propagate up the stack.
2380                                  */
2381                                 break;
2382                         }
2383                 }
2384         }
2385
2386         /* Release temporary memory, including the array value */
2387         array_free_iterator(array_iterator);
2388         pfree(arr);
2389
2390         /*
2391          * Set the FOUND variable to indicate the result of executing the loop
2392          * (namely, whether we looped one or more times). This must be set here so
2393          * that it does not interfere with the value of the FOUND variable inside
2394          * the loop processing itself.
2395          */
2396         exec_set_found(estate, found);
2397
2398         return rc;
2399 }
2400
2401
2402 /* ----------
2403  * exec_stmt_exit                       Implements EXIT and CONTINUE
2404  *
2405  * This begins the process of exiting / restarting a loop.
2406  * ----------
2407  */
2408 static int
2409 exec_stmt_exit(PLpgSQL_execstate *estate, PLpgSQL_stmt_exit *stmt)
2410 {
2411         /*
2412          * If the exit / continue has a condition, evaluate it
2413          */
2414         if (stmt->cond != NULL)
2415         {
2416                 bool            value;
2417                 bool            isnull;
2418
2419                 value = exec_eval_boolean(estate, stmt->cond, &isnull);
2420                 exec_eval_cleanup(estate);
2421                 if (isnull || value == false)
2422                         return PLPGSQL_RC_OK;
2423         }
2424
2425         estate->exitlabel = stmt->label;
2426         if (stmt->is_exit)
2427                 return PLPGSQL_RC_EXIT;
2428         else
2429                 return PLPGSQL_RC_CONTINUE;
2430 }
2431
2432
2433 /* ----------
2434  * exec_stmt_return                     Evaluate an expression and start
2435  *                                      returning from the function.
2436  * ----------
2437  */
2438 static int
2439 exec_stmt_return(PLpgSQL_execstate *estate, PLpgSQL_stmt_return *stmt)
2440 {
2441         /*
2442          * If processing a set-returning PL/pgSQL function, the final RETURN
2443          * indicates that the function is finished producing tuples.  The rest of
2444          * the work will be done at the top level.
2445          */
2446         if (estate->retisset)
2447                 return PLPGSQL_RC_RETURN;
2448
2449         /* initialize for null result (possibly a tuple) */
2450         estate->retval = (Datum) 0;
2451         estate->rettupdesc = NULL;
2452         estate->retisnull = true;
2453
2454         /*
2455          * This special-case path covers record/row variables in fn_retistuple
2456          * functions, as well as functions with one or more OUT parameters.
2457          */
2458         if (stmt->retvarno >= 0)
2459         {
2460                 PLpgSQL_datum *retvar = estate->datums[stmt->retvarno];
2461
2462                 switch (retvar->dtype)
2463                 {
2464                         case PLPGSQL_DTYPE_VAR:
2465                                 {
2466                                         PLpgSQL_var *var = (PLpgSQL_var *) retvar;
2467
2468                                         estate->retval = var->value;
2469                                         estate->retisnull = var->isnull;
2470                                         estate->rettype = var->datatype->typoid;
2471                                 }
2472                                 break;
2473
2474                         case PLPGSQL_DTYPE_REC:
2475                                 {
2476                                         PLpgSQL_rec *rec = (PLpgSQL_rec *) retvar;
2477
2478                                         if (HeapTupleIsValid(rec->tup))
2479                                         {
2480                                                 estate->retval = PointerGetDatum(rec->tup);
2481                                                 estate->rettupdesc = rec->tupdesc;
2482                                                 estate->retisnull = false;
2483                                         }
2484                                 }
2485                                 break;
2486
2487                         case PLPGSQL_DTYPE_ROW:
2488                                 {
2489                                         PLpgSQL_row *row = (PLpgSQL_row *) retvar;
2490
2491                                         Assert(row->rowtupdesc);
2492                                         estate->retval =
2493                                                 PointerGetDatum(make_tuple_from_row(estate, row,
2494                                                                                                                         row->rowtupdesc));
2495                                         if (DatumGetPointer(estate->retval) == NULL)            /* should not happen */
2496                                                 elog(ERROR, "row not compatible with its own tupdesc");
2497                                         estate->rettupdesc = row->rowtupdesc;
2498                                         estate->retisnull = false;
2499                                 }
2500                                 break;
2501
2502                         default:
2503                                 elog(ERROR, "unrecognized dtype: %d", retvar->dtype);
2504                 }
2505
2506                 return PLPGSQL_RC_RETURN;
2507         }
2508
2509         if (stmt->expr != NULL)
2510         {
2511                 estate->retval = exec_eval_expr(estate, stmt->expr,
2512                                                                                 &(estate->retisnull),
2513                                                                                 &(estate->rettype));
2514
2515                 if (estate->retistuple && !estate->retisnull)
2516                 {
2517                         /* Convert composite datum to a HeapTuple and TupleDesc */
2518                         HeapTuple       tuple;
2519                         TupleDesc       tupdesc;
2520
2521                         /* Source must be of RECORD or composite type */
2522                         if (!type_is_rowtype(estate->rettype))
2523                                 ereport(ERROR,
2524                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
2525                                                  errmsg("cannot return non-composite value from function returning composite type")));
2526                         tuple = get_tuple_from_datum(estate->retval);
2527                         tupdesc = get_tupdesc_from_datum(estate->retval);
2528                         estate->retval = PointerGetDatum(tuple);
2529                         estate->rettupdesc = CreateTupleDescCopy(tupdesc);
2530                         ReleaseTupleDesc(tupdesc);
2531                 }
2532
2533                 return PLPGSQL_RC_RETURN;
2534         }
2535
2536         /*
2537          * Special hack for function returning VOID: instead of NULL, return a
2538          * non-null VOID value.  This is of dubious importance but is kept for
2539          * backwards compatibility.
2540          */
2541         if (estate->fn_rettype == VOIDOID)
2542         {
2543                 estate->retval = (Datum) 0;
2544                 estate->retisnull = false;
2545                 estate->rettype = VOIDOID;
2546         }
2547
2548         return PLPGSQL_RC_RETURN;
2549 }
2550
2551 /* ----------
2552  * exec_stmt_return_next                Evaluate an expression and add it to the
2553  *                                                              list of tuples returned by the current
2554  *                                                              SRF.
2555  * ----------
2556  */
2557 static int
2558 exec_stmt_return_next(PLpgSQL_execstate *estate,
2559                                           PLpgSQL_stmt_return_next *stmt)
2560 {
2561         TupleDesc       tupdesc;
2562         int                     natts;
2563         HeapTuple       tuple = NULL;
2564         bool            free_tuple = false;
2565
2566         if (!estate->retisset)
2567                 ereport(ERROR,
2568                                 (errcode(ERRCODE_SYNTAX_ERROR),
2569                                  errmsg("cannot use RETURN NEXT in a non-SETOF function")));
2570
2571         if (estate->tuple_store == NULL)
2572                 exec_init_tuple_store(estate);
2573
2574         /* rettupdesc will be filled by exec_init_tuple_store */
2575         tupdesc = estate->rettupdesc;
2576         natts = tupdesc->natts;
2577
2578         /*
2579          * This special-case path covers record/row variables in fn_retistuple
2580          * functions, as well as functions with one or more OUT parameters.
2581          */
2582         if (stmt->retvarno >= 0)
2583         {
2584                 PLpgSQL_datum *retvar = estate->datums[stmt->retvarno];
2585
2586                 switch (retvar->dtype)
2587                 {
2588                         case PLPGSQL_DTYPE_VAR:
2589                                 {
2590                                         PLpgSQL_var *var = (PLpgSQL_var *) retvar;
2591                                         Datum           retval = var->value;
2592                                         bool            isNull = var->isnull;
2593
2594                                         if (natts != 1)
2595                                                 ereport(ERROR,
2596                                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
2597                                                 errmsg("wrong result type supplied in RETURN NEXT")));
2598
2599                                         /* coerce type if needed */
2600                                         retval = exec_simple_cast_value(estate,
2601                                                                                                         retval,
2602                                                                                                         var->datatype->typoid,
2603                                                                                                  tupdesc->attrs[0]->atttypid,
2604                                                                                                 tupdesc->attrs[0]->atttypmod,
2605                                                                                                         isNull);
2606
2607                                         tuplestore_putvalues(estate->tuple_store, tupdesc,
2608                                                                                  &retval, &isNull);
2609                                 }
2610                                 break;
2611
2612                         case PLPGSQL_DTYPE_REC:
2613                                 {
2614                                         PLpgSQL_rec *rec = (PLpgSQL_rec *) retvar;
2615                                         TupleConversionMap *tupmap;
2616
2617                                         if (!HeapTupleIsValid(rec->tup))
2618                                                 ereport(ERROR,
2619                                                   (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2620                                                    errmsg("record \"%s\" is not assigned yet",
2621                                                                   rec->refname),
2622                                                 errdetail("The tuple structure of a not-yet-assigned"
2623                                                                   " record is indeterminate.")));
2624                                         tupmap = convert_tuples_by_position(rec->tupdesc,
2625                                                                                                                 tupdesc,
2626                                                                                                                 gettext_noop("wrong record type supplied in RETURN NEXT"));
2627                                         tuple = rec->tup;
2628                                         /* it might need conversion */
2629                                         if (tupmap)
2630                                         {
2631                                                 tuple = do_convert_tuple(tuple, tupmap);
2632                                                 free_conversion_map(tupmap);
2633                                                 free_tuple = true;
2634                                         }
2635                                 }
2636                                 break;
2637
2638                         case PLPGSQL_DTYPE_ROW:
2639                                 {
2640                                         PLpgSQL_row *row = (PLpgSQL_row *) retvar;
2641
2642                                         tuple = make_tuple_from_row(estate, row, tupdesc);
2643                                         if (tuple == NULL)
2644                                                 ereport(ERROR,
2645                                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
2646                                                 errmsg("wrong record type supplied in RETURN NEXT")));
2647                                         free_tuple = true;
2648                                 }
2649                                 break;
2650
2651                         default:
2652                                 elog(ERROR, "unrecognized dtype: %d", retvar->dtype);
2653                                 break;
2654                 }
2655         }
2656         else if (stmt->expr)
2657         {
2658                 Datum           retval;
2659                 bool            isNull;
2660                 Oid                     rettype;
2661
2662                 retval = exec_eval_expr(estate,
2663                                                                 stmt->expr,
2664                                                                 &isNull,
2665                                                                 &rettype);
2666
2667                 if (estate->retistuple)
2668                 {
2669                         /* Expression should be of RECORD or composite type */
2670                         if (!isNull)
2671                         {
2672                                 TupleDesc       retvaldesc;
2673                                 TupleConversionMap *tupmap;
2674
2675                                 if (!type_is_rowtype(rettype))
2676                                         ereport(ERROR,
2677                                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
2678                                                          errmsg("cannot return non-composite value from function returning composite type")));
2679
2680                                 tuple = get_tuple_from_datum(retval);
2681                                 free_tuple = true;              /* tuple is always freshly palloc'd */
2682
2683                                 /* it might need conversion */
2684                                 retvaldesc = get_tupdesc_from_datum(retval);
2685                                 tupmap = convert_tuples_by_position(retvaldesc, tupdesc,
2686                                                                                                         gettext_noop("returned record type does not match expected record type"));
2687                                 if (tupmap)
2688                                 {
2689                                         HeapTuple       newtuple;
2690
2691                                         newtuple = do_convert_tuple(tuple, tupmap);
2692                                         free_conversion_map(tupmap);
2693                                         heap_freetuple(tuple);
2694                                         tuple = newtuple;
2695                                 }
2696                                 ReleaseTupleDesc(retvaldesc);
2697                                 /* tuple will be stored into tuplestore below */
2698                         }
2699                         else
2700                         {
2701                                 /* Composite NULL --- store a row of nulls */
2702                                 Datum      *nulldatums;
2703                                 bool       *nullflags;
2704
2705                                 nulldatums = (Datum *) palloc0(natts * sizeof(Datum));
2706                                 nullflags = (bool *) palloc(natts * sizeof(bool));
2707                                 memset(nullflags, true, natts * sizeof(bool));
2708                                 tuplestore_putvalues(estate->tuple_store, tupdesc,
2709                                                                          nulldatums, nullflags);
2710                                 pfree(nulldatums);
2711                                 pfree(nullflags);
2712                         }
2713                 }
2714                 else
2715                 {
2716                         /* Simple scalar result */
2717                         if (natts != 1)
2718                                 ereport(ERROR,
2719                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
2720                                            errmsg("wrong result type supplied in RETURN NEXT")));
2721
2722                         /* coerce type if needed */
2723                         retval = exec_simple_cast_value(estate,
2724                                                                                         retval,
2725                                                                                         rettype,
2726                                                                                         tupdesc->attrs[0]->atttypid,
2727                                                                                         tupdesc->attrs[0]->atttypmod,
2728                                                                                         isNull);
2729
2730                         tuplestore_putvalues(estate->tuple_store, tupdesc,
2731                                                                  &retval, &isNull);
2732                 }
2733         }
2734         else
2735         {
2736                 ereport(ERROR,
2737                                 (errcode(ERRCODE_SYNTAX_ERROR),
2738                                  errmsg("RETURN NEXT must have a parameter")));
2739         }
2740
2741         if (HeapTupleIsValid(tuple))
2742         {
2743                 tuplestore_puttuple(estate->tuple_store, tuple);
2744
2745                 if (free_tuple)
2746                         heap_freetuple(tuple);
2747         }
2748
2749         exec_eval_cleanup(estate);
2750
2751         return PLPGSQL_RC_OK;
2752 }
2753
2754 /* ----------
2755  * exec_stmt_return_query               Evaluate a query and add it to the
2756  *                                                              list of tuples returned by the current
2757  *                                                              SRF.
2758  * ----------
2759  */
2760 static int
2761 exec_stmt_return_query(PLpgSQL_execstate *estate,
2762                                            PLpgSQL_stmt_return_query *stmt)
2763 {
2764         Portal          portal;
2765         uint32          processed = 0;
2766         TupleConversionMap *tupmap;
2767
2768         if (!estate->retisset)
2769                 ereport(ERROR,
2770                                 (errcode(ERRCODE_SYNTAX_ERROR),
2771                                  errmsg("cannot use RETURN QUERY in a non-SETOF function")));
2772
2773         if (estate->tuple_store == NULL)
2774                 exec_init_tuple_store(estate);
2775
2776         if (stmt->query != NULL)
2777         {
2778                 /* static query */
2779                 exec_run_select(estate, stmt->query, 0, &portal);
2780         }
2781         else
2782         {
2783                 /* RETURN QUERY EXECUTE */
2784                 Assert(stmt->dynquery != NULL);
2785                 portal = exec_dynquery_with_params(estate, stmt->dynquery,
2786                                                                                    stmt->params, NULL, 0);
2787         }
2788
2789         tupmap = convert_tuples_by_position(portal->tupDesc,
2790                                                                                 estate->rettupdesc,
2791          gettext_noop("structure of query does not match function result type"));
2792
2793         while (true)
2794         {
2795                 int                     i;
2796
2797                 SPI_cursor_fetch(portal, true, 50);
2798                 if (SPI_processed == 0)
2799                         break;
2800
2801                 for (i = 0; i < SPI_processed; i++)
2802                 {
2803                         HeapTuple       tuple = SPI_tuptable->vals[i];
2804
2805                         if (tupmap)
2806                                 tuple = do_convert_tuple(tuple, tupmap);
2807                         tuplestore_puttuple(estate->tuple_store, tuple);
2808                         if (tupmap)
2809                                 heap_freetuple(tuple);
2810                         processed++;
2811                 }
2812
2813                 SPI_freetuptable(SPI_tuptable);
2814         }
2815
2816         if (tupmap)
2817                 free_conversion_map(tupmap);
2818
2819         SPI_freetuptable(SPI_tuptable);
2820         SPI_cursor_close(portal);
2821
2822         estate->eval_processed = processed;
2823         exec_set_found(estate, processed != 0);
2824
2825         return PLPGSQL_RC_OK;
2826 }
2827
2828 static void
2829 exec_init_tuple_store(PLpgSQL_execstate *estate)
2830 {
2831         ReturnSetInfo *rsi = estate->rsi;
2832         MemoryContext oldcxt;
2833         ResourceOwner oldowner;
2834
2835         /*
2836          * Check caller can handle a set result in the way we want
2837          */
2838         if (!rsi || !IsA(rsi, ReturnSetInfo) ||
2839                 (rsi->allowedModes & SFRM_Materialize) == 0 ||
2840                 rsi->expectedDesc == NULL)
2841                 ereport(ERROR,
2842                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2843                                  errmsg("set-valued function called in context that cannot accept a set")));
2844
2845         /*
2846          * Switch to the right memory context and resource owner for storing the
2847          * tuplestore for return set. If we're within a subtransaction opened for
2848          * an exception-block, for example, we must still create the tuplestore in
2849          * the resource owner that was active when this function was entered, and
2850          * not in the subtransaction resource owner.
2851          */
2852         oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
2853         oldowner = CurrentResourceOwner;
2854         CurrentResourceOwner = estate->tuple_store_owner;
2855
2856         estate->tuple_store =
2857                 tuplestore_begin_heap(rsi->allowedModes & SFRM_Materialize_Random,
2858                                                           false, work_mem);
2859
2860         CurrentResourceOwner = oldowner;
2861         MemoryContextSwitchTo(oldcxt);
2862
2863         estate->rettupdesc = rsi->expectedDesc;
2864 }
2865
2866 #define SET_RAISE_OPTION_TEXT(opt, name) \
2867 do { \
2868         if (opt) \
2869                 ereport(ERROR, \
2870                                 (errcode(ERRCODE_SYNTAX_ERROR), \
2871                                  errmsg("RAISE option already specified: %s", \
2872                                                 name))); \
2873         opt = pstrdup(extval); \
2874 } while (0)
2875
2876 /* ----------
2877  * exec_stmt_raise                      Build a message and throw it with elog()
2878  * ----------
2879  */
2880 static int
2881 exec_stmt_raise(PLpgSQL_execstate *estate, PLpgSQL_stmt_raise *stmt)
2882 {
2883         int                     err_code = 0;
2884         char       *condname = NULL;
2885         char       *err_message = NULL;
2886         char       *err_detail = NULL;
2887         char       *err_hint = NULL;
2888         char       *err_column = NULL;
2889         char       *err_constraint = NULL;
2890         char       *err_datatype = NULL;
2891         char       *err_table = NULL;
2892         char       *err_schema = NULL;
2893         ListCell   *lc;
2894
2895         /* RAISE with no parameters: re-throw current exception */
2896         if (stmt->condname == NULL && stmt->message == NULL &&
2897                 stmt->options == NIL)
2898         {
2899                 if (estate->cur_error != NULL)
2900                         ReThrowError(estate->cur_error);
2901                 /* oops, we're not inside a handler */
2902                 ereport(ERROR,
2903                 (errcode(ERRCODE_STACKED_DIAGNOSTICS_ACCESSED_WITHOUT_ACTIVE_HANDLER),
2904                  errmsg("RAISE without parameters cannot be used outside an exception handler")));
2905         }
2906
2907         if (stmt->condname)
2908         {
2909                 err_code = plpgsql_recognize_err_condition(stmt->condname, true);
2910                 condname = pstrdup(stmt->condname);
2911         }
2912
2913         if (stmt->message)
2914         {
2915                 StringInfoData ds;
2916                 ListCell   *current_param;
2917                 char       *cp;
2918
2919                 initStringInfo(&ds);
2920                 current_param = list_head(stmt->params);
2921
2922                 for (cp = stmt->message; *cp; cp++)
2923                 {
2924                         /*
2925                          * Occurrences of a single % are replaced by the next parameter's
2926                          * external representation. Double %'s are converted to one %.
2927                          */
2928                         if (cp[0] == '%')
2929                         {
2930                                 Oid                     paramtypeid;
2931                                 Datum           paramvalue;
2932                                 bool            paramisnull;
2933                                 char       *extval;
2934
2935                                 if (cp[1] == '%')
2936                                 {
2937                                         appendStringInfoChar(&ds, '%');
2938                                         cp++;
2939                                         continue;
2940                                 }
2941
2942                                 /* should have been checked at compile time */
2943                                 if (current_param == NULL)
2944                                         elog(ERROR, "unexpected RAISE parameter list length");
2945
2946                                 paramvalue = exec_eval_expr(estate,
2947                                                                           (PLpgSQL_expr *) lfirst(current_param),
2948                                                                                         &paramisnull,
2949                                                                                         &paramtypeid);
2950
2951                                 if (paramisnull)
2952                                         extval = "<NULL>";
2953                                 else
2954                                         extval = convert_value_to_string(estate,
2955                                                                                                          paramvalue,
2956                                                                                                          paramtypeid);
2957                                 appendStringInfoString(&ds, extval);
2958                                 current_param = lnext(current_param);
2959                                 exec_eval_cleanup(estate);
2960                         }
2961                         else
2962                                 appendStringInfoChar(&ds, cp[0]);
2963                 }
2964
2965                 /* should have been checked at compile time */
2966                 if (current_param != NULL)
2967                         elog(ERROR, "unexpected RAISE parameter list length");
2968
2969                 err_message = ds.data;
2970                 /* No pfree(ds.data), the pfree(err_message) does it */
2971         }
2972
2973         foreach(lc, stmt->options)
2974         {
2975                 PLpgSQL_raise_option *opt = (PLpgSQL_raise_option *) lfirst(lc);
2976                 Datum           optionvalue;
2977                 bool            optionisnull;
2978                 Oid                     optiontypeid;
2979                 char       *extval;
2980
2981                 optionvalue = exec_eval_expr(estate, opt->expr,
2982                                                                          &optionisnull,
2983                                                                          &optiontypeid);
2984                 if (optionisnull)
2985                         ereport(ERROR,
2986                                         (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
2987                                          errmsg("RAISE statement option cannot be null")));
2988
2989                 extval = convert_value_to_string(estate, optionvalue, optiontypeid);
2990
2991                 switch (opt->opt_type)
2992                 {
2993                         case PLPGSQL_RAISEOPTION_ERRCODE:
2994                                 if (err_code)
2995                                         ereport(ERROR,
2996                                                         (errcode(ERRCODE_SYNTAX_ERROR),
2997                                                          errmsg("RAISE option already specified: %s",
2998                                                                         "ERRCODE")));
2999                                 err_code = plpgsql_recognize_err_condition(extval, true);
3000                                 condname = pstrdup(extval);
3001                                 break;
3002                         case PLPGSQL_RAISEOPTION_MESSAGE:
3003                                 SET_RAISE_OPTION_TEXT(err_message, "MESSAGE");
3004                                 break;
3005                         case PLPGSQL_RAISEOPTION_DETAIL:
3006                                 SET_RAISE_OPTION_TEXT(err_detail, "DETAIL");
3007                                 break;
3008                         case PLPGSQL_RAISEOPTION_HINT:
3009                                 SET_RAISE_OPTION_TEXT(err_hint, "HINT");
3010                                 break;
3011                         case PLPGSQL_RAISEOPTION_COLUMN:
3012                                 SET_RAISE_OPTION_TEXT(err_column, "COLUMN");
3013                                 break;
3014                         case PLPGSQL_RAISEOPTION_CONSTRAINT:
3015                                 SET_RAISE_OPTION_TEXT(err_constraint, "CONSTRAINT");
3016                                 break;
3017                         case PLPGSQL_RAISEOPTION_DATATYPE:
3018                                 SET_RAISE_OPTION_TEXT(err_datatype, "DATATYPE");
3019                                 break;
3020                         case PLPGSQL_RAISEOPTION_TABLE:
3021                                 SET_RAISE_OPTION_TEXT(err_table, "TABLE");
3022                                 break;
3023                         case PLPGSQL_RAISEOPTION_SCHEMA:
3024                                 SET_RAISE_OPTION_TEXT(err_schema, "SCHEMA");
3025                                 break;
3026                         default:
3027                                 elog(ERROR, "unrecognized raise option: %d", opt->opt_type);
3028                 }
3029
3030                 exec_eval_cleanup(estate);
3031         }
3032
3033         /* Default code if nothing specified */
3034         if (err_code == 0 && stmt->elog_level >= ERROR)
3035                 err_code = ERRCODE_RAISE_EXCEPTION;
3036
3037         /* Default error message if nothing specified */
3038         if (err_message == NULL)
3039         {
3040                 if (condname)
3041                 {
3042                         err_message = condname;
3043                         condname = NULL;
3044                 }
3045                 else
3046                         err_message = pstrdup(unpack_sql_state(err_code));
3047         }
3048
3049         /*
3050          * Throw the error (may or may not come back)
3051          */
3052         estate->err_text = raise_skip_msg;      /* suppress traceback of raise */
3053
3054         ereport(stmt->elog_level,
3055                         (err_code ? errcode(err_code) : 0,
3056                          errmsg_internal("%s", err_message),
3057                          (err_detail != NULL) ? errdetail_internal("%s", err_detail) : 0,
3058                          (err_hint != NULL) ? errhint("%s", err_hint) : 0,
3059                          (err_column != NULL) ?
3060                          err_generic_string(PG_DIAG_COLUMN_NAME, err_column) : 0,
3061                          (err_constraint != NULL) ?
3062                          err_generic_string(PG_DIAG_CONSTRAINT_NAME, err_constraint) : 0,
3063                          (err_datatype != NULL) ?
3064                          err_generic_string(PG_DIAG_DATATYPE_NAME, err_datatype) : 0,
3065                          (err_table != NULL) ?
3066                          err_generic_string(PG_DIAG_TABLE_NAME, err_table) : 0,
3067                          (err_schema != NULL) ?
3068                          err_generic_string(PG_DIAG_SCHEMA_NAME, err_schema) : 0));
3069
3070         estate->err_text = NULL;        /* un-suppress... */
3071
3072         if (condname != NULL)
3073                 pfree(condname);
3074         if (err_message != NULL)
3075                 pfree(err_message);
3076         if (err_detail != NULL)
3077                 pfree(err_detail);
3078         if (err_hint != NULL)
3079                 pfree(err_hint);
3080         if (err_column != NULL)
3081                 pfree(err_column);
3082         if (err_constraint != NULL)
3083                 pfree(err_constraint);
3084         if (err_datatype != NULL)
3085                 pfree(err_datatype);
3086         if (err_table != NULL)
3087                 pfree(err_table);
3088         if (err_schema != NULL)
3089                 pfree(err_schema);
3090
3091         return PLPGSQL_RC_OK;
3092 }
3093
3094
3095 /* ----------
3096  * Initialize a mostly empty execution state
3097  * ----------
3098  */
3099 static void
3100 plpgsql_estate_setup(PLpgSQL_execstate *estate,
3101                                          PLpgSQL_function *func,
3102                                          ReturnSetInfo *rsi,
3103                                          EState *simple_eval_estate)
3104 {
3105         /* this link will be restored at exit from plpgsql_call_handler */
3106         func->cur_estate = estate;
3107
3108         estate->func = func;
3109
3110         estate->retval = (Datum) 0;
3111         estate->retisnull = true;
3112         estate->rettype = InvalidOid;
3113
3114         estate->fn_rettype = func->fn_rettype;
3115         estate->retistuple = func->fn_retistuple;
3116         estate->retisset = func->fn_retset;
3117
3118         estate->readonly_func = func->fn_readonly;
3119
3120         estate->rettupdesc = NULL;
3121         estate->exitlabel = NULL;
3122         estate->cur_error = NULL;
3123
3124         estate->tuple_store = NULL;
3125         if (rsi)
3126         {
3127                 estate->tuple_store_cxt = rsi->econtext->ecxt_per_query_memory;
3128                 estate->tuple_store_owner = CurrentResourceOwner;
3129         }
3130         else
3131         {
3132                 estate->tuple_store_cxt = NULL;
3133                 estate->tuple_store_owner = NULL;
3134         }
3135         estate->rsi = rsi;
3136
3137         estate->found_varno = func->found_varno;
3138         estate->ndatums = func->ndatums;
3139         estate->datums = palloc(sizeof(PLpgSQL_datum *) * estate->ndatums);
3140         /* caller is expected to fill the datums array */
3141
3142         /* set up for use of appropriate simple-expression EState */
3143         if (simple_eval_estate)
3144                 estate->simple_eval_estate = simple_eval_estate;
3145         else
3146                 estate->simple_eval_estate = shared_simple_eval_estate;
3147
3148         estate->eval_tuptable = NULL;
3149         estate->eval_processed = 0;
3150         estate->eval_lastoid = InvalidOid;
3151         estate->eval_econtext = NULL;
3152         estate->cur_expr = NULL;
3153
3154         estate->err_stmt = NULL;
3155         estate->err_text = NULL;
3156
3157         estate->plugin_info = NULL;
3158
3159         /*
3160          * Create an EState and ExprContext for evaluation of simple expressions.
3161          */
3162         plpgsql_create_econtext(estate);
3163
3164         /*
3165          * Let the plugin see this function before we initialize any local
3166          * PL/pgSQL variables - note that we also give the plugin a few function
3167          * pointers so it can call back into PL/pgSQL for doing things like
3168          * variable assignments and stack traces
3169          */
3170         if (*plugin_ptr)
3171         {
3172                 (*plugin_ptr)->error_callback = plpgsql_exec_error_callback;
3173                 (*plugin_ptr)->assign_expr = exec_assign_expr;
3174
3175                 if ((*plugin_ptr)->func_setup)
3176                         ((*plugin_ptr)->func_setup) (estate, func);
3177         }
3178 }
3179
3180 /* ----------
3181  * Release temporary memory used by expression/subselect evaluation
3182  *
3183  * NB: the result of the evaluation is no longer valid after this is done,
3184  * unless it is a pass-by-value datatype.
3185  *
3186  * NB: if you change this code, see also the hacks in exec_assign_value's
3187  * PLPGSQL_DTYPE_ARRAYELEM case.
3188  * ----------
3189  */
3190 static void
3191 exec_eval_cleanup(PLpgSQL_execstate *estate)
3192 {
3193         /* Clear result of a full SPI_execute */
3194         if (estate->eval_tuptable != NULL)
3195                 SPI_freetuptable(estate->eval_tuptable);
3196         estate->eval_tuptable = NULL;
3197
3198         /* Clear result of exec_eval_simple_expr (but keep the econtext) */
3199         if (estate->eval_econtext != NULL)
3200                 ResetExprContext(estate->eval_econtext);
3201 }
3202
3203
3204 /* ----------
3205  * Generate a prepared plan
3206  * ----------
3207  */
3208 static void
3209 exec_prepare_plan(PLpgSQL_execstate *estate,
3210                                   PLpgSQL_expr *expr, int cursorOptions)
3211 {
3212         SPIPlanPtr      plan;
3213
3214         /*
3215          * The grammar can't conveniently set expr->func while building the parse
3216          * tree, so make sure it's set before parser hooks need it.
3217          */
3218         expr->func = estate->func;
3219
3220         /*
3221          * Generate and save the plan
3222          */
3223         plan = SPI_prepare_params(expr->query,
3224                                                           (ParserSetupHook) plpgsql_parser_setup,
3225                                                           (void *) expr,
3226                                                           cursorOptions);
3227         if (plan == NULL)
3228         {
3229                 /* Some SPI errors deserve specific error messages */
3230                 switch (SPI_result)
3231                 {
3232                         case SPI_ERROR_COPY:
3233                                 ereport(ERROR,
3234                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3235                                                  errmsg("cannot COPY to/from client in PL/pgSQL")));
3236                         case SPI_ERROR_TRANSACTION:
3237                                 ereport(ERROR,
3238                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3239                                                  errmsg("cannot begin/end transactions in PL/pgSQL"),
3240                                                  errhint("Use a BEGIN block with an EXCEPTION clause instead.")));
3241                         default:
3242                                 elog(ERROR, "SPI_prepare_params failed for \"%s\": %s",
3243                                          expr->query, SPI_result_code_string(SPI_result));
3244                 }
3245         }
3246         SPI_keepplan(plan);
3247         expr->plan = plan;
3248
3249         /* Check to see if it's a simple expression */
3250         exec_simple_check_plan(expr);
3251 }
3252
3253
3254 /* ----------
3255  * exec_stmt_execsql                    Execute an SQL statement (possibly with INTO).
3256  * ----------
3257  */
3258 static int
3259 exec_stmt_execsql(PLpgSQL_execstate *estate,
3260                                   PLpgSQL_stmt_execsql *stmt)
3261 {
3262         ParamListInfo paramLI;
3263         long            tcount;
3264         int                     rc;
3265         PLpgSQL_expr *expr = stmt->sqlstmt;
3266
3267         /*
3268          * On the first call for this statement generate the plan, and detect
3269          * whether the statement is INSERT/UPDATE/DELETE
3270          */
3271         if (expr->plan == NULL)
3272         {
3273                 ListCell   *l;
3274
3275                 exec_prepare_plan(estate, expr, 0);
3276                 stmt->mod_stmt = false;
3277                 foreach(l, SPI_plan_get_plan_sources(expr->plan))
3278                 {
3279                         CachedPlanSource *plansource = (CachedPlanSource *) lfirst(l);
3280                         ListCell   *l2;
3281
3282                         foreach(l2, plansource->query_list)
3283                         {
3284                                 Query      *q = (Query *) lfirst(l2);
3285
3286                                 Assert(IsA(q, Query));
3287                                 if (q->canSetTag)
3288                                 {
3289                                         if (q->commandType == CMD_INSERT ||
3290                                                 q->commandType == CMD_UPDATE ||
3291                                                 q->commandType == CMD_DELETE)
3292                                                 stmt->mod_stmt = true;
3293                                 }
3294                         }
3295                 }
3296         }
3297
3298         /*
3299          * Set up ParamListInfo (hook function and possibly data values)
3300          */
3301         paramLI = setup_param_list(estate, expr);
3302
3303         /*
3304          * If we have INTO, then we only need one row back ... but if we have INTO
3305          * STRICT, ask for two rows, so that we can verify the statement returns
3306          * only one.  INSERT/UPDATE/DELETE are always treated strictly. Without
3307          * INTO, just run the statement to completion (tcount = 0).
3308          *
3309          * We could just ask for two rows always when using INTO, but there are
3310          * some cases where demanding the extra row costs significant time, eg by
3311          * forcing completion of a sequential scan.  So don't do it unless we need
3312          * to enforce strictness.
3313          */
3314         if (stmt->into)
3315         {
3316                 if (stmt->strict || stmt->mod_stmt)
3317                         tcount = 2;
3318                 else
3319                         tcount = 1;
3320         }
3321         else
3322                 tcount = 0;
3323
3324         /*
3325          * Execute the plan
3326          */
3327         rc = SPI_execute_plan_with_paramlist(expr->plan, paramLI,
3328                                                                                  estate->readonly_func, tcount);
3329
3330         /*
3331          * Check for error, and set FOUND if appropriate (for historical reasons
3332          * we set FOUND only for certain query types).  Also Assert that we
3333          * identified the statement type the same as SPI did.
3334          */
3335         switch (rc)
3336         {
3337                 case SPI_OK_SELECT:
3338                         Assert(!stmt->mod_stmt);
3339                         exec_set_found(estate, (SPI_processed != 0));
3340                         break;
3341
3342                 case SPI_OK_INSERT:
3343                 case SPI_OK_UPDATE:
3344                 case SPI_OK_DELETE:
3345                 case SPI_OK_INSERT_RETURNING:
3346                 case SPI_OK_UPDATE_RETURNING:
3347                 case SPI_OK_DELETE_RETURNING:
3348                         Assert(stmt->mod_stmt);
3349                         exec_set_found(estate, (SPI_processed != 0));
3350                         break;
3351
3352                 case SPI_OK_SELINTO:
3353                 case SPI_OK_UTILITY:
3354                         Assert(!stmt->mod_stmt);
3355                         break;
3356
3357                 case SPI_OK_REWRITTEN:
3358                         Assert(!stmt->mod_stmt);
3359
3360                         /*
3361                          * The command was rewritten into another kind of command. It's
3362                          * not clear what FOUND would mean in that case (and SPI doesn't
3363                          * return the row count either), so just set it to false.
3364                          */
3365                         exec_set_found(estate, false);
3366                         break;
3367
3368                         /* Some SPI errors deserve specific error messages */
3369                 case SPI_ERROR_COPY:
3370                         ereport(ERROR,
3371                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3372                                          errmsg("cannot COPY to/from client in PL/pgSQL")));
3373                 case SPI_ERROR_TRANSACTION:
3374                         ereport(ERROR,
3375                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3376                                          errmsg("cannot begin/end transactions in PL/pgSQL"),
3377                         errhint("Use a BEGIN block with an EXCEPTION clause instead.")));
3378
3379                 default:
3380                         elog(ERROR, "SPI_execute_plan_with_paramlist failed executing query \"%s\": %s",
3381                                  expr->query, SPI_result_code_string(rc));
3382         }
3383
3384         /* All variants should save result info for GET DIAGNOSTICS */
3385         estate->eval_processed = SPI_processed;
3386         estate->eval_lastoid = SPI_lastoid;
3387
3388         /* Process INTO if present */
3389         if (stmt->into)
3390         {
3391                 SPITupleTable *tuptab = SPI_tuptable;
3392                 uint32          n = SPI_processed;
3393                 PLpgSQL_rec *rec = NULL;
3394                 PLpgSQL_row *row = NULL;
3395
3396                 /* If the statement did not return a tuple table, complain */
3397                 if (tuptab == NULL)
3398                         ereport(ERROR,
3399                                         (errcode(ERRCODE_SYNTAX_ERROR),
3400                                 errmsg("INTO used with a command that cannot return data")));
3401
3402                 /* Determine if we assign to a record or a row */
3403                 if (stmt->rec != NULL)
3404                         rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->dno]);
3405                 else if (stmt->row != NULL)
3406                         row = (PLpgSQL_row *) (estate->datums[stmt->row->dno]);
3407                 else
3408                         elog(ERROR, "unsupported target");
3409
3410                 /*
3411                  * If SELECT ... INTO specified STRICT, and the query didn't find
3412                  * exactly one row, throw an error.  If STRICT was not specified, then
3413                  * allow the query to find any number of rows.
3414                  */
3415                 if (n == 0)
3416                 {
3417                         if (stmt->strict)
3418                         {
3419                                 char       *errdetail;
3420
3421                                 if (estate->func->print_strict_params)
3422                                         errdetail = format_expr_params(estate, expr);
3423                                 else
3424                                         errdetail = NULL;
3425
3426                                 ereport(ERROR,
3427                                                 (errcode(ERRCODE_NO_DATA_FOUND),
3428                                                  errmsg("query returned no rows"),
3429                                                  errdetail ? errdetail_internal("parameters: %s", errdetail) : 0));
3430                         }
3431                         /* set the target to NULL(s) */
3432                         exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
3433                 }
3434                 else
3435                 {
3436                         if (n > 1 && (stmt->strict || stmt->mod_stmt))
3437                         {
3438                                 char       *errdetail;
3439
3440                                 if (estate->func->print_strict_params)
3441                                         errdetail = format_expr_params(estate, expr);
3442                                 else
3443                                         errdetail = NULL;
3444
3445                                 ereport(ERROR,
3446                                                 (errcode(ERRCODE_TOO_MANY_ROWS),
3447                                                  errmsg("query returned more than one row"),
3448                                                  errdetail ? errdetail_internal("parameters: %s", errdetail) : 0));
3449                         }
3450                         /* Put the first result row into the target */
3451                         exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
3452                 }
3453
3454                 /* Clean up */
3455                 exec_eval_cleanup(estate);
3456                 SPI_freetuptable(SPI_tuptable);
3457         }
3458         else
3459         {
3460                 /* If the statement returned a tuple table, complain */
3461                 if (SPI_tuptable != NULL)
3462                         ereport(ERROR,
3463                                         (errcode(ERRCODE_SYNTAX_ERROR),
3464                                          errmsg("query has no destination for result data"),
3465                                          (rc == SPI_OK_SELECT) ? errhint("If you want to discard the results of a SELECT, use PERFORM instead.") : 0));
3466         }
3467
3468         if (paramLI)
3469                 pfree(paramLI);
3470
3471         return PLPGSQL_RC_OK;
3472 }
3473
3474
3475 /* ----------
3476  * exec_stmt_dynexecute                 Execute a dynamic SQL query
3477  *                                      (possibly with INTO).
3478  * ----------
3479  */
3480 static int
3481 exec_stmt_dynexecute(PLpgSQL_execstate *estate,
3482                                          PLpgSQL_stmt_dynexecute *stmt)
3483 {
3484         Datum           query;
3485         bool            isnull = false;
3486         Oid                     restype;
3487         char       *querystr;
3488         int                     exec_res;
3489         PreparedParamsData *ppd = NULL;
3490
3491         /*
3492          * First we evaluate the string expression after the EXECUTE keyword. Its
3493          * result is the querystring we have to execute.
3494          */
3495         query = exec_eval_expr(estate, stmt->query, &isnull, &restype);
3496         if (isnull)
3497                 ereport(ERROR,
3498                                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3499                                  errmsg("query string argument of EXECUTE is null")));
3500
3501         /* Get the C-String representation */
3502         querystr = convert_value_to_string(estate, query, restype);
3503
3504         /* copy it out of the temporary context before we clean up */
3505         querystr = pstrdup(querystr);
3506
3507         exec_eval_cleanup(estate);
3508
3509         /*
3510          * Execute the query without preparing a saved plan.
3511          */
3512         if (stmt->params)
3513         {
3514                 ppd = exec_eval_using_params(estate, stmt->params);
3515                 exec_res = SPI_execute_with_args(querystr,
3516                                                                                  ppd->nargs, ppd->types,
3517                                                                                  ppd->values, ppd->nulls,
3518                                                                                  estate->readonly_func, 0);
3519         }
3520         else
3521                 exec_res = SPI_execute(querystr, estate->readonly_func, 0);
3522
3523         switch (exec_res)
3524         {
3525                 case SPI_OK_SELECT:
3526                 case SPI_OK_INSERT:
3527                 case SPI_OK_UPDATE:
3528                 case SPI_OK_DELETE:
3529                 case SPI_OK_INSERT_RETURNING:
3530                 case SPI_OK_UPDATE_RETURNING:
3531                 case SPI_OK_DELETE_RETURNING:
3532                 case SPI_OK_UTILITY:
3533                 case SPI_OK_REWRITTEN:
3534                         break;
3535
3536                 case 0:
3537
3538                         /*
3539                          * Also allow a zero return, which implies the querystring
3540                          * contained no commands.
3541                          */
3542                         break;
3543
3544                 case SPI_OK_SELINTO:
3545
3546                         /*
3547                          * We want to disallow SELECT INTO for now, because its behavior
3548                          * is not consistent with SELECT INTO in a normal plpgsql context.
3549                          * (We need to reimplement EXECUTE to parse the string as a
3550                          * plpgsql command, not just feed it to SPI_execute.)  This is not
3551                          * a functional limitation because CREATE TABLE AS is allowed.
3552                          */
3553                         ereport(ERROR,
3554                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3555                                          errmsg("EXECUTE of SELECT ... INTO is not implemented"),
3556                                          errhint("You might want to use EXECUTE ... INTO or EXECUTE CREATE TABLE ... AS instead.")));
3557                         break;
3558
3559                         /* Some SPI errors deserve specific error messages */
3560                 case SPI_ERROR_COPY:
3561                         ereport(ERROR,
3562                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3563                                          errmsg("cannot COPY to/from client in PL/pgSQL")));
3564                 case SPI_ERROR_TRANSACTION:
3565                         ereport(ERROR,
3566                                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3567                                          errmsg("cannot begin/end transactions in PL/pgSQL"),
3568                         errhint("Use a BEGIN block with an EXCEPTION clause instead.")));
3569
3570                 default:
3571                         elog(ERROR, "SPI_execute failed executing query \"%s\": %s",
3572                                  querystr, SPI_result_code_string(exec_res));
3573                         break;
3574         }
3575
3576         /* Save result info for GET DIAGNOSTICS */
3577         estate->eval_processed = SPI_processed;
3578         estate->eval_lastoid = SPI_lastoid;
3579
3580         /* Process INTO if present */
3581         if (stmt->into)
3582         {
3583                 SPITupleTable *tuptab = SPI_tuptable;
3584                 uint32          n = SPI_processed;
3585                 PLpgSQL_rec *rec = NULL;
3586                 PLpgSQL_row *row = NULL;
3587
3588                 /* If the statement did not return a tuple table, complain */
3589                 if (tuptab == NULL)
3590                         ereport(ERROR,
3591                                         (errcode(ERRCODE_SYNTAX_ERROR),
3592                                 errmsg("INTO used with a command that cannot return data")));
3593
3594                 /* Determine if we assign to a record or a row */
3595                 if (stmt->rec != NULL)
3596                         rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->dno]);
3597                 else if (stmt->row != NULL)
3598                         row = (PLpgSQL_row *) (estate->datums[stmt->row->dno]);
3599                 else
3600                         elog(ERROR, "unsupported target");
3601
3602                 /*
3603                  * If SELECT ... INTO specified STRICT, and the query didn't find
3604                  * exactly one row, throw an error.  If STRICT was not specified, then
3605                  * allow the query to find any number of rows.
3606                  */
3607                 if (n == 0)
3608                 {
3609                         if (stmt->strict)
3610                         {
3611                                 char       *errdetail;
3612
3613                                 if (estate->func->print_strict_params)
3614                                         errdetail = format_preparedparamsdata(estate, ppd);
3615                                 else
3616                                         errdetail = NULL;
3617
3618                                 ereport(ERROR,
3619                                                 (errcode(ERRCODE_NO_DATA_FOUND),
3620                                                  errmsg("query returned no rows"),
3621                                                  errdetail ? errdetail_internal("parameters: %s", errdetail) : 0));
3622                         }
3623                         /* set the target to NULL(s) */
3624                         exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
3625                 }
3626                 else
3627                 {
3628                         if (n > 1 && stmt->strict)
3629                         {
3630                                 char       *errdetail;
3631
3632                                 if (estate->func->print_strict_params)
3633                                         errdetail = format_preparedparamsdata(estate, ppd);
3634                                 else
3635                                         errdetail = NULL;
3636
3637                                 ereport(ERROR,
3638                                                 (errcode(ERRCODE_TOO_MANY_ROWS),
3639                                                  errmsg("query returned more than one row"),
3640                                                  errdetail ? errdetail_internal("parameters: %s", errdetail) : 0));
3641                         }
3642
3643                         /* Put the first result row into the target */
3644                         exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
3645                 }
3646                 /* clean up after exec_move_row() */
3647                 exec_eval_cleanup(estate);
3648         }
3649         else
3650         {
3651                 /*
3652                  * It might be a good idea to raise an error if the query returned
3653                  * tuples that are being ignored, but historically we have not done
3654                  * that.
3655                  */
3656         }
3657
3658         if (ppd)
3659                 free_params_data(ppd);
3660
3661         /* Release any result from SPI_execute, as well as the querystring */
3662         SPI_freetuptable(SPI_tuptable);
3663         pfree(querystr);
3664
3665         return PLPGSQL_RC_OK;
3666 }
3667
3668
3669 /* ----------
3670  * exec_stmt_dynfors                    Execute a dynamic query, assign each
3671  *                                      tuple to a record or row and
3672  *                                      execute a group of statements
3673  *                                      for it.
3674  * ----------
3675  */
3676 static int
3677 exec_stmt_dynfors(PLpgSQL_execstate *estate, PLpgSQL_stmt_dynfors *stmt)
3678 {
3679         Portal          portal;
3680         int                     rc;
3681
3682         portal = exec_dynquery_with_params(estate, stmt->query, stmt->params,
3683                                                                            NULL, 0);
3684
3685         /*
3686          * Execute the loop
3687          */
3688         rc = exec_for_query(estate, (PLpgSQL_stmt_forq *) stmt, portal, true);
3689
3690         /*
3691          * Close the implicit cursor
3692          */
3693         SPI_cursor_close(portal);
3694
3695         return rc;
3696 }
3697
3698
3699 /* ----------
3700  * exec_stmt_open                       Execute an OPEN cursor statement
3701  * ----------
3702  */
3703 static int
3704 exec_stmt_open(PLpgSQL_execstate *estate, PLpgSQL_stmt_open *stmt)
3705 {
3706         PLpgSQL_var *curvar;
3707         char       *curname = NULL;
3708         PLpgSQL_expr *query;
3709         Portal          portal;
3710         ParamListInfo paramLI;
3711
3712         /* ----------
3713          * Get the cursor variable and if it has an assigned name, check
3714          * that it's not in use currently.
3715          * ----------
3716          */
3717         curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
3718         if (!curvar->isnull)
3719         {
3720                 curname = TextDatumGetCString(curvar->value);
3721                 if (SPI_cursor_find(curname) != NULL)
3722                         ereport(ERROR,
3723                                         (errcode(ERRCODE_DUPLICATE_CURSOR),
3724                                          errmsg("cursor \"%s\" already in use", curname)));
3725         }
3726
3727         /* ----------
3728          * Process the OPEN according to it's type.
3729          * ----------
3730          */
3731         if (stmt->query != NULL)
3732         {
3733                 /* ----------
3734                  * This is an OPEN refcursor FOR SELECT ...
3735                  *
3736                  * We just make sure the query is planned. The real work is
3737                  * done downstairs.
3738                  * ----------
3739                  */
3740                 query = stmt->query;
3741                 if (query->plan == NULL)
3742                         exec_prepare_plan(estate, query, stmt->cursor_options);
3743         }
3744         else if (stmt->dynquery != NULL)
3745         {
3746                 /* ----------
3747                  * This is an OPEN refcursor FOR EXECUTE ...
3748                  * ----------
3749                  */
3750                 portal = exec_dynquery_with_params(estate,
3751                                                                                    stmt->dynquery,
3752                                                                                    stmt->params,
3753                                                                                    curname,
3754                                                                                    stmt->cursor_options);
3755
3756                 /*
3757                  * If cursor variable was NULL, store the generated portal name in it
3758                  */
3759                 if (curname == NULL)
3760                         assign_text_var(curvar, portal->name);
3761
3762                 return PLPGSQL_RC_OK;
3763         }
3764         else
3765         {
3766                 /* ----------
3767                  * This is an OPEN cursor
3768                  *
3769                  * Note: parser should already have checked that statement supplies
3770                  * args iff cursor needs them, but we check again to be safe.
3771                  * ----------
3772                  */
3773                 if (stmt->argquery != NULL)
3774                 {
3775                         /* ----------
3776                          * OPEN CURSOR with args.  We fake a SELECT ... INTO ...
3777                          * statement to evaluate the args and put 'em into the
3778                          * internal row.
3779                          * ----------
3780                          */
3781                         PLpgSQL_stmt_execsql set_args;
3782
3783                         if (curvar->cursor_explicit_argrow < 0)
3784                                 ereport(ERROR,
3785                                                 (errcode(ERRCODE_SYNTAX_ERROR),
3786                                         errmsg("arguments given for cursor without arguments")));
3787
3788                         memset(&set_args, 0, sizeof(set_args));
3789                         set_args.cmd_type = PLPGSQL_STMT_EXECSQL;
3790                         set_args.lineno = stmt->lineno;
3791                         set_args.sqlstmt = stmt->argquery;
3792                         set_args.into = true;
3793                         /* XXX historically this has not been STRICT */
3794                         set_args.row = (PLpgSQL_row *)
3795                                 (estate->datums[curvar->cursor_explicit_argrow]);
3796
3797                         if (exec_stmt_execsql(estate, &set_args) != PLPGSQL_RC_OK)
3798                                 elog(ERROR, "open cursor failed during argument processing");
3799                 }
3800                 else
3801                 {
3802                         if (curvar->cursor_explicit_argrow >= 0)
3803                                 ereport(ERROR,
3804                                                 (errcode(ERRCODE_SYNTAX_ERROR),
3805                                                  errmsg("arguments required for cursor")));
3806                 }
3807
3808                 query = curvar->cursor_explicit_expr;
3809                 if (query->plan == NULL)
3810                         exec_prepare_plan(estate, query, curvar->cursor_options);
3811         }
3812
3813         /*
3814          * Set up ParamListInfo (hook function and possibly data values)
3815          */
3816         paramLI = setup_param_list(estate, query);
3817
3818         /*
3819          * Open the cursor
3820          */
3821         portal = SPI_cursor_open_with_paramlist(curname, query->plan,
3822                                                                                         paramLI,
3823                                                                                         estate->readonly_func);
3824         if (portal == NULL)
3825                 elog(ERROR, "could not open cursor: %s",
3826                          SPI_result_code_string(SPI_result));
3827
3828         /*
3829          * If cursor variable was NULL, store the generated portal name in it
3830          */
3831         if (curname == NULL)
3832                 assign_text_var(curvar, portal->name);
3833
3834         if (curname)
3835                 pfree(curname);
3836         if (paramLI)
3837                 pfree(paramLI);
3838
3839         return PLPGSQL_RC_OK;
3840 }
3841
3842
3843 /* ----------
3844  * exec_stmt_fetch                      Fetch from a cursor into a target, or just
3845  *                                                      move the current position of the cursor
3846  * ----------
3847  */
3848 static int
3849 exec_stmt_fetch(PLpgSQL_execstate *estate, PLpgSQL_stmt_fetch *stmt)
3850 {
3851         PLpgSQL_var *curvar = NULL;
3852         PLpgSQL_rec *rec = NULL;
3853         PLpgSQL_row *row = NULL;
3854         long            how_many = stmt->how_many;
3855         SPITupleTable *tuptab;
3856         Portal          portal;
3857         char       *curname;
3858         uint32          n;
3859
3860         /* ----------
3861          * Get the portal of the cursor by name
3862          * ----------
3863          */
3864         curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
3865         if (curvar->isnull)
3866                 ereport(ERROR,
3867                                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3868                                  errmsg("cursor variable \"%s\" is null", curvar->refname)));
3869         curname = TextDatumGetCString(curvar->value);
3870
3871         portal = SPI_cursor_find(curname);
3872         if (portal == NULL)
3873                 ereport(ERROR,
3874                                 (errcode(ERRCODE_UNDEFINED_CURSOR),
3875                                  errmsg("cursor \"%s\" does not exist", curname)));
3876         pfree(curname);
3877
3878         /* Calculate position for FETCH_RELATIVE or FETCH_ABSOLUTE */
3879         if (stmt->expr)
3880         {
3881                 bool            isnull;
3882
3883                 /* XXX should be doing this in LONG not INT width */
3884                 how_many = exec_eval_integer(estate, stmt->expr, &isnull);
3885
3886                 if (isnull)
3887                         ereport(ERROR,
3888                                         (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3889                                          errmsg("relative or absolute cursor position is null")));
3890
3891                 exec_eval_cleanup(estate);
3892         }
3893
3894         if (!stmt->is_move)
3895         {
3896                 /* ----------
3897                  * Determine if we fetch into a record or a row
3898                  * ----------
3899                  */
3900                 if (stmt->rec != NULL)
3901                         rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->dno]);
3902                 else if (stmt->row != NULL)
3903                         row = (PLpgSQL_row *) (estate->datums[stmt->row->dno]);
3904                 else
3905                         elog(ERROR, "unsupported target");
3906
3907                 /* ----------
3908                  * Fetch 1 tuple from the cursor
3909                  * ----------
3910                  */
3911                 SPI_scroll_cursor_fetch(portal, stmt->direction, how_many);
3912                 tuptab = SPI_tuptable;
3913                 n = SPI_processed;
3914
3915                 /* ----------
3916                  * Set the target appropriately.
3917                  * ----------
3918                  */
3919                 if (n == 0)
3920                         exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
3921                 else
3922                         exec_move_row(estate, rec, row, tuptab->vals[0], tuptab->tupdesc);
3923
3924                 exec_eval_cleanup(estate);
3925                 SPI_freetuptable(tuptab);
3926         }
3927         else
3928         {
3929                 /* Move the cursor */
3930                 SPI_scroll_cursor_move(portal, stmt->direction, how_many);
3931                 n = SPI_processed;
3932         }
3933
3934         /* Set the ROW_COUNT and the global FOUND variable appropriately. */
3935         estate->eval_processed = n;
3936         exec_set_found(estate, n != 0);
3937
3938         return PLPGSQL_RC_OK;
3939 }
3940
3941 /* ----------
3942  * exec_stmt_close                      Close a cursor
3943  * ----------
3944  */
3945 static int
3946 exec_stmt_close(PLpgSQL_execstate *estate, PLpgSQL_stmt_close *stmt)
3947 {
3948         PLpgSQL_var *curvar = NULL;
3949         Portal          portal;
3950         char       *curname;
3951
3952         /* ----------
3953          * Get the portal of the cursor by name
3954          * ----------
3955          */
3956         curvar = (PLpgSQL_var *) (estate->datums[stmt->curvar]);
3957         if (curvar->isnull)
3958                 ereport(ERROR,
3959                                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
3960                                  errmsg("cursor variable \"%s\" is null", curvar->refname)));
3961         curname = TextDatumGetCString(curvar->value);
3962
3963         portal = SPI_cursor_find(curname);
3964         if (portal == NULL)
3965                 ereport(ERROR,
3966                                 (errcode(ERRCODE_UNDEFINED_CURSOR),
3967                                  errmsg("cursor \"%s\" does not exist", curname)));
3968         pfree(curname);
3969
3970         /* ----------
3971          * And close it.
3972          * ----------
3973          */
3974         SPI_cursor_close(portal);
3975
3976         return PLPGSQL_RC_OK;
3977 }
3978
3979
3980 /* ----------
3981  * exec_assign_expr                     Put an expression's result into a variable.
3982  * ----------
3983  */
3984 static void
3985 exec_assign_expr(PLpgSQL_execstate *estate, PLpgSQL_datum *target,
3986                                  PLpgSQL_expr *expr)
3987 {
3988         Datum           value;
3989         Oid                     valtype;
3990         bool            isnull = false;
3991
3992         value = exec_eval_expr(estate, expr, &isnull, &valtype);
3993         exec_assign_value(estate, target, value, valtype, &isnull);
3994         exec_eval_cleanup(estate);
3995 }
3996
3997
3998 /* ----------
3999  * exec_assign_c_string         Put a C string into a text variable.
4000  *
4001  * We take a NULL pointer as signifying empty string, not SQL null.
4002  * ----------
4003  */
4004 static void
4005 exec_assign_c_string(PLpgSQL_execstate *estate, PLpgSQL_datum *target,
4006                                          const char *str)
4007 {
4008         text       *value;
4009         bool            isnull = false;
4010
4011         if (str != NULL)
4012                 value = cstring_to_text(str);
4013         else
4014                 value = cstring_to_text("");
4015         exec_assign_value(estate, target, PointerGetDatum(value),
4016                                           TEXTOID, &isnull);
4017         pfree(value);
4018 }
4019
4020
4021 /* ----------
4022  * exec_assign_value                    Put a value into a target field
4023  *
4024  * Note: in some code paths, this will leak memory in the eval_econtext;
4025  * we assume that will be cleaned up later by exec_eval_cleanup.  We cannot
4026  * call exec_eval_cleanup here for fear of destroying the input Datum value.
4027  * ----------
4028  */
4029 static void
4030 exec_assign_value(PLpgSQL_execstate *estate,
4031                                   PLpgSQL_datum *target,
4032                                   Datum value, Oid valtype, bool *isNull)
4033 {
4034         switch (target->dtype)
4035         {
4036                 case PLPGSQL_DTYPE_VAR:
4037                         {
4038                                 /*
4039                                  * Target is a variable
4040                                  */
4041                                 PLpgSQL_var *var = (PLpgSQL_var *) target;
4042                                 Datum           newvalue;
4043
4044                                 newvalue = exec_cast_value(estate,
4045                                                                                    value,
4046                                                                                    valtype,
4047                                                                                    var->datatype->typoid,
4048                                                                                    &(var->datatype->typinput),
4049                                                                                    var->datatype->typioparam,
4050                                                                                    var->datatype->atttypmod,
4051                                                                                    *isNull);
4052
4053                                 if (*isNull && var->notnull)
4054                                         ereport(ERROR,
4055                                                         (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
4056                                                          errmsg("null value cannot be assigned to variable \"%s\" declared NOT NULL",
4057                                                                         var->refname)));
4058
4059                                 /*
4060                                  * If type is by-reference, copy the new value (which is
4061                                  * probably in the eval_econtext) into the procedure's memory
4062                                  * context.
4063                                  */
4064                                 if (!var->datatype->typbyval && !*isNull)
4065                                         newvalue = datumCopy(newvalue,
4066                                                                                  false,
4067                                                                                  var->datatype->typlen);
4068
4069                                 /*
4070                                  * Now free the old value.  (We can't do this any earlier
4071                                  * because of the possibility that we are assigning the var's
4072                                  * old value to it, eg "foo := foo".  We could optimize out
4073                                  * the assignment altogether in such cases, but it's too
4074                                  * infrequent to be worth testing for.)
4075                                  */
4076                                 free_var(var);
4077
4078                                 var->value = newvalue;
4079                                 var->isnull = *isNull;
4080                                 if (!var->datatype->typbyval && !*isNull)
4081                                         var->freeval = true;
4082                                 break;
4083                         }
4084
4085                 case PLPGSQL_DTYPE_ROW:
4086                         {
4087                                 /*
4088                                  * Target is a row variable
4089                                  */
4090                                 PLpgSQL_row *row = (PLpgSQL_row *) target;
4091
4092                                 if (*isNull)
4093                                 {
4094                                         /* If source is null, just assign nulls to the row */
4095                                         exec_move_row(estate, NULL, row, NULL, NULL);
4096                                 }
4097                                 else
4098                                 {
4099                                         /* Source must be of RECORD or composite type */
4100                                         if (!type_is_rowtype(valtype))
4101                                                 ereport(ERROR,
4102                                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
4103                                                                  errmsg("cannot assign non-composite value to a row variable")));
4104                                         exec_move_row_from_datum(estate, NULL, row, value);
4105                                 }
4106                                 break;
4107                         }
4108
4109                 case PLPGSQL_DTYPE_REC:
4110                         {
4111                                 /*
4112                                  * Target is a record variable
4113                                  */
4114                                 PLpgSQL_rec *rec = (PLpgSQL_rec *) target;
4115
4116                                 if (*isNull)
4117                                 {
4118                                         /* If source is null, just assign nulls to the record */
4119                                         exec_move_row(estate, rec, NULL, NULL, NULL);
4120                                 }
4121                                 else
4122                                 {
4123                                         /* Source must be of RECORD or composite type */
4124                                         if (!type_is_rowtype(valtype))
4125                                                 ereport(ERROR,
4126                                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
4127                                                                  errmsg("cannot assign non-composite value to a record variable")));
4128                                         exec_move_row_from_datum(estate, rec, NULL, value);
4129                                 }
4130                                 break;
4131                         }
4132
4133                 case PLPGSQL_DTYPE_RECFIELD:
4134                         {
4135                                 /*
4136                                  * Target is a field of a record
4137                                  */
4138                                 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) target;
4139                                 PLpgSQL_rec *rec;
4140                                 int                     fno;
4141                                 HeapTuple       newtup;
4142                                 int                     natts;
4143                                 Datum      *values;
4144                                 bool       *nulls;
4145                                 bool       *replaces;
4146                                 bool            attisnull;
4147                                 Oid                     atttype;
4148                                 int32           atttypmod;
4149
4150                                 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
4151
4152                                 /*
4153                                  * Check that there is already a tuple in the record. We need
4154                                  * that because records don't have any predefined field
4155                                  * structure.
4156                                  */
4157                                 if (!HeapTupleIsValid(rec->tup))
4158                                         ereport(ERROR,
4159                                                   (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4160                                                    errmsg("record \"%s\" is not assigned yet",
4161                                                                   rec->refname),
4162                                                    errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
4163
4164                                 /*
4165                                  * Get the number of the records field to change and the
4166                                  * number of attributes in the tuple.  Note: disallow system
4167                                  * column names because the code below won't cope.
4168                                  */
4169                                 fno = SPI_fnumber(rec->tupdesc, recfield->fieldname);
4170                                 if (fno <= 0)
4171                                         ereport(ERROR,
4172                                                         (errcode(ERRCODE_UNDEFINED_COLUMN),
4173                                                          errmsg("record \"%s\" has no field \"%s\"",
4174                                                                         rec->refname, recfield->fieldname)));
4175                                 fno--;
4176                                 natts = rec->tupdesc->natts;
4177
4178                                 /*
4179                                  * Set up values/control arrays for heap_modify_tuple. For all
4180                                  * the attributes except the one we want to replace, use the
4181                                  * value that's in the old tuple.
4182                                  */
4183                                 values = palloc(sizeof(Datum) * natts);
4184                                 nulls = palloc(sizeof(bool) * natts);
4185                                 replaces = palloc(sizeof(bool) * natts);
4186
4187                                 memset(replaces, false, sizeof(bool) * natts);
4188                                 replaces[fno] = true;
4189
4190                                 /*
4191                                  * Now insert the new value, being careful to cast it to the
4192                                  * right type.
4193                                  */
4194                                 atttype = SPI_gettypeid(rec->tupdesc, fno + 1);
4195                                 atttypmod = rec->tupdesc->attrs[fno]->atttypmod;
4196                                 attisnull = *isNull;
4197                                 values[fno] = exec_simple_cast_value(estate,
4198                                                                                                          value,
4199                                                                                                          valtype,
4200                                                                                                          atttype,
4201                                                                                                          atttypmod,
4202                                                                                                          attisnull);
4203                                 nulls[fno] = attisnull;
4204
4205                                 /*
4206                                  * Now call heap_modify_tuple() to create a new tuple that
4207                                  * replaces the old one in the record.
4208                                  */
4209                                 newtup = heap_modify_tuple(rec->tup, rec->tupdesc,
4210                                                                                    values, nulls, replaces);
4211
4212                                 if (rec->freetup)
4213                                         heap_freetuple(rec->tup);
4214
4215                                 rec->tup = newtup;
4216                                 rec->freetup = true;
4217
4218                                 pfree(values);
4219                                 pfree(nulls);
4220                                 pfree(replaces);
4221
4222                                 break;
4223                         }
4224
4225                 case PLPGSQL_DTYPE_ARRAYELEM:
4226                         {
4227                                 /*
4228                                  * Target is an element of an array
4229                                  */
4230                                 PLpgSQL_arrayelem *arrayelem;
4231                                 int                     nsubscripts;
4232                                 int                     i;
4233                                 PLpgSQL_expr *subscripts[MAXDIM];
4234                                 int                     subscriptvals[MAXDIM];
4235                                 Datum           oldarraydatum,
4236                                                         coerced_value;
4237                                 bool            oldarrayisnull;
4238                                 Oid                     parenttypoid;
4239                                 int32           parenttypmod;
4240                                 ArrayType  *oldarrayval;
4241                                 ArrayType  *newarrayval;
4242                                 SPITupleTable *save_eval_tuptable;
4243                                 MemoryContext oldcontext;
4244
4245                                 /*
4246                                  * We need to do subscript evaluation, which might require
4247                                  * evaluating general expressions; and the caller might have
4248                                  * done that too in order to prepare the input Datum.  We have
4249                                  * to save and restore the caller's SPI_execute result, if
4250                                  * any.
4251                                  */
4252                                 save_eval_tuptable = estate->eval_tuptable;
4253                                 estate->eval_tuptable = NULL;
4254
4255                                 /*
4256                                  * To handle constructs like x[1][2] := something, we have to
4257                                  * be prepared to deal with a chain of arrayelem datums. Chase
4258                                  * back to find the base array datum, and save the subscript
4259                                  * expressions as we go.  (We are scanning right to left here,
4260                                  * but want to evaluate the subscripts left-to-right to
4261                                  * minimize surprises.)  Note that arrayelem is left pointing
4262                                  * to the leftmost arrayelem datum, where we will cache the
4263                                  * array element type data.
4264                                  */
4265                                 nsubscripts = 0;
4266                                 do
4267                                 {
4268                                         arrayelem = (PLpgSQL_arrayelem *) target;
4269                                         if (nsubscripts >= MAXDIM)
4270                                                 ereport(ERROR,
4271                                                                 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
4272                                                                  errmsg("number of array dimensions (%d) exceeds the maximum allowed (%d)",
4273                                                                                 nsubscripts + 1, MAXDIM)));
4274                                         subscripts[nsubscripts++] = arrayelem->subscript;
4275                                         target = estate->datums[arrayelem->arrayparentno];
4276                                 } while (target->dtype == PLPGSQL_DTYPE_ARRAYELEM);
4277
4278                                 /* Fetch current value of array datum */
4279                                 exec_eval_datum(estate, target,
4280                                                                 &parenttypoid, &parenttypmod,
4281                                                                 &oldarraydatum, &oldarrayisnull);
4282
4283                                 /* Update cached type data if necessary */
4284                                 if (arrayelem->parenttypoid != parenttypoid ||
4285                                         arrayelem->parenttypmod != parenttypmod)
4286                                 {
4287                                         Oid                     arraytypoid;
4288                                         int32           arraytypmod = parenttypmod;
4289                                         int16           arraytyplen;
4290                                         Oid                     elemtypoid;
4291                                         int16           elemtyplen;
4292                                         bool            elemtypbyval;
4293                                         char            elemtypalign;
4294
4295                                         /* If target is domain over array, reduce to base type */
4296                                         arraytypoid = getBaseTypeAndTypmod(parenttypoid,
4297                                                                                                            &arraytypmod);
4298
4299                                         /* ... and identify the element type */
4300                                         elemtypoid = get_element_type(arraytypoid);
4301                                         if (!OidIsValid(elemtypoid))
4302                                                 ereport(ERROR,
4303                                                                 (errcode(ERRCODE_DATATYPE_MISMATCH),
4304                                                           errmsg("subscripted object is not an array")));
4305
4306                                         /* Collect needed data about the types */
4307                                         arraytyplen = get_typlen(arraytypoid);
4308
4309                                         get_typlenbyvalalign(elemtypoid,
4310                                                                                  &elemtyplen,
4311                                                                                  &elemtypbyval,
4312                                                                                  &elemtypalign);
4313
4314                                         /* Now safe to update the cached data */
4315                                         arrayelem->parenttypoid = parenttypoid;
4316                                         arrayelem->parenttypmod = parenttypmod;
4317                                         arrayelem->arraytypoid = arraytypoid;
4318                                         arrayelem->arraytypmod = arraytypmod;
4319                                         arrayelem->arraytyplen = arraytyplen;
4320                                         arrayelem->elemtypoid = elemtypoid;
4321                                         arrayelem->elemtyplen = elemtyplen;
4322                                         arrayelem->elemtypbyval = elemtypbyval;
4323                                         arrayelem->elemtypalign = elemtypalign;
4324                                 }
4325
4326                                 /*
4327                                  * Evaluate the subscripts, switch into left-to-right order.
4328                                  * Like ExecEvalArrayRef(), complain if any subscript is null.
4329                                  */
4330                                 for (i = 0; i < nsubscripts; i++)
4331                                 {
4332                                         bool            subisnull;
4333
4334                                         subscriptvals[i] =
4335                                                 exec_eval_integer(estate,
4336                                                                                   subscripts[nsubscripts - 1 - i],
4337                                                                                   &subisnull);
4338                                         if (subisnull)
4339                                                 ereport(ERROR,
4340                                                                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
4341                                                                  errmsg("array subscript in assignment must not be null")));
4342
4343                                         /*
4344                                          * Clean up in case the subscript expression wasn't
4345                                          * simple. We can't do exec_eval_cleanup, but we can do
4346                                          * this much (which is safe because the integer subscript
4347                                          * value is surely pass-by-value), and we must do it in
4348                                          * case the next subscript expression isn't simple either.
4349                                          */
4350                                         if (estate->eval_tuptable != NULL)
4351                                                 SPI_freetuptable(estate->eval_tuptable);
4352                                         estate->eval_tuptable = NULL;
4353                                 }
4354
4355                                 /* Now we can restore caller's SPI_execute result if any. */
4356                                 Assert(estate->eval_tuptable == NULL);
4357                                 estate->eval_tuptable = save_eval_tuptable;
4358
4359                                 /* Coerce source value to match array element type. */
4360                                 coerced_value = exec_simple_cast_value(estate,
4361                                                                                                            value,
4362                                                                                                            valtype,
4363                                                                                                            arrayelem->elemtypoid,
4364                                                                                                            arrayelem->arraytypmod,
4365                                                                                                            *isNull);
4366
4367                                 /*
4368                                  * If the original array is null, cons up an empty array so
4369                                  * that the assignment can proceed; we'll end with a
4370                                  * one-element array containing just the assigned-to
4371                                  * subscript.  This only works for varlena arrays, though; for
4372                                  * fixed-length array types we skip the assignment.  We can't
4373                                  * support assignment of a null entry into a fixed-length
4374                                  * array, either, so that's a no-op too.  This is all ugly but
4375                                  * corresponds to the current behavior of ExecEvalArrayRef().
4376                                  */
4377                                 if (arrayelem->arraytyplen > 0 &&               /* fixed-length array? */
4378                                         (oldarrayisnull || *isNull))
4379                                         return;
4380
4381                                 /* oldarrayval and newarrayval should be short-lived */
4382                                 oldcontext = MemoryContextSwitchTo(estate->eval_econtext->ecxt_per_tuple_memory);
4383
4384                                 if (oldarrayisnull)
4385                                         oldarrayval = construct_empty_array(arrayelem->elemtypoid);
4386                                 else
4387                                         oldarrayval = (ArrayType *) DatumGetPointer(oldarraydatum);
4388
4389                                 /*
4390                                  * Build the modified array value.
4391                                  */
4392                                 newarrayval = array_set(oldarrayval,
4393                                                                                 nsubscripts,
4394                                                                                 subscriptvals,
4395                                                                                 coerced_value,
4396                                                                                 *isNull,
4397                                                                                 arrayelem->arraytyplen,
4398                                                                                 arrayelem->elemtyplen,
4399                                                                                 arrayelem->elemtypbyval,
4400                                                                                 arrayelem->elemtypalign);
4401
4402                                 MemoryContextSwitchTo(oldcontext);
4403
4404                                 /*
4405                                  * Assign the new array to the base variable.  It's never NULL
4406                                  * at this point.  Note that if the target is a domain,
4407                                  * coercing the base array type back up to the domain will
4408                                  * happen within exec_assign_value.
4409                                  */
4410                                 *isNull = false;
4411                                 exec_assign_value(estate, target,
4412                                                                   PointerGetDatum(newarrayval),
4413                                                                   arrayelem->arraytypoid, isNull);
4414                                 break;
4415                         }
4416
4417                 default:
4418                         elog(ERROR, "unrecognized dtype: %d", target->dtype);
4419         }
4420 }
4421
4422 /*
4423  * exec_eval_datum                              Get current value of a PLpgSQL_datum
4424  *
4425  * The type oid, typmod, value in Datum format, and null flag are returned.
4426  *
4427  * At present this doesn't handle PLpgSQL_expr or PLpgSQL_arrayelem datums.
4428  *
4429  * NOTE: caller must not modify the returned value, since it points right
4430  * at the stored value in the case of pass-by-reference datatypes.  In some
4431  * cases we have to palloc a return value, and in such cases we put it into
4432  * the estate's short-term memory context.
4433  */
4434 static void
4435 exec_eval_datum(PLpgSQL_execstate *estate,
4436                                 PLpgSQL_datum *datum,
4437                                 Oid *typeid,
4438                                 int32 *typetypmod,
4439                                 Datum *value,
4440                                 bool *isnull)
4441 {
4442         MemoryContext oldcontext;
4443
4444         switch (datum->dtype)
4445         {
4446                 case PLPGSQL_DTYPE_VAR:
4447                         {
4448                                 PLpgSQL_var *var = (PLpgSQL_var *) datum;
4449
4450                                 *typeid = var->datatype->typoid;
4451                                 *typetypmod = var->datatype->atttypmod;
4452                                 *value = var->value;
4453                                 *isnull = var->isnull;
4454                                 break;
4455                         }
4456
4457                 case PLPGSQL_DTYPE_ROW:
4458                         {
4459                                 PLpgSQL_row *row = (PLpgSQL_row *) datum;
4460                                 HeapTuple       tup;
4461
4462                                 if (!row->rowtupdesc)   /* should not happen */
4463                                         elog(ERROR, "row variable has no tupdesc");
4464                                 /* Make sure we have a valid type/typmod setting */
4465                                 BlessTupleDesc(row->rowtupdesc);
4466                                 oldcontext = MemoryContextSwitchTo(estate->eval_econtext->ecxt_per_tuple_memory);
4467                                 tup = make_tuple_from_row(estate, row, row->rowtupdesc);
4468                                 if (tup == NULL)        /* should not happen */
4469                                         elog(ERROR, "row not compatible with its own tupdesc");
4470                                 *typeid = row->rowtupdesc->tdtypeid;
4471                                 *typetypmod = row->rowtupdesc->tdtypmod;
4472                                 *value = HeapTupleGetDatum(tup);
4473                                 *isnull = false;
4474                                 MemoryContextSwitchTo(oldcontext);
4475                                 break;
4476                         }
4477
4478                 case PLPGSQL_DTYPE_REC:
4479                         {
4480                                 PLpgSQL_rec *rec = (PLpgSQL_rec *) datum;
4481
4482                                 if (!HeapTupleIsValid(rec->tup))
4483                                         ereport(ERROR,
4484                                                   (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4485                                                    errmsg("record \"%s\" is not assigned yet",
4486                                                                   rec->refname),
4487                                                    errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
4488                                 Assert(rec->tupdesc != NULL);
4489                                 /* Make sure we have a valid type/typmod setting */
4490                                 BlessTupleDesc(rec->tupdesc);
4491
4492                                 oldcontext = MemoryContextSwitchTo(estate->eval_econtext->ecxt_per_tuple_memory);
4493                                 *typeid = rec->tupdesc->tdtypeid;
4494                                 *typetypmod = rec->tupdesc->tdtypmod;
4495                                 *value = heap_copy_tuple_as_datum(rec->tup, rec->tupdesc);
4496                                 *isnull = false;
4497                                 MemoryContextSwitchTo(oldcontext);
4498                                 break;
4499                         }
4500
4501                 case PLPGSQL_DTYPE_RECFIELD:
4502                         {
4503                                 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) datum;
4504                                 PLpgSQL_rec *rec;
4505                                 int                     fno;
4506
4507                                 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
4508                                 if (!HeapTupleIsValid(rec->tup))
4509                                         ereport(ERROR,
4510                                                   (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4511                                                    errmsg("record \"%s\" is not assigned yet",
4512                                                                   rec->refname),
4513                                                    errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
4514                                 fno = SPI_fnumber(rec->tupdesc, recfield->fieldname);
4515                                 if (fno == SPI_ERROR_NOATTRIBUTE)
4516                                         ereport(ERROR,
4517                                                         (errcode(ERRCODE_UNDEFINED_COLUMN),
4518                                                          errmsg("record \"%s\" has no field \"%s\"",
4519                                                                         rec->refname, recfield->fieldname)));
4520                                 *typeid = SPI_gettypeid(rec->tupdesc, fno);
4521                                 if (fno > 0)
4522                                         *typetypmod = rec->tupdesc->attrs[fno - 1]->atttypmod;
4523                                 else
4524                                         *typetypmod = -1;
4525                                 *value = SPI_getbinval(rec->tup, rec->tupdesc, fno, isnull);
4526                                 break;
4527                         }
4528
4529                 default:
4530                         elog(ERROR, "unrecognized dtype: %d", datum->dtype);
4531         }
4532 }
4533
4534 /*
4535  * exec_get_datum_type                          Get datatype of a PLpgSQL_datum
4536  *
4537  * This is the same logic as in exec_eval_datum, except that it can handle
4538  * some cases where exec_eval_datum has to fail; specifically, we may have
4539  * a tupdesc but no row value for a record variable.  (This currently can
4540  * happen only for a trigger's NEW/OLD records.)
4541  */
4542 Oid
4543 exec_get_datum_type(PLpgSQL_execstate *estate,
4544                                         PLpgSQL_datum *datum)
4545 {
4546         Oid                     typeid;
4547
4548         switch (datum->dtype)
4549         {
4550                 case PLPGSQL_DTYPE_VAR:
4551                         {
4552                                 PLpgSQL_var *var = (PLpgSQL_var *) datum;
4553
4554                                 typeid = var->datatype->typoid;
4555                                 break;
4556                         }
4557
4558                 case PLPGSQL_DTYPE_ROW:
4559                         {
4560                                 PLpgSQL_row *row = (PLpgSQL_row *) datum;
4561
4562                                 if (!row->rowtupdesc)   /* should not happen */
4563                                         elog(ERROR, "row variable has no tupdesc");
4564                                 /* Make sure we have a valid type/typmod setting */
4565                                 BlessTupleDesc(row->rowtupdesc);
4566                                 typeid = row->rowtupdesc->tdtypeid;
4567                                 break;
4568                         }
4569
4570                 case PLPGSQL_DTYPE_REC:
4571                         {
4572                                 PLpgSQL_rec *rec = (PLpgSQL_rec *) datum;
4573
4574                                 if (rec->tupdesc == NULL)
4575                                         ereport(ERROR,
4576                                                   (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4577                                                    errmsg("record \"%s\" is not assigned yet",
4578                                                                   rec->refname),
4579                                                    errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
4580                                 /* Make sure we have a valid type/typmod setting */
4581                                 BlessTupleDesc(rec->tupdesc);
4582                                 typeid = rec->tupdesc->tdtypeid;
4583                                 break;
4584                         }
4585
4586                 case PLPGSQL_DTYPE_RECFIELD:
4587                         {
4588                                 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) datum;
4589                                 PLpgSQL_rec *rec;
4590                                 int                     fno;
4591
4592                                 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
4593                                 if (rec->tupdesc == NULL)
4594                                         ereport(ERROR,
4595                                                   (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4596                                                    errmsg("record \"%s\" is not assigned yet",
4597                                                                   rec->refname),
4598                                                    errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
4599                                 fno = SPI_fnumber(rec->tupdesc, recfield->fieldname);
4600                                 if (fno == SPI_ERROR_NOATTRIBUTE)
4601                                         ereport(ERROR,
4602                                                         (errcode(ERRCODE_UNDEFINED_COLUMN),
4603                                                          errmsg("record \"%s\" has no field \"%s\"",
4604                                                                         rec->refname, recfield->fieldname)));
4605                                 typeid = SPI_gettypeid(rec->tupdesc, fno);
4606                                 break;
4607                         }
4608
4609                 default:
4610                         elog(ERROR, "unrecognized dtype: %d", datum->dtype);
4611                         typeid = InvalidOid;    /* keep compiler quiet */
4612                         break;
4613         }
4614
4615         return typeid;
4616 }
4617
4618 /*
4619  * exec_get_datum_type_info                     Get datatype etc of a PLpgSQL_datum
4620  *
4621  * An extended version of exec_get_datum_type, which also retrieves the
4622  * typmod and collation of the datum.
4623  */
4624 void
4625 exec_get_datum_type_info(PLpgSQL_execstate *estate,
4626                                                  PLpgSQL_datum *datum,
4627                                                  Oid *typeid, int32 *typmod, Oid *collation)
4628 {
4629         switch (datum->dtype)
4630         {
4631                 case PLPGSQL_DTYPE_VAR:
4632                         {
4633                                 PLpgSQL_var *var = (PLpgSQL_var *) datum;
4634
4635                                 *typeid = var->datatype->typoid;
4636                                 *typmod = var->datatype->atttypmod;
4637                                 *collation = var->datatype->collation;
4638                                 break;
4639                         }
4640
4641                 case PLPGSQL_DTYPE_ROW:
4642                         {
4643                                 PLpgSQL_row *row = (PLpgSQL_row *) datum;
4644
4645                                 if (!row->rowtupdesc)   /* should not happen */
4646                                         elog(ERROR, "row variable has no tupdesc");
4647                                 /* Make sure we have a valid type/typmod setting */
4648                                 BlessTupleDesc(row->rowtupdesc);
4649                                 *typeid = row->rowtupdesc->tdtypeid;
4650                                 /* do NOT return the mutable typmod of a RECORD variable */
4651                                 *typmod = -1;
4652                                 /* composite types are never collatable */
4653                                 *collation = InvalidOid;
4654                                 break;
4655                         }
4656
4657                 case PLPGSQL_DTYPE_REC:
4658                         {
4659                                 PLpgSQL_rec *rec = (PLpgSQL_rec *) datum;
4660
4661                                 if (rec->tupdesc == NULL)
4662                                         ereport(ERROR,
4663                                                   (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4664                                                    errmsg("record \"%s\" is not assigned yet",
4665                                                                   rec->refname),
4666                                                    errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
4667                                 /* Make sure we have a valid type/typmod setting */
4668                                 BlessTupleDesc(rec->tupdesc);
4669                                 *typeid = rec->tupdesc->tdtypeid;
4670                                 /* do NOT return the mutable typmod of a RECORD variable */
4671                                 *typmod = -1;
4672                                 /* composite types are never collatable */
4673                                 *collation = InvalidOid;
4674                                 break;
4675                         }
4676
4677                 case PLPGSQL_DTYPE_RECFIELD:
4678                         {
4679                                 PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) datum;
4680                                 PLpgSQL_rec *rec;
4681                                 int                     fno;
4682
4683                                 rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
4684                                 if (rec->tupdesc == NULL)
4685                                         ereport(ERROR,
4686                                                   (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
4687                                                    errmsg("record \"%s\" is not assigned yet",
4688                                                                   rec->refname),
4689                                                    errdetail("The tuple structure of a not-yet-assigned record is indeterminate.")));
4690                                 fno = SPI_fnumber(rec->tupdesc, recfield->fieldname);
4691                                 if (fno == SPI_ERROR_NOATTRIBUTE)
4692                                         ereport(ERROR,
4693                                                         (errcode(ERRCODE_UNDEFINED_COLUMN),
4694                                                          errmsg("record \"%s\" has no field \"%s\"",
4695                                                                         rec->refname, recfield->fieldname)));
4696                                 *typeid = SPI_gettypeid(rec->tupdesc, fno);
4697                                 if (fno > 0)
4698                                         *typmod = rec->tupdesc->attrs[fno - 1]->atttypmod;
4699                                 else
4700                                         *typmod = -1;
4701                                 if (fno > 0)
4702                                         *collation = rec->tupdesc->attrs[fno - 1]->attcollation;
4703                                 else    /* no system column types have collation */
4704                                         *collation = InvalidOid;
4705                                 break;
4706                         }
4707
4708                 default:
4709                         elog(ERROR, "unrecognized dtype: %d", datum->dtype);
4710                         *typeid = InvalidOid;           /* keep compiler quiet */
4711                         *typmod = -1;
4712                         *collation = InvalidOid;
4713                         break;
4714         }
4715 }
4716
4717 /* ----------
4718  * exec_eval_integer            Evaluate an expression, coerce result to int4
4719  *
4720  * Note we do not do exec_eval_cleanup here; the caller must do it at
4721  * some later point.  (We do this because the caller may be holding the
4722  * results of other, pass-by-reference, expression evaluations, such as
4723  * an array value to be subscripted.  Also see notes in exec_eval_simple_expr
4724  * about allocation of the parameter array.)
4725  * ----------
4726  */
4727 static int
4728 exec_eval_integer(PLpgSQL_execstate *estate,
4729                                   PLpgSQL_expr *expr,
4730                                   bool *isNull)
4731 {
4732         Datum           exprdatum;
4733         Oid                     exprtypeid;
4734
4735         exprdatum = exec_eval_expr(estate, expr, isNull, &exprtypeid);
4736         exprdatum = exec_simple_cast_value(estate, exprdatum, exprtypeid,
4737                                                                            INT4OID, -1,
4738                                                                            *isNull);
4739         return DatumGetInt32(exprdatum);
4740 }
4741
4742 /* ----------
4743  * exec_eval_boolean            Evaluate an expression, coerce result to bool
4744  *
4745  * Note we do not do exec_eval_cleanup here; the caller must do it at
4746  * some later point.
4747  * ----------
4748  */
4749 static bool
4750 exec_eval_boolean(PLpgSQL_execstate *estate,
4751                                   PLpgSQL_expr *expr,
4752                                   bool *isNull)
4753 {
4754         Datum           exprdatum;
4755         Oid                     exprtypeid;
4756
4757         exprdatum = exec_eval_expr(estate, expr, isNull, &exprtypeid);
4758         exprdatum = exec_simple_cast_value(estate, exprdatum, exprtypeid,
4759                                                                            BOOLOID, -1,
4760                                                                            *isNull);
4761         return DatumGetBool(exprdatum);
4762 }
4763
4764 /* ----------
4765  * exec_eval_expr                       Evaluate an expression and return
4766  *                                      the result Datum.
4767  *
4768  * NOTE: caller must do exec_eval_cleanup when done with the Datum.
4769  * ----------
4770  */
4771 static Datum
4772 exec_eval_expr(PLpgSQL_execstate *estate,
4773                            PLpgSQL_expr *expr,
4774                            bool *isNull,
4775                            Oid *rettype)
4776 {
4777         Datum           result = 0;
4778         int                     rc;
4779
4780         /*
4781          * If first time through, create a plan for this expression.
4782          */
4783         if (expr->plan == NULL)
4784                 exec_prepare_plan(estate, expr, 0);
4785
4786         /*
4787          * If this is a simple expression, bypass SPI and use the executor
4788          * directly
4789          */
4790         if (exec_eval_simple_expr(estate, expr, &result, isNull, rettype))
4791                 return result;
4792
4793         /*
4794          * Else do it the hard way via exec_run_select
4795          */
4796         rc = exec_run_select(estate, expr, 2, NULL);
4797         if (rc != SPI_OK_SELECT)
4798                 ereport(ERROR,
4799                                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
4800                                  errmsg("query \"%s\" did not return data", expr->query)));
4801
4802         /*
4803          * Check that the expression returns exactly one column...
4804          */
4805         if (estate->eval_tuptable->tupdesc->natts != 1)
4806                 ereport(ERROR,
4807                                 (errcode(ERRCODE_SYNTAX_ERROR),
4808                                  errmsg_plural("query \"%s\" returned %d column",
4809                                                            "query \"%s\" returned %d columns",
4810                                                            estate->eval_tuptable->tupdesc->natts,
4811                                                            expr->query,
4812                                                            estate->eval_tuptable->tupdesc->natts)));
4813
4814         /*
4815          * ... and get the column's datatype.
4816          */
4817         *rettype = SPI_gettypeid(estate->eval_tuptable->tupdesc, 1);
4818
4819         /*
4820          * If there are no rows selected, the result is a NULL of that type.
4821          */
4822         if (estate->eval_processed == 0)
4823         {
4824                 *isNull = true;
4825                 return (Datum) 0;
4826         }
4827
4828         /*
4829          * Check that the expression returned no more than one row.
4830          */
4831         if (estate->eval_processed != 1)
4832                 ereport(ERROR,
4833                                 (errcode(ERRCODE_CARDINALITY_VIOLATION),
4834                                  errmsg("query \"%s\" returned more than one row",
4835                                                 expr->query)));
4836
4837         /*
4838          * Return the single result Datum.
4839          */
4840         return SPI_getbinval(estate->eval_tuptable->vals[0],
4841                                                  estate->eval_tuptable->tupdesc, 1, isNull);
4842 }
4843
4844
4845 /* ----------
4846  * exec_run_select                      Execute a select query
4847  * ----------
4848  */
4849 static int
4850 exec_run_select(PLpgSQL_execstate *estate,
4851                                 PLpgSQL_expr *expr, long maxtuples, Portal *portalP)
4852 {
4853         ParamListInfo paramLI;
4854         int                     rc;
4855
4856         /*
4857          * On the first call for this expression generate the plan
4858          */
4859         if (expr->plan == NULL)
4860                 exec_prepare_plan(estate, expr, 0);
4861
4862         /*
4863          * Set up ParamListInfo (hook function and possibly data values)
4864          */
4865         paramLI = setup_param_list(estate, expr);
4866
4867         /*
4868          * If a portal was requested, put the query into the portal
4869          */
4870         if (portalP != NULL)
4871         {
4872                 *portalP = SPI_cursor_open_with_paramlist(NULL, expr->plan,
4873                                                                                                   paramLI,
4874                                                                                                   estate->readonly_func);
4875                 if (*portalP == NULL)
4876                         elog(ERROR, "could not open implicit cursor for query \"%s\": %s",
4877                                  expr->query, SPI_result_code_string(SPI_result));
4878                 if (paramLI)
4879                         pfree(paramLI);
4880                 return SPI_OK_CURSOR;
4881         }
4882
4883         /*
4884          * Execute the query
4885          */
4886         rc = SPI_execute_plan_with_paramlist(expr->plan, paramLI,
4887                                                                                  estate->readonly_func, maxtuples);
4888         if (rc != SPI_OK_SELECT)
4889                 ereport(ERROR,
4890                                 (errcode(ERRCODE_SYNTAX_ERROR),
4891                                  errmsg("query \"%s\" is not a SELECT", expr->query)));
4892
4893         /* Save query results for eventual cleanup */
4894         Assert(estate->eval_tuptable == NULL);
4895         estate->eval_tuptable = SPI_tuptable;
4896         estate->eval_processed = SPI_processed;
4897         estate->eval_lastoid = SPI_lastoid;
4898
4899         if (paramLI)
4900                 pfree(paramLI);
4901
4902         return rc;
4903 }
4904
4905
4906 /*
4907  * exec_for_query --- execute body of FOR loop for each row from a portal
4908  *
4909  * Used by exec_stmt_fors, exec_stmt_forc and exec_stmt_dynfors
4910  */
4911 static int
4912 exec_for_query(PLpgSQL_execstate *estate, PLpgSQL_stmt_forq *stmt,
4913                            Portal portal, bool prefetch_ok)
4914 {
4915         PLpgSQL_rec *rec = NULL;
4916         PLpgSQL_row *row = NULL;
4917         SPITupleTable *tuptab;
4918         bool            found = false;
4919         int                     rc = PLPGSQL_RC_OK;
4920         int                     n;
4921
4922         /*
4923          * Determine if we assign to a record or a row
4924          */
4925         if (stmt->rec != NULL)
4926                 rec = (PLpgSQL_rec *) (estate->datums[stmt->rec->dno]);
4927         else if (stmt->row != NULL)
4928                 row = (PLpgSQL_row *) (estate->datums[stmt->row->dno]);
4929         else
4930                 elog(ERROR, "unsupported target");
4931
4932         /*
4933          * Make sure the portal doesn't get closed by the user statements we
4934          * execute.
4935          */
4936         PinPortal(portal);
4937
4938         /*
4939          * Fetch the initial tuple(s).  If prefetching is allowed then we grab a
4940          * few more rows to avoid multiple trips through executor startup
4941          * overhead.
4942          */
4943         SPI_cursor_fetch(portal, true, prefetch_ok ? 10 : 1);
4944         tuptab = SPI_tuptable;
4945         n = SPI_processed;
4946
4947         /*
4948          * If the query didn't return any rows, set the target to NULL and fall
4949          * through with found = false.
4950          */
4951         if (n <= 0)
4952         {
4953                 exec_move_row(estate, rec, row, NULL, tuptab->tupdesc);
4954                 exec_eval_cleanup(estate);
4955         }
4956         else
4957                 found = true;                   /* processed at least one tuple */
4958
4959         /*
4960          * Now do the loop
4961          */
4962         while (n > 0)
4963         {
4964                 int                     i;
4965
4966                 for (i = 0; i < n; i++)
4967                 {
4968                         /*
4969                          * Assign the tuple to the target
4970                          */
4971                         exec_move_row(estate, rec, row, tuptab->vals[i], tuptab->tupdesc);
4972                         exec_eval_cleanup(estate);
4973
4974                         /*
4975                          * Execute the statements
4976                          */
4977                         rc = exec_stmts(estate, stmt->body);
4978
4979                         if (rc != PLPGSQL_RC_OK)
4980                         {
4981                                 if (rc == PLPGSQL_RC_EXIT)
4982                                 {
4983                                         if (estate->exitlabel == NULL)
4984                                         {
4985                                                 /* unlabelled exit, so exit the current loop */
4986                                                 rc = PLPGSQL_RC_OK;
4987                                         }
4988                                         else if (stmt->label != NULL &&
4989                                                          strcmp(stmt->label, estate->exitlabel) == 0)
4990                                         {
4991                                                 /* label matches this loop, so exit loop */
4992                                                 estate->exitlabel = NULL;
4993                                                 rc = PLPGSQL_RC_OK;
4994                                         }
4995
4996                                         /*
4997                                          * otherwise, we processed a labelled exit that does not
4998                                          * match the current statement's label, if any; return
4999                                          * RC_EXIT so that the EXIT continues to recurse upward.
5000                                          */
5001                                 }
5002                                 else if (rc == PLPGSQL_RC_CONTINUE)
5003                                 {
5004                                         if (estate->exitlabel == NULL)
5005                                         {
5006                                                 /* unlabelled continue, so re-run the current loop */
5007                                                 rc = PLPGSQL_RC_OK;
5008                                                 continue;
5009                                         }
5010                                         else if (stmt->label != NULL &&
5011                                                          strcmp(stmt->label, estate->exitlabel) == 0)
5012                                         {
5013                                                 /* label matches this loop, so re-run loop */
5014                                                 estate->exitlabel = NULL;
5015                                                 rc = PLPGSQL_RC_OK;
5016                                                 continue;
5017                                         }
5018
5019                                         /*
5020                                          * otherwise, we process a labelled continue that does not
5021                                          * match the current statement's label, if any; return
5022                                          * RC_CONTINUE so that the CONTINUE will propagate up the
5023                                          * stack.
5024                                          */
5025                                 }
5026
5027                                 /*
5028                                  * We're aborting the loop.  Need a goto to get out of two
5029                                  * levels of loop...
5030                                  */
5031                                 goto loop_exit;
5032                         }
5033                 }
5034
5035                 SPI_freetuptable(tuptab);
5036
5037                 /*
5038                  * Fetch more tuples.  If prefetching is allowed, grab 50 at a time.
5039                  */
5040                 SPI_cursor_fetch(portal, true, prefetch_ok ? 50 : 1);
5041                 tuptab = SPI_tuptable;
5042                 n = SPI_processed;
5043         }
5044
5045 loop_exit:
5046
5047         /*
5048          * Release last group of tuples (if any)
5049          */
5050         SPI_freetuptable(tuptab);
5051
5052         UnpinPortal(portal);
5053
5054         /*
5055          * Set the FOUND variable to indicate the result of executing the loop
5056          * (namely, whether we looped one or more times). This must be set last so
5057          * that it does not interfere with the value of the FOUND variable inside
5058          * the loop processing itself.
5059          */
5060         exec_set_found(estate, found);
5061
5062         return rc;
5063 }
5064
5065
5066 /* ----------
5067  * exec_eval_simple_expr -              Evaluate a simple expression returning
5068  *                                                              a Datum by directly calling ExecEvalExpr().
5069  *
5070  * If successful, store results into *result, *isNull, *rettype and return
5071  * TRUE.  If the expression cannot be handled by simple evaluation,
5072  * return FALSE.
5073  *
5074  * Because we only store one execution tree for a simple expression, we
5075  * can't handle recursion cases.  So, if we see the tree is already busy
5076  * with an evaluation in the current xact, we just return FALSE and let the
5077  * caller run the expression the hard way.  (Other alternatives such as
5078  * creating a new tree for a recursive call either introduce memory leaks,
5079  * or add enough bookkeeping to be doubtful wins anyway.)  Another case that
5080  * is covered by the expr_simple_in_use test is where a previous execution
5081  * of the tree was aborted by an error: the tree may contain bogus state
5082  * so we dare not re-use it.
5083  *
5084  * It is possible though unlikely for a simple expression to become non-simple
5085  * (consider for example redefining a trivial view).  We must handle that for
5086  * correctness; fortunately it's normally inexpensive to call
5087  * SPI_plan_get_cached_plan for a simple expression.  We do not consider the
5088  * other direction (non-simple expression becoming simple) because we'll still
5089  * give correct results if that happens, and it's unlikely to be worth the
5090  * cycles to check.
5091  *
5092  * Note: if pass-by-reference, the result is in the eval_econtext's
5093  * temporary memory context.  It will be freed when exec_eval_cleanup
5094  * is done.
5095  * ----------
5096  */
5097 static bool
5098 exec_eval_simple_expr(PLpgSQL_execstate *estate,
5099                                           PLpgSQL_expr *expr,
5100                                           Datum *result,
5101                                           bool *isNull,
5102                                           Oid *rettype)
5103 {
5104         ExprContext *econtext = estate->eval_econtext;
5105         LocalTransactionId curlxid = MyProc->lxid;
5106         CachedPlan *cplan;
5107         ParamListInfo paramLI;
5108         PLpgSQL_expr *save_cur_expr;
5109         MemoryContext oldcontext;
5110
5111         /*
5112          * Forget it if expression wasn't simple before.
5113          */
5114         if (expr->expr_simple_expr == NULL)
5115                 return false;
5116
5117         /*
5118          * If expression is in use in current xact, don't touch it.
5119          */
5120         if (expr->expr_simple_in_use && expr->expr_simple_lxid == curlxid)
5121                 return false;
5122
5123         /*
5124          * Revalidate cached plan, so that we will notice if it became stale. (We
5125          * need to hold a refcount while using the plan, anyway.)
5126          */
5127         cplan = SPI_plan_get_cached_plan(expr->plan);
5128
5129         /*
5130          * We can't get a failure here, because the number of CachedPlanSources in
5131          * the SPI plan can't change from what exec_simple_check_plan saw; it's a
5132          * property of the raw parsetree generated from the query text.
5133          */
5134         Assert(cplan != NULL);
5135
5136         if (cplan->generation != expr->expr_simple_generation)
5137         {
5138                 /* It got replanned ... is it still simple? */
5139                 exec_simple_recheck_plan(expr, cplan);
5140                 if (expr->expr_simple_expr == NULL)
5141                 {
5142                         /* Ooops, release refcount and fail */
5143                         ReleaseCachedPlan(cplan, true);
5144                         return false;
5145                 }
5146         }
5147
5148         /*
5149          * Pass back previously-determined result type.
5150          */
5151         *rettype = expr->expr_simple_type;
5152
5153         /*
5154          * Prepare the expression for execution, if it's not been done already in
5155          * the current transaction.  (This will be forced to happen if we called
5156          * exec_simple_recheck_plan above.)
5157          */
5158         if (expr->expr_simple_lxid != curlxid)
5159         {
5160                 oldcontext = MemoryContextSwitchTo(estate->simple_eval_estate->es_query_cxt);
5161                 expr->expr_simple_state = ExecInitExpr(expr->expr_simple_expr, NULL);
5162                 expr->expr_simple_in_use = false;
5163                 expr->expr_simple_lxid = curlxid;
5164                 MemoryContextSwitchTo(oldcontext);
5165         }
5166
5167         /*
5168          * We have to do some of the things SPI_execute_plan would do, in
5169          * particular advance the snapshot if we are in a non-read-only function.
5170          * Without this, stable functions within the expression would fail to see
5171          * updates made so far by our own function.
5172          */
5173         SPI_push();
5174
5175         oldcontext = MemoryContextSwitchTo(econtext->ecxt_per_tuple_memory);
5176         if (!estate->readonly_func)
5177         {
5178                 CommandCounterIncrement();
5179                 PushActiveSnapshot(GetTransactionSnapshot());
5180         }
5181
5182         /*
5183          * Create the param list in econtext's temporary memory context. We won't
5184          * need to free it explicitly, since it will go away at the next reset of
5185          * that context.
5186          *
5187          * Just for paranoia's sake, save and restore the prior value of
5188          * estate->cur_expr, which setup_param_list() sets.
5189          */
5190         save_cur_expr = estate->cur_expr;
5191
5192         paramLI = setup_param_list(estate, expr);
5193         econtext->ecxt_param_list_info = paramLI;
5194
5195         /*
5196          * Mark expression as busy for the duration of the ExecEvalExpr call.
5197          */
5198         expr->expr_simple_in_use = true;
5199
5200         /*
5201          * Finally we can call the executor to evaluate the expression
5202          */
5203         *result = ExecEvalExpr(expr->expr_simple_state,
5204                                                    econtext,
5205                                                    isNull,
5206                                                    NULL);
5207
5208         /* Assorted cleanup */
5209         expr->expr_simple_in_use = false;
5210
5211         estate->cur_expr = save_cur_expr;
5212
5213         if (!estate->readonly_func)
5214                 PopActiveSnapshot();
5215
5216         MemoryContextSwitchTo(oldcontext);
5217
5218         SPI_pop();
5219
5220         /*
5221          * Now we can release our refcount on the cached plan.
5222          */
5223         ReleaseCachedPlan(cplan, true);
5224
5225         /*
5226          * That's it.
5227          */
5228         return true;
5229 }
5230
5231
5232 /*
5233  * Create a ParamListInfo to pass to SPI
5234  *
5235  * We fill in the values for any expression parameters that are plain
5236  * PLpgSQL_var datums; these are cheap and safe to evaluate, and by setting
5237  * them with PARAM_FLAG_CONST flags, we allow the planner to use those values
5238  * in custom plans.  However, parameters that are not plain PLpgSQL_vars
5239  * should not be evaluated here, because they could throw errors (for example
5240  * "no such record field") and we do not want that to happen in a part of
5241  * the expression that might never be evaluated at runtime.  To handle those
5242  * parameters, we set up a paramFetch hook for the executor to call when it
5243  * wants a not-presupplied value.
5244  *
5245  * The result is a locally palloc'd array that should be pfree'd after use;
5246  * but note it can be NULL.
5247  */
5248 static ParamListInfo
5249 setup_param_list(PLpgSQL_execstate *estate, PLpgSQL_expr *expr)
5250 {
5251         ParamListInfo paramLI;
5252
5253         /*
5254          * We must have created the SPIPlan already (hence, query text has been
5255          * parsed/analyzed at least once); else we cannot rely on expr->paramnos.
5256          */
5257         Assert(expr->plan != NULL);
5258
5259         /*
5260          * Could we re-use these arrays instead of palloc'ing a new one each time?
5261          * However, we'd have to re-fill the array each time anyway, since new
5262          * values might have been assigned to the variables.
5263          */
5264         if (!bms_is_empty(expr->paramnos))
5265         {
5266                 Bitmapset  *tmpset;
5267                 int                     dno;
5268
5269                 paramLI = (ParamListInfo)
5270                         palloc0(offsetof(ParamListInfoData, params) +
5271                                         estate->ndatums * sizeof(ParamExternData));
5272                 paramLI->paramFetch = plpgsql_param_fetch;
5273                 paramLI->paramFetchArg = (void *) estate;
5274                 paramLI->parserSetup = (ParserSetupHook) plpgsql_parser_setup;
5275                 paramLI->parserSetupArg = (void *) expr;
5276                 paramLI->numParams = estate->ndatums;
5277
5278                 /* Instantiate values for "safe" parameters of the expression */
5279                 tmpset = bms_copy(expr->paramnos);
5280                 while ((dno = bms_first_member(tmpset)) >= 0)
5281                 {
5282                         PLpgSQL_datum *datum = estate->datums[dno];
5283
5284                         if (datum->dtype == PLPGSQL_DTYPE_VAR)
5285                         {
5286                                 PLpgSQL_var *var = (PLpgSQL_var *) datum;
5287                                 ParamExternData *prm = &paramLI->params[dno];
5288
5289                                 prm->value = var->value;
5290                                 prm->isnull = var->isnull;
5291                                 prm->pflags = PARAM_FLAG_CONST;
5292                                 prm->ptype = var->datatype->typoid;
5293                         }
5294                 }
5295                 bms_free(tmpset);
5296
5297                 /*
5298                  * Set up link to active expr where the hook functions can find it.
5299                  * Callers must save and restore cur_expr if there is any chance that
5300                  * they are interrupting an active use of parameters.
5301                  */
5302                 estate->cur_expr = expr;
5303
5304                 /*
5305                  * Also make sure this is set before parser hooks need it.  There is
5306                  * no need to save and restore, since the value is always correct once
5307                  * set.  (Should be set already, but let's be sure.)
5308                  */
5309                 expr->func = estate->func;
5310         }
5311         else
5312         {
5313                 /*
5314                  * Expression requires no parameters.  Be sure we represent this case
5315                  * as a NULL ParamListInfo, so that plancache.c knows there is no
5316                  * point in a custom plan.
5317                  */
5318                 paramLI = NULL;
5319         }
5320         return paramLI;
5321 }
5322
5323 /*
5324  * plpgsql_param_fetch          paramFetch callback for dynamic parameter fetch
5325  */
5326 static void
5327 plpgsql_param_fetch(ParamListInfo params, int paramid)
5328 {
5329         int                     dno;
5330         PLpgSQL_execstate *estate;
5331         PLpgSQL_expr *expr;
5332         PLpgSQL_datum *datum;
5333         ParamExternData *prm;
5334         int32           prmtypmod;
5335
5336         /* paramid's are 1-based, but dnos are 0-based */
5337         dno = paramid - 1;
5338         Assert(dno >= 0 && dno < params->numParams);
5339
5340         /* fetch back the hook data */
5341         estate = (PLpgSQL_execstate *) params->paramFetchArg;
5342         expr = estate->cur_expr;
5343         Assert(params->numParams == estate->ndatums);
5344
5345         /*
5346          * Do nothing if asked for a value that's not supposed to be used by this
5347          * SQL expression.  This avoids unwanted evaluations when functions such
5348          * as copyParamList try to materialize all the values.
5349          */
5350         if (!bms_is_member(dno, expr->paramnos))
5351                 return;
5352
5353         /* OK, evaluate the value and store into the appropriate paramlist slot */
5354         datum = estate->datums[dno];
5355         prm = &params->params[dno];
5356         exec_eval_datum(estate, datum,
5357                                         &prm->ptype, &prmtypmod,
5358                                         &prm->value, &prm->isnull);
5359 }
5360
5361
5362 /* ----------
5363  * exec_move_row                        Move one tuple's values into a record or row
5364  *
5365  * Since this uses exec_assign_value, caller should eventually call
5366  * exec_eval_cleanup to prevent long-term memory leaks.
5367  * ----------
5368  */
5369 static void
5370 exec_move_row(PLpgSQL_execstate *estate,
5371                           PLpgSQL_rec *rec,
5372                           PLpgSQL_row *row,
5373                           HeapTuple tup, TupleDesc tupdesc)
5374 {
5375         /*
5376          * Record is simple - just copy the tuple and its descriptor into the
5377          * record variable
5378          */
5379         if (rec != NULL)
5380         {
5381                 /*
5382                  * Copy input first, just in case it is pointing at variable's value
5383                  */
5384                 if (HeapTupleIsValid(tup))
5385                         tup = heap_copytuple(tup);
5386                 else if (tupdesc)
5387                 {
5388                         /* If we have a tupdesc but no data, form an all-nulls tuple */
5389                         bool       *nulls;
5390
5391                         nulls = (bool *) palloc(tupdesc->natts * sizeof(bool));
5392                         memset(nulls, true, tupdesc->natts * sizeof(bool));
5393
5394                         tup = heap_form_tuple(tupdesc, NULL, nulls);
5395
5396                         pfree(nulls);
5397                 }
5398
5399                 if (tupdesc)
5400                         tupdesc = CreateTupleDescCopy(tupdesc);
5401
5402                 /* Free the old value ... */
5403                 if (rec->freetup)
5404                 {
5405                         heap_freetuple(rec->tup);
5406                         rec->freetup = false;
5407                 }
5408                 if (rec->freetupdesc)
5409                 {
5410                         FreeTupleDesc(rec->tupdesc);
5411                         rec->freetupdesc = false;
5412                 }
5413
5414                 /* ... and install the new */
5415                 if (HeapTupleIsValid(tup))
5416                 {
5417                         rec->tup = tup;
5418                         rec->freetup = true;
5419                 }
5420                 else
5421                         rec->tup = NULL;
5422
5423                 if (tupdesc)
5424                 {
5425                         rec->tupdesc = tupdesc;
5426                         rec->freetupdesc = true;
5427                 }
5428                 else
5429                         rec->tupdesc = NULL;
5430
5431                 return;
5432         }
5433
5434         /*
5435          * Row is a bit more complicated in that we assign the individual
5436          * attributes of the tuple to the variables the row points to.
5437          *
5438          * NOTE: this code used to demand row->nfields ==
5439          * HeapTupleHeaderGetNatts(tup->t_data), but that's wrong.  The tuple
5440          * might have more fields than we expected if it's from an
5441          * inheritance-child table of the current table, or it might have fewer if
5442          * the table has had columns added by ALTER TABLE. Ignore extra columns
5443          * and assume NULL for missing columns, the same as heap_getattr would do.
5444          * We also have to skip over dropped columns in either the source or
5445          * destination.
5446          *
5447          * If we have no tuple data at all, we'll assign NULL to all columns of
5448          * the row variable.
5449          */
5450         if (row != NULL)
5451         {
5452                 int                     td_natts = tupdesc ? tupdesc->natts : 0;
5453                 int                     t_natts;
5454                 int                     fnum;
5455                 int                     anum;
5456
5457                 if (HeapTupleIsValid(tup))
5458                         t_natts = HeapTupleHeaderGetNatts(tup->t_data);
5459                 else
5460                         t_natts = 0;
5461
5462                 anum = 0;
5463                 for (fnum = 0; fnum < row->nfields; fnum++)
5464                 {
5465                         PLpgSQL_var *var;
5466                         Datum           value;
5467                         bool            isnull;
5468                         Oid                     valtype;
5469
5470                         if (row->varnos[fnum] < 0)
5471                                 continue;               /* skip dropped column in row struct */
5472
5473                         var = (PLpgSQL_var *) (estate->datums[row->varnos[fnum]]);
5474
5475                         while (anum < td_natts && tupdesc->attrs[anum]->attisdropped)
5476                                 anum++;                 /* skip dropped column in tuple */
5477
5478                         if (anum < td_natts)
5479                         {
5480                                 if (anum < t_natts)
5481                                         value = SPI_getbinval(tup, tupdesc, anum + 1, &isnull);
5482                                 else
5483                                 {
5484                                         value = (Datum) 0;
5485                                         isnull = true;
5486                                 }
5487                                 valtype = SPI_gettypeid(tupdesc, anum + 1);
5488                                 anum++;
5489                         }
5490                         else
5491                         {
5492                                 value = (Datum) 0;
5493                                 isnull = true;
5494
5495                                 /*
5496                                  * InvalidOid is OK because exec_assign_value doesn't care
5497                                  * about the type of a source NULL
5498                                  */
5499                                 valtype = InvalidOid;
5500                         }
5501
5502                         exec_assign_value(estate, (PLpgSQL_datum *) var,
5503                                                           value, valtype, &isnull);
5504                 }
5505
5506                 return;
5507         }
5508
5509         elog(ERROR, "unsupported target");
5510 }
5511
5512 /* ----------
5513  * make_tuple_from_row          Make a tuple from the values of a row object
5514  *
5515  * A NULL return indicates rowtype mismatch; caller must raise suitable error
5516  * ----------
5517  */
5518 static HeapTuple
5519 make_tuple_from_row(PLpgSQL_execstate *estate,
5520                                         PLpgSQL_row *row,
5521                                         TupleDesc tupdesc)
5522 {
5523         int                     natts = tupdesc->natts;
5524         HeapTuple       tuple;
5525         Datum      *dvalues;
5526         bool       *nulls;
5527         int                     i;
5528
5529         if (natts != row->nfields)
5530                 return NULL;
5531
5532         dvalues = (Datum *) palloc0(natts * sizeof(Datum));
5533         nulls = (bool *) palloc(natts * sizeof(bool));
5534
5535         for (i = 0; i < natts; i++)
5536         {
5537                 Oid                     fieldtypeid;
5538                 int32           fieldtypmod;
5539
5540                 if (tupdesc->attrs[i]->attisdropped)
5541                 {
5542                         nulls[i] = true;        /* leave the column as null */
5543                         continue;
5544                 }
5545                 if (row->varnos[i] < 0) /* should not happen */
5546                         elog(ERROR, "dropped rowtype entry for non-dropped column");
5547
5548                 exec_eval_datum(estate, estate->datums[row->varnos[i]],
5549                                                 &fieldtypeid, &fieldtypmod,
5550                                                 &dvalues[i], &nulls[i]);
5551                 if (fieldtypeid != tupdesc->attrs[i]->atttypid)
5552                         return NULL;
5553                 /* XXX should we insist on typmod match, too? */
5554         }
5555
5556         tuple = heap_form_tuple(tupdesc, dvalues, nulls);
5557
5558         pfree(dvalues);
5559         pfree(nulls);
5560
5561         return tuple;
5562 }
5563
5564 /* ----------
5565  * get_tuple_from_datum         extract a tuple from a composite Datum
5566  *
5567  * Returns a freshly palloc'd HeapTuple.
5568  *
5569  * Note: it's caller's responsibility to be sure value is of composite type.
5570  * ----------
5571  */
5572 static HeapTuple
5573 get_tuple_from_datum(Datum value)
5574 {
5575         HeapTupleHeader td = DatumGetHeapTupleHeader(value);
5576         HeapTupleData tmptup;
5577
5578         /* Build a temporary HeapTuple control structure */
5579         tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
5580         ItemPointerSetInvalid(&(tmptup.t_self));
5581         tmptup.t_tableOid = InvalidOid;
5582         tmptup.t_data = td;
5583
5584         /* Build a copy and return it */
5585         return heap_copytuple(&tmptup);
5586 }
5587
5588 /* ----------
5589  * get_tupdesc_from_datum       get a tuple descriptor for a composite Datum
5590  *
5591  * Returns a pointer to the TupleDesc of the tuple's rowtype.
5592  * Caller is responsible for calling ReleaseTupleDesc when done with it.
5593  *
5594  * Note: it's caller's responsibility to be sure value is of composite type.
5595  * ----------
5596  */
5597 static TupleDesc
5598 get_tupdesc_from_datum(Datum value)
5599 {
5600         HeapTupleHeader td = DatumGetHeapTupleHeader(value);
5601         Oid                     tupType;
5602         int32           tupTypmod;
5603
5604         /* Extract rowtype info and find a tupdesc */
5605         tupType = HeapTupleHeaderGetTypeId(td);
5606         tupTypmod = HeapTupleHeaderGetTypMod(td);
5607         return lookup_rowtype_tupdesc(tupType, tupTypmod);
5608 }
5609
5610 /* ----------
5611  * exec_move_row_from_datum             Move a composite Datum into a record or row
5612  *
5613  * This is equivalent to get_tuple_from_datum() followed by exec_move_row(),
5614  * but we avoid constructing an intermediate physical copy of the tuple.
5615  * ----------
5616  */
5617 static void
5618 exec_move_row_from_datum(PLpgSQL_execstate *estate,
5619                                                  PLpgSQL_rec *rec,
5620                                                  PLpgSQL_row *row,
5621                                                  Datum value)
5622 {
5623         HeapTupleHeader td = DatumGetHeapTupleHeader(value);
5624         Oid                     tupType;
5625         int32           tupTypmod;
5626         TupleDesc       tupdesc;
5627         HeapTupleData tmptup;
5628
5629         /* Extract rowtype info and find a tupdesc */
5630         tupType = HeapTupleHeaderGetTypeId(td);
5631         tupTypmod = HeapTupleHeaderGetTypMod(td);
5632         tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
5633
5634         /* Build a temporary HeapTuple control structure */
5635         tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
5636         ItemPointerSetInvalid(&(tmptup.t_self));
5637         tmptup.t_tableOid = InvalidOid;
5638         tmptup.t_data = td;
5639
5640         /* Do the move */
5641         exec_move_row(estate, rec, row, &tmptup, tupdesc);
5642
5643         /* Release tupdesc usage count */
5644         ReleaseTupleDesc(tupdesc);
5645 }
5646
5647 /* ----------
5648  * convert_value_to_string                      Convert a non-null Datum to C string
5649  *
5650  * Note: the result is in the estate's eval_econtext, and will be cleared
5651  * by the next exec_eval_cleanup() call.  The invoked output function might
5652  * leave additional cruft there as well, so just pfree'ing the result string
5653  * would not be enough to avoid memory leaks if we did not do it like this.
5654  * In most usages the Datum being passed in is also in that context (if
5655  * pass-by-reference) and so an exec_eval_cleanup() call is needed anyway.
5656  *
5657  * Note: not caching the conversion function lookup is bad for performance.
5658  * ----------
5659  */
5660 static char *
5661 convert_value_to_string(PLpgSQL_execstate *estate, Datum value, Oid valtype)
5662 {
5663         char       *result;
5664         MemoryContext oldcontext;
5665         Oid                     typoutput;
5666         bool            typIsVarlena;
5667
5668         oldcontext = MemoryContextSwitchTo(estate->eval_econtext->ecxt_per_tuple_memory);
5669         getTypeOutputInfo(valtype, &typoutput, &typIsVarlena);
5670         result = OidOutputFunctionCall(typoutput, value);
5671         MemoryContextSwitchTo(oldcontext);
5672
5673         return result;
5674 }
5675
5676 /* ----------
5677  * exec_cast_value                      Cast a value if required
5678  *
5679  * Note: the estate's eval_econtext is used for temporary storage, and may
5680  * also contain the result Datum if we have to do a conversion to a pass-
5681  * by-reference data type.  Be sure to do an exec_eval_cleanup() call when
5682  * done with the result.
5683  * ----------
5684  */
5685 static Datum
5686 exec_cast_value(PLpgSQL_execstate *estate,
5687                                 Datum value, Oid valtype,
5688                                 Oid reqtype,
5689                                 FmgrInfo *reqinput,
5690                                 Oid reqtypioparam,
5691                                 int32 reqtypmod,
5692                                 bool isnull)
5693 {
5694         /*
5695          * If the type of the given value isn't what's requested, convert it.
5696          */
5697         if (valtype != reqtype || reqtypmod != -1)
5698         {
5699                 MemoryContext oldcontext;
5700
5701                 oldcontext = MemoryContextSwitchTo(estate->eval_econtext->ecxt_per_tuple_memory);
5702                 if (!isnull)
5703                 {
5704                         char       *extval;
5705
5706                         extval = convert_value_to_string(estate, value, valtype);
5707                         value = InputFunctionCall(reqinput, extval,
5708                                                                           reqtypioparam, reqtypmod);
5709                 }
5710                 else
5711                 {
5712                         value = InputFunctionCall(reqinput, NULL,
5713                                                                           reqtypioparam, reqtypmod);
5714                 }
5715                 MemoryContextSwitchTo(oldcontext);
5716         }
5717
5718         return value;
5719 }
5720
5721 /* ----------
5722  * exec_simple_cast_value                       Cast a value if required
5723  *
5724  * As above, but need not supply details about target type.  Note that this
5725  * is slower than exec_cast_value with cached type info, and so should be
5726  * avoided in heavily used code paths.
5727  * ----------
5728  */
5729 static Datum
5730 exec_simple_cast_value(PLpgSQL_execstate *estate,
5731                                            Datum value, Oid valtype,
5732                                            Oid reqtype, int32 reqtypmod,
5733                                            bool isnull)
5734 {
5735         if (valtype != reqtype || reqtypmod != -1)
5736         {
5737                 Oid                     typinput;
5738                 Oid                     typioparam;
5739                 FmgrInfo        finfo_input;
5740
5741                 getTypeInputInfo(reqtype, &typinput, &typioparam);
5742
5743                 fmgr_info(typinput, &finfo_input);
5744
5745                 value = exec_cast_value(estate,
5746                                                                 value,
5747                                                                 valtype,
5748                                                                 reqtype,
5749                                                                 &finfo_input,
5750                                                                 typioparam,
5751                                                                 reqtypmod,
5752                                                                 isnull);
5753         }
5754
5755         return value;
5756 }
5757
5758
5759 /* ----------
5760  * exec_simple_check_node -             Recursively check if an expression
5761  *                                                              is made only of simple things we can
5762  *                                                              hand out directly to ExecEvalExpr()
5763  *                                                              instead of calling SPI.
5764  * ----------
5765  */
5766 static bool
5767 exec_simple_check_node(Node *node)
5768 {
5769         if (node == NULL)
5770                 return TRUE;
5771
5772         switch (nodeTag(node))
5773         {
5774                 case T_Const:
5775                         return TRUE;
5776
5777                 case T_Param:
5778                         return TRUE;
5779
5780                 case T_ArrayRef:
5781                         {
5782                                 ArrayRef   *expr = (ArrayRef *) node;
5783
5784                                 if (!exec_simple_check_node((Node *) expr->refupperindexpr))
5785                                         return FALSE;
5786                                 if (!exec_simple_check_node((Node *) expr->reflowerindexpr))
5787                                         return FALSE;
5788                                 if (!exec_simple_check_node((Node *) expr->refexpr))
5789                                         return FALSE;
5790                                 if (!exec_simple_check_node((Node *) expr->refassgnexpr))
5791                                         return FALSE;
5792
5793                                 return TRUE;
5794                         }
5795
5796                 case T_FuncExpr:
5797                         {
5798                                 FuncExpr   *expr = (FuncExpr *) node;
5799
5800                                 if (expr->funcretset)
5801                                         return FALSE;
5802                                 if (!exec_simple_check_node((Node *) expr->args))
5803                                         return FALSE;
5804
5805                                 return TRUE;
5806                         }
5807
5808                 case T_OpExpr:
5809                         {
5810                                 OpExpr     *expr = (OpExpr *) node;
5811
5812                                 if (expr->opretset)
5813                                         return FALSE;
5814                                 if (!exec_simple_check_node((Node *) expr->args))
5815                                         return FALSE;
5816
5817                                 return TRUE;
5818                         }
5819
5820                 case T_DistinctExpr:
5821                         {
5822                                 DistinctExpr *expr = (DistinctExpr *) node;
5823
5824                                 if (expr->opretset)
5825                                         return FALSE;
5826                                 if (!exec_simple_check_node((Node *) expr->args))
5827                                         return FALSE;
5828
5829                                 return TRUE;
5830                         }
5831
5832                 case T_NullIfExpr:
5833                         {
5834                                 NullIfExpr *expr = (NullIfExpr *) node;
5835
5836                                 if (expr->opretset)
5837                                         return FALSE;
5838                                 if (!exec_simple_check_node((Node *) expr->args))
5839                                         return FALSE;
5840
5841                                 return TRUE;
5842                         }
5843
5844                 case T_ScalarArrayOpExpr:
5845                         {
5846                                 ScalarArrayOpExpr *expr = (ScalarArrayOpExpr *) node;
5847
5848                                 if (!exec_simple_check_node((Node *) expr->args))
5849                                         return FALSE;
5850
5851                                 return TRUE;
5852                         }
5853
5854                 case T_BoolExpr:
5855                         {
5856                                 BoolExpr   *expr = (BoolExpr *) node;
5857
5858                                 if (!exec_simple_check_node((Node *) expr->args))
5859                                         return FALSE;
5860
5861                                 return TRUE;
5862                         }
5863
5864                 case T_FieldSelect:
5865                         return exec_simple_check_node((Node *) ((FieldSelect *) node)->arg);
5866
5867                 case T_FieldStore:
5868                         {
5869                                 FieldStore *expr = (FieldStore *) node;
5870
5871                                 if (!exec_simple_check_node((Node *) expr->arg))
5872                                         return FALSE;
5873                                 if (!exec_simple_check_node((Node *) expr->newvals))
5874                                         return FALSE;
5875
5876                                 return TRUE;
5877                         }
5878
5879                 case T_RelabelType:
5880                         return exec_simple_check_node((Node *) ((RelabelType *) node)->arg);
5881
5882                 case T_CoerceViaIO:
5883                         return exec_simple_check_node((Node *) ((CoerceViaIO *) node)->arg);
5884
5885                 case T_ArrayCoerceExpr:
5886                         return exec_simple_check_node((Node *) ((ArrayCoerceExpr *) node)->arg);
5887
5888                 case T_ConvertRowtypeExpr:
5889                         return exec_simple_check_node((Node *) ((ConvertRowtypeExpr *) node)->arg);
5890
5891                 case T_CaseExpr:
5892                         {
5893                                 CaseExpr   *expr = (CaseExpr *) node;
5894
5895                                 if (!exec_simple_check_node((Node *) expr->arg))
5896                                         return FALSE;
5897                                 if (!exec_simple_check_node((Node *) expr->args))
5898                                         return FALSE;
5899                                 if (!exec_simple_check_node((Node *) expr->defresult))
5900                                         return FALSE;
5901
5902                                 return TRUE;
5903                         }
5904
5905                 case T_CaseWhen:
5906                         {
5907                                 CaseWhen   *when = (CaseWhen *) node;
5908
5909                                 if (!exec_simple_check_node((Node *) when->expr))
5910                                         return FALSE;
5911                                 if (!exec_simple_check_node((Node *) when->result))
5912                                         return FALSE;
5913
5914                                 return TRUE;
5915                         }
5916
5917                 case T_CaseTestExpr:
5918                         return TRUE;
5919
5920                 case T_ArrayExpr:
5921                         {
5922                                 ArrayExpr  *expr = (ArrayExpr *) node;
5923
5924                                 if (!exec_simple_check_node((Node *) expr->elements))
5925                                         return FALSE;
5926
5927                                 return TRUE;
5928                         }
5929
5930                 case T_RowExpr:
5931                         {
5932                                 RowExpr    *expr = (RowExpr *) node;
5933
5934                                 if (!exec_simple_check_node((Node *) expr->args))
5935                                         return FALSE;
5936
5937                                 return TRUE;
5938                         }
5939
5940                 case T_RowCompareExpr:
5941                         {
5942                                 RowCompareExpr *expr = (RowCompareExpr *) node;
5943
5944                                 if (!exec_simple_check_node((Node *) expr->largs))
5945                                         return FALSE;
5946                                 if (!exec_simple_check_node((Node *) expr->rargs))
5947                                         return FALSE;
5948
5949                                 return TRUE;
5950                         }
5951
5952                 case T_CoalesceExpr:
5953                         {
5954                                 CoalesceExpr *expr = (CoalesceExpr *) node;
5955
5956                                 if (!exec_simple_check_node((Node *) expr->args))
5957                                         return FALSE;
5958
5959                                 return TRUE;
5960                         }
5961
5962                 case T_MinMaxExpr:
5963                         {
5964                                 MinMaxExpr *expr = (MinMaxExpr *) node;
5965
5966                                 if (!exec_simple_check_node((Node *) expr->args))
5967                                         return FALSE;
5968
5969                                 return TRUE;
5970                         }
5971
5972                 case T_XmlExpr:
5973                         {
5974                                 XmlExpr    *expr = (XmlExpr *) node;
5975
5976                                 if (!exec_simple_check_node((Node *) expr->named_args))
5977                                         return FALSE;
5978                                 if (!exec_simple_check_node((Node *) expr->args))
5979                                         return FALSE;
5980
5981                                 return TRUE;
5982                         }
5983
5984                 case T_NullTest:
5985                         return exec_simple_check_node((Node *) ((NullTest *) node)->arg);
5986
5987                 case T_BooleanTest:
5988                         return exec_simple_check_node((Node *) ((BooleanTest *) node)->arg);
5989
5990                 case T_CoerceToDomain:
5991                         return exec_simple_check_node((Node *) ((CoerceToDomain *) node)->arg);
5992
5993                 case T_CoerceToDomainValue:
5994                         return TRUE;
5995
5996                 case T_List:
5997                         {
5998                                 List       *expr = (List *) node;
5999                                 ListCell   *l;
6000
6001                                 foreach(l, expr)
6002                                 {
6003                                         if (!exec_simple_check_node(lfirst(l)))
6004                                                 return FALSE;
6005                                 }
6006
6007                                 return TRUE;
6008                         }
6009
6010                 default:
6011                         return FALSE;
6012         }
6013 }
6014
6015
6016 /* ----------
6017  * exec_simple_check_plan -             Check if a plan is simple enough to
6018  *                                                              be evaluated by ExecEvalExpr() instead
6019  *                                                              of SPI.
6020  * ----------
6021  */
6022 static void
6023 exec_simple_check_plan(PLpgSQL_expr *expr)
6024 {
6025         List       *plansources;
6026         CachedPlanSource *plansource;
6027         Query      *query;
6028         CachedPlan *cplan;
6029
6030         /*
6031          * Initialize to "not simple", and remember the plan generation number we
6032          * last checked.  (If we don't get as far as obtaining a plan to check, we
6033          * just leave expr_simple_generation set to 0.)
6034          */
6035         expr->expr_simple_expr = NULL;
6036         expr->expr_simple_generation = 0;
6037
6038         /*
6039          * We can only test queries that resulted in exactly one CachedPlanSource
6040          */
6041         plansources = SPI_plan_get_plan_sources(expr->plan);
6042         if (list_length(plansources) != 1)
6043                 return;
6044         plansource = (CachedPlanSource *) linitial(plansources);
6045
6046         /*
6047          * Do some checking on the analyzed-and-rewritten form of the query. These
6048          * checks are basically redundant with the tests in
6049          * exec_simple_recheck_plan, but the point is to avoid building a plan if
6050          * possible.  Since this function is only called immediately after
6051          * creating the CachedPlanSource, we need not worry about the query being
6052          * stale.
6053          */
6054
6055         /*
6056          * 1. There must be one single querytree.
6057          */
6058         if (list_length(plansource->query_list) != 1)
6059                 return;
6060         query = (Query *) linitial(plansource->query_list);
6061
6062         /*
6063          * 2. It must be a plain SELECT query without any input tables
6064          */
6065         if (!IsA(query, Query))
6066                 return;
6067         if (query->commandType != CMD_SELECT)
6068                 return;
6069         if (query->rtable != NIL)
6070                 return;
6071
6072         /*
6073          * 3. Can't have any subplans, aggregates, qual clauses either
6074          */
6075         if (query->hasAggs ||
6076                 query->hasWindowFuncs ||
6077                 query->hasSubLinks ||
6078                 query->hasForUpdate ||
6079                 query->cteList ||
6080                 query->jointree->quals ||
6081                 query->groupClause ||
6082                 query->havingQual ||
6083                 query->windowClause ||
6084                 query->distinctClause ||
6085                 query->sortClause ||
6086                 query->limitOffset ||
6087                 query->limitCount ||
6088                 query->setOperations)
6089                 return;
6090
6091         /*
6092          * 4. The query must have a single attribute as result
6093          */
6094         if (list_length(query->targetList) != 1)
6095                 return;
6096
6097         /*
6098          * OK, it seems worth constructing a plan for more careful checking.
6099          */
6100
6101         /* Get the generic plan for the query */
6102         cplan = SPI_plan_get_cached_plan(expr->plan);
6103
6104         /* Can't fail, because we checked for a single CachedPlanSource above */
6105         Assert(cplan != NULL);
6106
6107         /* Share the remaining work with recheck code path */
6108         exec_simple_recheck_plan(expr, cplan);
6109
6110         /* Release our plan refcount */
6111         ReleaseCachedPlan(cplan, true);
6112 }
6113
6114 /*
6115  * exec_simple_recheck_plan --- check for simple plan once we have CachedPlan
6116  */
6117 static void
6118 exec_simple_recheck_plan(PLpgSQL_expr *expr, CachedPlan *cplan)
6119 {
6120         PlannedStmt *stmt;
6121         Plan       *plan;
6122         TargetEntry *tle;
6123
6124         /*
6125          * Initialize to "not simple", and remember the plan generation number we
6126          * last checked.
6127          */
6128         expr->expr_simple_expr = NULL;
6129         expr->expr_simple_generation = cplan->generation;
6130
6131         /*
6132          * 1. There must be one single plantree
6133          */
6134         if (list_length(cplan->stmt_list) != 1)
6135                 return;
6136         stmt = (PlannedStmt *) linitial(cplan->stmt_list);
6137
6138         /*
6139          * 2. It must be a RESULT plan --> no scan's required
6140          */
6141         if (!IsA(stmt, PlannedStmt))
6142                 return;
6143         if (stmt->commandType != CMD_SELECT)
6144                 return;
6145         plan = stmt->planTree;
6146         if (!IsA(plan, Result))
6147                 return;
6148
6149         /*
6150          * 3. Can't have any subplan or qual clause, either
6151          */
6152         if (plan->lefttree != NULL ||
6153                 plan->righttree != NULL ||
6154                 plan->initPlan != NULL ||
6155                 plan->qual != NULL ||
6156                 ((Result *) plan)->resconstantqual != NULL)
6157                 return;
6158
6159         /*
6160          * 4. The plan must have a single attribute as result
6161          */
6162         if (list_length(plan->targetlist) != 1)
6163                 return;
6164
6165         tle = (TargetEntry *) linitial(plan->targetlist);
6166
6167         /*
6168          * 5. Check that all the nodes in the expression are non-scary.
6169          */
6170         if (!exec_simple_check_node((Node *) tle->expr))
6171                 return;
6172
6173         /*
6174          * Yes - this is a simple expression.  Mark it as such, and initialize
6175          * state to "not valid in current transaction".
6176          */
6177         expr->expr_simple_expr = tle->expr;
6178         expr->expr_simple_state = NULL;
6179         expr->expr_simple_in_use = false;
6180         expr->expr_simple_lxid = InvalidLocalTransactionId;
6181         /* Also stash away the expression result type */
6182         expr->expr_simple_type = exprType((Node *) tle->expr);
6183 }
6184
6185 /* ----------
6186  * exec_set_found                       Set the global found variable to true/false
6187  * ----------
6188  */
6189 static void
6190 exec_set_found(PLpgSQL_execstate *estate, bool state)
6191 {
6192         PLpgSQL_var *var;
6193
6194         var = (PLpgSQL_var *) (estate->datums[estate->found_varno]);
6195         var->value = BoolGetDatum(state);
6196         var->isnull = false;
6197 }
6198
6199 /*
6200  * plpgsql_create_econtext --- create an eval_econtext for the current function
6201  *
6202  * We may need to create a new shared_simple_eval_estate too, if there's not
6203  * one already for the current transaction.  The EState will be cleaned up at
6204  * transaction end.
6205  */
6206 static void
6207 plpgsql_create_econtext(PLpgSQL_execstate *estate)
6208 {
6209         SimpleEcontextStackEntry *entry;
6210
6211         /*
6212          * Create an EState for evaluation of simple expressions, if there's not
6213          * one already in the current transaction.  The EState is made a child of
6214          * TopTransactionContext so it will have the right lifespan.
6215          *
6216          * Note that this path is never taken when executing a DO block; the
6217          * required EState was already made by plpgsql_inline_handler.
6218          */
6219         if (estate->simple_eval_estate == NULL)
6220         {
6221                 MemoryContext oldcontext;
6222
6223                 Assert(shared_simple_eval_estate == NULL);
6224                 oldcontext = MemoryContextSwitchTo(TopTransactionContext);
6225                 shared_simple_eval_estate = CreateExecutorState();
6226                 estate->simple_eval_estate = shared_simple_eval_estate;
6227                 MemoryContextSwitchTo(oldcontext);
6228         }
6229
6230         /*
6231          * Create a child econtext for the current function.
6232          */
6233         estate->eval_econtext = CreateExprContext(estate->simple_eval_estate);
6234
6235         /*
6236          * Make a stack entry so we can clean up the econtext at subxact end.
6237          * Stack entries are kept in TopTransactionContext for simplicity.
6238          */
6239         entry = (SimpleEcontextStackEntry *)
6240                 MemoryContextAlloc(TopTransactionContext,
6241                                                    sizeof(SimpleEcontextStackEntry));
6242
6243         entry->stack_econtext = estate->eval_econtext;
6244         entry->xact_subxid = GetCurrentSubTransactionId();
6245
6246         entry->next = simple_econtext_stack;
6247         simple_econtext_stack = entry;
6248 }
6249
6250 /*
6251  * plpgsql_destroy_econtext --- destroy function's econtext
6252  *
6253  * We check that it matches the top stack entry, and destroy the stack
6254  * entry along with the context.
6255  */
6256 static void
6257 plpgsql_destroy_econtext(PLpgSQL_execstate *estate)
6258 {
6259         SimpleEcontextStackEntry *next;
6260
6261         Assert(simple_econtext_stack != NULL);
6262         Assert(simple_econtext_stack->stack_econtext == estate->eval_econtext);
6263
6264         next = simple_econtext_stack->next;
6265         pfree(simple_econtext_stack);
6266         simple_econtext_stack = next;
6267
6268         FreeExprContext(estate->eval_econtext, true);
6269         estate->eval_econtext = NULL;
6270 }
6271
6272 /*
6273  * plpgsql_xact_cb --- post-transaction-commit-or-abort cleanup
6274  *
6275  * If a simple-expression EState was created in the current transaction,
6276  * it has to be cleaned up.
6277  */
6278 void
6279 plpgsql_xact_cb(XactEvent event, void *arg)
6280 {
6281         /*
6282          * If we are doing a clean transaction shutdown, free the EState (so that
6283          * any remaining resources will be released correctly). In an abort, we
6284          * expect the regular abort recovery procedures to release everything of
6285          * interest.
6286          */
6287         if (event == XACT_EVENT_COMMIT || event == XACT_EVENT_PREPARE)
6288         {
6289                 /* Shouldn't be any econtext stack entries left at commit */
6290                 Assert(simple_econtext_stack == NULL);
6291
6292                 if (shared_simple_eval_estate)
6293                         FreeExecutorState(shared_simple_eval_estate);
6294                 shared_simple_eval_estate = NULL;
6295         }
6296         else if (event == XACT_EVENT_ABORT)
6297         {
6298                 simple_econtext_stack = NULL;
6299                 shared_simple_eval_estate = NULL;
6300         }
6301 }
6302
6303 /*
6304  * plpgsql_subxact_cb --- post-subtransaction-commit-or-abort cleanup
6305  *
6306  * Make sure any simple-expression econtexts created in the current
6307  * subtransaction get cleaned up.  We have to do this explicitly because
6308  * no other code knows which econtexts belong to which level of subxact.
6309  */
6310 void
6311 plpgsql_subxact_cb(SubXactEvent event, SubTransactionId mySubid,
6312                                    SubTransactionId parentSubid, void *arg)
6313 {
6314         if (event == SUBXACT_EVENT_COMMIT_SUB || event == SUBXACT_EVENT_ABORT_SUB)
6315         {
6316                 while (simple_econtext_stack != NULL &&
6317                            simple_econtext_stack->xact_subxid == mySubid)
6318                 {
6319                         SimpleEcontextStackEntry *next;
6320
6321                         FreeExprContext(simple_econtext_stack->stack_econtext,
6322                                                         (event == SUBXACT_EVENT_COMMIT_SUB));
6323                         next = simple_econtext_stack->next;
6324                         pfree(simple_econtext_stack);
6325                         simple_econtext_stack = next;
6326                 }
6327         }
6328 }
6329
6330 /*
6331  * free_var --- pfree any pass-by-reference value of the variable.
6332  *
6333  * This should always be followed by some assignment to var->value,
6334  * as it leaves a dangling pointer.
6335  */
6336 static void
6337 free_var(PLpgSQL_var *var)
6338 {
6339         if (var->freeval)
6340         {
6341                 pfree(DatumGetPointer(var->value));
6342                 var->freeval = false;
6343         }
6344 }
6345
6346 /*
6347  * free old value of a text variable and assign new value from C string
6348  */
6349 static void
6350 assign_text_var(PLpgSQL_var *var, const char *str)
6351 {
6352         free_var(var);
6353         var->value = CStringGetTextDatum(str);
6354         var->isnull = false;
6355         var->freeval = true;
6356 }
6357
6358 /*
6359  * exec_eval_using_params --- evaluate params of USING clause
6360  */
6361 static PreparedParamsData *
6362 exec_eval_using_params(PLpgSQL_execstate *estate, List *params)
6363 {
6364         PreparedParamsData *ppd;
6365         int                     nargs;
6366         int                     i;
6367         ListCell   *lc;
6368
6369         ppd = (PreparedParamsData *) palloc(sizeof(PreparedParamsData));
6370         nargs = list_length(params);
6371
6372         ppd->nargs = nargs;
6373         ppd->types = (Oid *) palloc(nargs * sizeof(Oid));
6374         ppd->values = (Datum *) palloc(nargs * sizeof(Datum));
6375         ppd->nulls = (char *) palloc(nargs * sizeof(char));
6376         ppd->freevals = (bool *) palloc(nargs * sizeof(bool));
6377
6378         i = 0;
6379         foreach(lc, params)
6380         {
6381                 PLpgSQL_expr *param = (PLpgSQL_expr *) lfirst(lc);
6382                 bool            isnull;
6383
6384                 ppd->values[i] = exec_eval_expr(estate, param,
6385                                                                                 &isnull,
6386                                                                                 &ppd->types[i]);
6387                 ppd->nulls[i] = isnull ? 'n' : ' ';
6388                 ppd->freevals[i] = false;
6389
6390                 if (ppd->types[i] == UNKNOWNOID)
6391                 {
6392                         /*
6393                          * Treat 'unknown' parameters as text, since that's what most
6394                          * people would expect. SPI_execute_with_args can coerce unknown
6395                          * constants in a more intelligent way, but not unknown Params.
6396                          * This code also takes care of copying into the right context.
6397                          * Note we assume 'unknown' has the representation of C-string.
6398                          */
6399                         ppd->types[i] = TEXTOID;
6400                         if (!isnull)
6401                         {
6402                                 ppd->values[i] = CStringGetTextDatum(DatumGetCString(ppd->values[i]));
6403                                 ppd->freevals[i] = true;
6404                         }
6405                 }
6406                 /* pass-by-ref non null values must be copied into plpgsql context */
6407                 else if (!isnull)
6408                 {
6409                         int16           typLen;
6410                         bool            typByVal;
6411
6412                         get_typlenbyval(ppd->types[i], &typLen, &typByVal);
6413                         if (!typByVal)
6414                         {
6415                                 ppd->values[i] = datumCopy(ppd->values[i], typByVal, typLen);
6416                                 ppd->freevals[i] = true;
6417                         }
6418                 }
6419
6420                 exec_eval_cleanup(estate);
6421
6422                 i++;
6423         }
6424
6425         return ppd;
6426 }
6427
6428 /*
6429  * free_params_data --- pfree all pass-by-reference values used in USING clause
6430  */
6431 static void
6432 free_params_data(PreparedParamsData *ppd)
6433 {
6434         int                     i;
6435
6436         for (i = 0; i < ppd->nargs; i++)
6437         {
6438                 if (ppd->freevals[i])
6439                         pfree(DatumGetPointer(ppd->values[i]));
6440         }
6441
6442         pfree(ppd->types);
6443         pfree(ppd->values);
6444         pfree(ppd->nulls);
6445         pfree(ppd->freevals);
6446
6447         pfree(ppd);
6448 }
6449
6450 /*
6451  * Open portal for dynamic query
6452  */
6453 static Portal
6454 exec_dynquery_with_params(PLpgSQL_execstate *estate,
6455                                                   PLpgSQL_expr *dynquery,
6456                                                   List *params,
6457                                                   const char *portalname,
6458                                                   int cursorOptions)
6459 {
6460         Portal          portal;
6461         Datum           query;
6462         bool            isnull;
6463         Oid                     restype;
6464         char       *querystr;
6465
6466         /*
6467          * Evaluate the string expression after the EXECUTE keyword. Its result is
6468          * the querystring we have to execute.
6469          */
6470         query = exec_eval_expr(estate, dynquery, &isnull, &restype);
6471         if (isnull)
6472                 ereport(ERROR,
6473                                 (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
6474                                  errmsg("query string argument of EXECUTE is null")));
6475
6476         /* Get the C-String representation */
6477         querystr = convert_value_to_string(estate, query, restype);
6478
6479         /* copy it out of the temporary context before we clean up */
6480         querystr = pstrdup(querystr);
6481
6482         exec_eval_cleanup(estate);
6483
6484         /*
6485          * Open an implicit cursor for the query.  We use
6486          * SPI_cursor_open_with_args even when there are no params, because this
6487          * avoids making and freeing one copy of the plan.
6488          */
6489         if (params)
6490         {
6491                 PreparedParamsData *ppd;
6492
6493                 ppd = exec_eval_using_params(estate, params);
6494                 portal = SPI_cursor_open_with_args(portalname,
6495                                                                                    querystr,
6496                                                                                    ppd->nargs, ppd->types,
6497                                                                                    ppd->values, ppd->nulls,
6498                                                                                    estate->readonly_func,
6499                                                                                    cursorOptions);
6500                 free_params_data(ppd);
6501         }
6502         else
6503         {
6504                 portal = SPI_cursor_open_with_args(portalname,
6505                                                                                    querystr,
6506                                                                                    0, NULL,
6507                                                                                    NULL, NULL,
6508                                                                                    estate->readonly_func,
6509                                                                                    cursorOptions);
6510         }
6511
6512         if (portal == NULL)
6513                 elog(ERROR, "could not open implicit cursor for query \"%s\": %s",
6514                          querystr, SPI_result_code_string(SPI_result));
6515         pfree(querystr);
6516
6517         return portal;
6518 }
6519
6520 /*
6521  * Return a formatted string with information about an expression's parameters,
6522  * or NULL if the expression does not take any parameters.
6523  */
6524 static char *
6525 format_expr_params(PLpgSQL_execstate *estate,
6526                                    const PLpgSQL_expr *expr)
6527 {
6528         int                     paramno;
6529         int                     dno;
6530         StringInfoData paramstr;
6531         Bitmapset  *tmpset;
6532
6533         if (!expr->paramnos)
6534                 return NULL;
6535
6536         initStringInfo(&paramstr);
6537         tmpset = bms_copy(expr->paramnos);
6538         paramno = 0;
6539         while ((dno = bms_first_member(tmpset)) >= 0)
6540         {
6541                 Datum           paramdatum;
6542                 Oid                     paramtypeid;
6543                 bool            paramisnull;
6544                 int32           paramtypmod;
6545                 PLpgSQL_var *curvar;
6546
6547                 curvar = (PLpgSQL_var *) estate->datums[dno];
6548
6549                 exec_eval_datum(estate, (PLpgSQL_datum *) curvar, &paramtypeid,
6550                                                 &paramtypmod, &paramdatum, &paramisnull);
6551
6552                 appendStringInfo(&paramstr, "%s%s = ",
6553                                                  paramno > 0 ? ", " : "",
6554                                                  curvar->refname);
6555
6556                 if (paramisnull)
6557                         appendStringInfoString(&paramstr, "NULL");
6558                 else
6559                 {
6560                         char       *value = convert_value_to_string(estate, paramdatum, paramtypeid);
6561                         char       *p;
6562
6563                         appendStringInfoCharMacro(&paramstr, '\'');
6564                         for (p = value; *p; p++)
6565                         {
6566                                 if (*p == '\'') /* double single quotes */
6567                                         appendStringInfoCharMacro(&paramstr, *p);
6568                                 appendStringInfoCharMacro(&paramstr, *p);
6569                         }
6570                         appendStringInfoCharMacro(&paramstr, '\'');
6571                 }
6572
6573                 paramno++;
6574         }
6575         bms_free(tmpset);
6576
6577         return paramstr.data;
6578 }
6579
6580 /*
6581  * Return a formatted string with information about PreparedParamsData, or NULL
6582  * if there are no parameters.
6583  */
6584 static char *
6585 format_preparedparamsdata(PLpgSQL_execstate *estate,
6586                                                   const PreparedParamsData *ppd)
6587 {
6588         int                     paramno;
6589         StringInfoData paramstr;
6590
6591         if (!ppd)
6592                 return NULL;
6593
6594         initStringInfo(&paramstr);
6595         for (paramno = 0; paramno < ppd->nargs; paramno++)
6596         {
6597                 appendStringInfo(&paramstr, "%s$%d = ",
6598                                                  paramno > 0 ? ", " : "",
6599                                                  paramno + 1);
6600
6601                 if (ppd->nulls[paramno] == 'n')
6602                         appendStringInfoString(&paramstr, "NULL");
6603                 else
6604                 {
6605                         char       *value = convert_value_to_string(estate, ppd->values[paramno], ppd->types[paramno]);
6606                         char       *p;
6607
6608                         appendStringInfoCharMacro(&paramstr, '\'');
6609                         for (p = value; *p; p++)
6610                         {
6611                                 if (*p == '\'') /* double single quotes */
6612                                         appendStringInfoCharMacro(&paramstr, *p);
6613                                 appendStringInfoCharMacro(&paramstr, *p);
6614                         }
6615                         appendStringInfoCharMacro(&paramstr, '\'');
6616                 }
6617         }
6618
6619         return paramstr.data;
6620 }