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