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