PostgreSQL Source Code  git master
pl_exec.c File Reference
#include "postgres.h"
#include <ctype.h>
#include "access/htup_details.h"
#include "access/transam.h"
#include "access/tupconvert.h"
#include "access/tuptoaster.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_type.h"
#include "commands/defrem.h"
#include "executor/execExpr.h"
#include "executor/spi.h"
#include "executor/spi_priv.h"
#include "funcapi.h"
#include "miscadmin.h"
#include "nodes/nodeFuncs.h"
#include "optimizer/optimizer.h"
#include "parser/parse_coerce.h"
#include "parser/parse_type.h"
#include "parser/scansup.h"
#include "storage/proc.h"
#include "tcop/tcopprot.h"
#include "tcop/utility.h"
#include "utils/array.h"
#include "utils/builtins.h"
#include "utils/datum.h"
#include "utils/fmgroids.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/rel.h"
#include "utils/snapmgr.h"
#include "utils/syscache.h"
#include "utils/typcache.h"
#include "plpgsql.h"
Include dependency graph for pl_exec.c:

Go to the source code of this file.

Data Structures

struct  PreparedParamsData
 
struct  SimpleEcontextStackEntry
 
struct  plpgsql_CastHashKey
 
struct  plpgsql_CastHashEntry
 

Macros

#define get_eval_mcontext(estate)   ((estate)->eval_econtext->ecxt_per_tuple_memory)
 
#define eval_mcontext_alloc(estate, sz)   MemoryContextAlloc(get_eval_mcontext(estate), sz)
 
#define eval_mcontext_alloc0(estate, sz)   MemoryContextAllocZero(get_eval_mcontext(estate), sz)
 
#define LOOP_RC_PROCESSING(looplabel, exit_action)
 
#define SET_RAISE_OPTION_TEXT(opt, name)
 

Typedefs

typedef struct SimpleEcontextStackEntry SimpleEcontextStackEntry
 

Functions

static void coerce_function_result_tuple (PLpgSQL_execstate *estate, TupleDesc tupdesc)
 
static void plpgsql_exec_error_callback (void *arg)
 
static void copy_plpgsql_datums (PLpgSQL_execstate *estate, PLpgSQL_function *func)
 
static void plpgsql_fulfill_promise (PLpgSQL_execstate *estate, PLpgSQL_var *var)
 
static MemoryContext get_stmt_mcontext (PLpgSQL_execstate *estate)
 
static void push_stmt_mcontext (PLpgSQL_execstate *estate)
 
static void pop_stmt_mcontext (PLpgSQL_execstate *estate)
 
static int exec_stmt_block (PLpgSQL_execstate *estate, PLpgSQL_stmt_block *block)
 
static int exec_stmts (PLpgSQL_execstate *estate, List *stmts)
 
static int exec_stmt (PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
 
static int exec_stmt_assign (PLpgSQL_execstate *estate, PLpgSQL_stmt_assign *stmt)
 
static int exec_stmt_perform (PLpgSQL_execstate *estate, PLpgSQL_stmt_perform *stmt)
 
static int exec_stmt_call (PLpgSQL_execstate *estate, PLpgSQL_stmt_call *stmt)
 
static int exec_stmt_getdiag (PLpgSQL_execstate *estate, PLpgSQL_stmt_getdiag *stmt)
 
static int exec_stmt_if (PLpgSQL_execstate *estate, PLpgSQL_stmt_if *stmt)
 
static int exec_stmt_case (PLpgSQL_execstate *estate, PLpgSQL_stmt_case *stmt)
 
static int exec_stmt_loop (PLpgSQL_execstate *estate, PLpgSQL_stmt_loop *stmt)
 
static int exec_stmt_while (PLpgSQL_execstate *estate, PLpgSQL_stmt_while *stmt)
 
static int exec_stmt_fori (PLpgSQL_execstate *estate, PLpgSQL_stmt_fori *stmt)
 
static int exec_stmt_fors (PLpgSQL_execstate *estate, PLpgSQL_stmt_fors *stmt)
 
static int exec_stmt_forc (PLpgSQL_execstate *estate, PLpgSQL_stmt_forc *stmt)
 
static int exec_stmt_foreach_a (PLpgSQL_execstate *estate, PLpgSQL_stmt_foreach_a *stmt)
 
static int exec_stmt_open (PLpgSQL_execstate *estate, PLpgSQL_stmt_open *stmt)
 
static int exec_stmt_fetch (PLpgSQL_execstate *estate, PLpgSQL_stmt_fetch *stmt)
 
static int exec_stmt_close (PLpgSQL_execstate *estate, PLpgSQL_stmt_close *stmt)
 
static int exec_stmt_exit (PLpgSQL_execstate *estate, PLpgSQL_stmt_exit *stmt)
 
static int exec_stmt_return (PLpgSQL_execstate *estate, PLpgSQL_stmt_return *stmt)
 
static int exec_stmt_return_next (PLpgSQL_execstate *estate, PLpgSQL_stmt_return_next *stmt)
 
static int exec_stmt_return_query (PLpgSQL_execstate *estate, PLpgSQL_stmt_return_query *stmt)
 
static int exec_stmt_raise (PLpgSQL_execstate *estate, PLpgSQL_stmt_raise *stmt)
 
static int exec_stmt_assert (PLpgSQL_execstate *estate, PLpgSQL_stmt_assert *stmt)
 
static int exec_stmt_execsql (PLpgSQL_execstate *estate, PLpgSQL_stmt_execsql *stmt)
 
static int exec_stmt_dynexecute (PLpgSQL_execstate *estate, PLpgSQL_stmt_dynexecute *stmt)
 
static int exec_stmt_dynfors (PLpgSQL_execstate *estate, PLpgSQL_stmt_dynfors *stmt)
 
static int exec_stmt_commit (PLpgSQL_execstate *estate, PLpgSQL_stmt_commit *stmt)
 
static int exec_stmt_rollback (PLpgSQL_execstate *estate, PLpgSQL_stmt_rollback *stmt)
 
static int exec_stmt_set (PLpgSQL_execstate *estate, PLpgSQL_stmt_set *stmt)
 
static void plpgsql_estate_setup (PLpgSQL_execstate *estate, PLpgSQL_function *func, ReturnSetInfo *rsi, EState *simple_eval_estate)
 
static void exec_eval_cleanup (PLpgSQL_execstate *estate)
 
static void exec_prepare_plan (PLpgSQL_execstate *estate, PLpgSQL_expr *expr, int cursorOptions, bool keepplan)
 
static void exec_simple_check_plan (PLpgSQL_execstate *estate, PLpgSQL_expr *expr)
 
static void exec_save_simple_expr (PLpgSQL_expr *expr, CachedPlan *cplan)
 
static void exec_check_rw_parameter (PLpgSQL_expr *expr, int target_dno)
 
static bool contains_target_param (Node *node, int *target_dno)
 
static bool exec_eval_simple_expr (PLpgSQL_execstate *estate, PLpgSQL_expr *expr, Datum *result, bool *isNull, Oid *rettype, int32 *rettypmod)
 
static void exec_assign_expr (PLpgSQL_execstate *estate, PLpgSQL_datum *target, PLpgSQL_expr *expr)
 
static void exec_assign_c_string (PLpgSQL_execstate *estate, PLpgSQL_datum *target, const char *str)
 
static void exec_assign_value (PLpgSQL_execstate *estate, PLpgSQL_datum *target, Datum value, bool isNull, Oid valtype, int32 valtypmod)
 
static void exec_eval_datum (PLpgSQL_execstate *estate, PLpgSQL_datum *datum, Oid *typeid, int32 *typetypmod, Datum *value, bool *isnull)
 
static int exec_eval_integer (PLpgSQL_execstate *estate, PLpgSQL_expr *expr, bool *isNull)
 
static bool exec_eval_boolean (PLpgSQL_execstate *estate, PLpgSQL_expr *expr, bool *isNull)
 
static Datum exec_eval_expr (PLpgSQL_execstate *estate, PLpgSQL_expr *expr, bool *isNull, Oid *rettype, int32 *rettypmod)
 
static int exec_run_select (PLpgSQL_execstate *estate, PLpgSQL_expr *expr, long maxtuples, Portal *portalP)
 
static int exec_for_query (PLpgSQL_execstate *estate, PLpgSQL_stmt_forq *stmt, Portal portal, bool prefetch_ok)
 
static ParamListInfo setup_param_list (PLpgSQL_execstate *estate, PLpgSQL_expr *expr)
 
static ParamExternDataplpgsql_param_fetch (ParamListInfo params, int paramid, bool speculative, ParamExternData *workspace)
 
static void plpgsql_param_compile (ParamListInfo params, Param *param, ExprState *state, Datum *resv, bool *resnull)
 
static void plpgsql_param_eval_var (ExprState *state, ExprEvalStep *op, ExprContext *econtext)
 
static void plpgsql_param_eval_var_ro (ExprState *state, ExprEvalStep *op, ExprContext *econtext)
 
static void plpgsql_param_eval_recfield (ExprState *state, ExprEvalStep *op, ExprContext *econtext)
 
static void plpgsql_param_eval_generic (ExprState *state, ExprEvalStep *op, ExprContext *econtext)
 
static void plpgsql_param_eval_generic_ro (ExprState *state, ExprEvalStep *op, ExprContext *econtext)
 
static void exec_move_row (PLpgSQL_execstate *estate, PLpgSQL_variable *target, HeapTuple tup, TupleDesc tupdesc)
 
static void revalidate_rectypeid (PLpgSQL_rec *rec)
 
static ExpandedRecordHeadermake_expanded_record_for_rec (PLpgSQL_execstate *estate, PLpgSQL_rec *rec, TupleDesc srctupdesc, ExpandedRecordHeader *srcerh)
 
static void exec_move_row_from_fields (PLpgSQL_execstate *estate, PLpgSQL_variable *target, ExpandedRecordHeader *newerh, Datum *values, bool *nulls, TupleDesc tupdesc)
 
static bool compatible_tupdescs (TupleDesc src_tupdesc, TupleDesc dst_tupdesc)
 
static HeapTuple make_tuple_from_row (PLpgSQL_execstate *estate, PLpgSQL_row *row, TupleDesc tupdesc)
 
static TupleDesc deconstruct_composite_datum (Datum value, HeapTupleData *tmptup)
 
static void exec_move_row_from_datum (PLpgSQL_execstate *estate, PLpgSQL_variable *target, Datum value)
 
static void instantiate_empty_record_variable (PLpgSQL_execstate *estate, PLpgSQL_rec *rec)
 
static char * convert_value_to_string (PLpgSQL_execstate *estate, Datum value, Oid valtype)
 
static Datum exec_cast_value (PLpgSQL_execstate *estate, Datum value, bool *isnull, Oid valtype, int32 valtypmod, Oid reqtype, int32 reqtypmod)
 
static plpgsql_CastHashEntryget_cast_hashentry (PLpgSQL_execstate *estate, Oid srctype, int32 srctypmod, Oid dsttype, int32 dsttypmod)
 
static void exec_init_tuple_store (PLpgSQL_execstate *estate)
 
static void exec_set_found (PLpgSQL_execstate *estate, bool state)
 
static void plpgsql_create_econtext (PLpgSQL_execstate *estate)
 
static void plpgsql_destroy_econtext (PLpgSQL_execstate *estate)
 
static void assign_simple_var (PLpgSQL_execstate *estate, PLpgSQL_var *var, Datum newvalue, bool isnull, bool freeable)
 
static void assign_text_var (PLpgSQL_execstate *estate, PLpgSQL_var *var, const char *str)
 
static void assign_record_var (PLpgSQL_execstate *estate, PLpgSQL_rec *rec, ExpandedRecordHeader *erh)
 
static PreparedParamsDataexec_eval_using_params (PLpgSQL_execstate *estate, List *params)
 
static Portal exec_dynquery_with_params (PLpgSQL_execstate *estate, PLpgSQL_expr *dynquery, List *params, const char *portalname, int cursorOptions)
 
static char * format_expr_params (PLpgSQL_execstate *estate, const PLpgSQL_expr *expr)
 
static char * format_preparedparamsdata (PLpgSQL_execstate *estate, const PreparedParamsData *ppd)
 
Datum plpgsql_exec_function (PLpgSQL_function *func, FunctionCallInfo fcinfo, EState *simple_eval_estate, bool atomic)
 
HeapTuple plpgsql_exec_trigger (PLpgSQL_function *func, TriggerData *trigdata)
 
void plpgsql_exec_event_trigger (PLpgSQL_function *func, EventTriggerData *trigdata)
 
static bool exception_matches_conditions (ErrorData *edata, PLpgSQL_condition *cond)
 
Oid plpgsql_exec_get_datum_type (PLpgSQL_execstate *estate, PLpgSQL_datum *datum)
 
void plpgsql_exec_get_datum_type_info (PLpgSQL_execstate *estate, PLpgSQL_datum *datum, Oid *typeId, int32 *typMod, Oid *collation)
 
void plpgsql_xact_cb (XactEvent event, void *arg)
 
void plpgsql_subxact_cb (SubXactEvent event, SubTransactionId mySubid, SubTransactionId parentSubid, void *arg)
 

Variables

static EStateshared_simple_eval_estate = NULL
 
static SimpleEcontextStackEntrysimple_econtext_stack = NULL
 
static MemoryContext shared_cast_context = NULL
 
static HTABshared_cast_hash = NULL
 

Macro Definition Documentation

◆ eval_mcontext_alloc

#define eval_mcontext_alloc (   estate,
  sz 
)    MemoryContextAlloc(get_eval_mcontext(estate), sz)

◆ eval_mcontext_alloc0

#define eval_mcontext_alloc0 (   estate,
  sz 
)    MemoryContextAllocZero(get_eval_mcontext(estate), sz)

Definition at line 125 of file pl_exec.c.

Referenced by exec_stmt_return_next(), and make_tuple_from_row().

◆ get_eval_mcontext

◆ LOOP_RC_PROCESSING

#define LOOP_RC_PROCESSING (   looplabel,
  exit_action 
)

◆ SET_RAISE_OPTION_TEXT

#define SET_RAISE_OPTION_TEXT (   opt,
  name 
)
Value:
do { \
if (opt) \
ereport(ERROR, \
(errcode(ERRCODE_SYNTAX_ERROR), \
errmsg("RAISE option already specified: %s", \
name))); \
opt = MemoryContextStrdup(stmt_mcontext, extval); \
} while (0)
int errcode(int sqlerrcode)
Definition: elog.c:570
#define ERROR
Definition: elog.h:43
const char * name
Definition: encode.c:521
int errmsg(const char *fmt,...)
Definition: elog.c:784
char * MemoryContextStrdup(MemoryContext context, const char *string)
Definition: mcxt.c:1148

Definition at line 3607 of file pl_exec.c.

Referenced by exec_stmt_raise().

Typedef Documentation

◆ SimpleEcontextStackEntry

Function Documentation

◆ assign_record_var()

static void assign_record_var ( PLpgSQL_execstate estate,
PLpgSQL_rec rec,
ExpandedRecordHeader erh 
)
static

Definition at line 8394 of file pl_exec.c.

References Assert, PLpgSQL_execstate::datum_context, DeleteExpandedObject(), PLpgSQL_rec::dtype, PLpgSQL_rec::erh, ExpandedRecordGetDatum, PLPGSQL_DTYPE_REC, and TransferExpandedRecord.

Referenced by exec_move_row(), exec_move_row_from_datum(), and exec_move_row_from_fields().

8396 {
8397  Assert(rec->dtype == PLPGSQL_DTYPE_REC);
8398 
8399  /* Transfer new record object into datum_context */
8400  TransferExpandedRecord(erh, estate->datum_context);
8401 
8402  /* Free the old value ... */
8403  if (rec->erh)
8405 
8406  /* ... and install the new */
8407  rec->erh = erh;
8408 }
PLpgSQL_datum_type dtype
Definition: plpgsql.h:371
ExpandedRecordHeader * erh
Definition: plpgsql.h:394
void DeleteExpandedObject(Datum d)
#define Assert(condition)
Definition: c.h:732
#define TransferExpandedRecord(erh, cxt)
MemoryContext datum_context
Definition: plpgsql.h:1073
#define ExpandedRecordGetDatum(erh)

◆ assign_simple_var()

static void assign_simple_var ( PLpgSQL_execstate estate,
PLpgSQL_var var,
Datum  newvalue,
bool  isnull,
bool  freeable 
)
static

Definition at line 8318 of file pl_exec.c.

References Assert, PLpgSQL_execstate::atomic, PLpgSQL_var::datatype, datumCopy(), DatumGetPointer, DatumIsReadWriteExpandedObject, DeleteExpandedObject(), PLpgSQL_var::dtype, PLpgSQL_var::freeval, get_eval_mcontext, heap_tuple_fetch_attr(), PLpgSQL_var::isnull, MemoryContextSwitchTo(), pfree(), PLPGSQL_DTYPE_PROMISE, PLPGSQL_DTYPE_VAR, PLPGSQL_PROMISE_NONE, PointerGetDatum, PLpgSQL_var::promise, PLpgSQL_type::typlen, PLpgSQL_var::value, and VARATT_IS_EXTERNAL_NON_EXPANDED.

Referenced by assign_text_var(), exec_assign_value(), exec_set_found(), exec_stmt_block(), exec_stmt_case(), exec_stmt_forc(), exec_stmt_fori(), plpgsql_exec_function(), and plpgsql_fulfill_promise().

8320 {
8321  Assert(var->dtype == PLPGSQL_DTYPE_VAR ||
8322  var->dtype == PLPGSQL_DTYPE_PROMISE);
8323 
8324  /*
8325  * In non-atomic contexts, we do not want to store TOAST pointers in
8326  * variables, because such pointers might become stale after a commit.
8327  * Forcibly detoast in such cases. We don't want to detoast (flatten)
8328  * expanded objects, however; those should be OK across a transaction
8329  * boundary since they're just memory-resident objects. (Elsewhere in
8330  * this module, operations on expanded records likewise need to request
8331  * detoasting of record fields when !estate->atomic. Expanded arrays are
8332  * not a problem since all array entries are always detoasted.)
8333  */
8334  if (!estate->atomic && !isnull && var->datatype->typlen == -1 &&
8336  {
8337  MemoryContext oldcxt;
8338  Datum detoasted;
8339 
8340  /*
8341  * Do the detoasting in the eval_mcontext to avoid long-term leakage
8342  * of whatever memory toast fetching might leak. Then we have to copy
8343  * the detoasted datum to the function's main context, which is a
8344  * pain, but there's little choice.
8345  */
8346  oldcxt = MemoryContextSwitchTo(get_eval_mcontext(estate));
8347  detoasted = PointerGetDatum(heap_tuple_fetch_attr((struct varlena *) DatumGetPointer(newvalue)));
8348  MemoryContextSwitchTo(oldcxt);
8349  /* Now's a good time to not leak the input value if it's freeable */
8350  if (freeable)
8351  pfree(DatumGetPointer(newvalue));
8352  /* Once we copy the value, it's definitely freeable */
8353  newvalue = datumCopy(detoasted, false, -1);
8354  freeable = true;
8355  /* Can't clean up eval_mcontext here, but it'll happen before long */
8356  }
8357 
8358  /* Free the old value if needed */
8359  if (var->freeval)
8360  {
8362  var->isnull,
8363  var->datatype->typlen))
8365  else
8366  pfree(DatumGetPointer(var->value));
8367  }
8368  /* Assign new value to datum */
8369  var->value = newvalue;
8370  var->isnull = isnull;
8371  var->freeval = freeable;
8372 
8373  /*
8374  * If it's a promise variable, then either we just assigned the promised
8375  * value, or the user explicitly assigned an overriding value. Either
8376  * way, cancel the promise.
8377  */
8379 }
PLpgSQL_promise_type promise
Definition: plpgsql.h:322
#define VARATT_IS_EXTERNAL_NON_EXPANDED(PTR)
Definition: postgres.h:324
PLpgSQL_datum_type dtype
Definition: plpgsql.h:291
#define PointerGetDatum(X)
Definition: postgres.h:556
struct varlena * heap_tuple_fetch_attr(struct varlena *attr)
Definition: tuptoaster.c:101
PLpgSQL_type * datatype
Definition: plpgsql.h:300
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void pfree(void *pointer)
Definition: mcxt.c:1031
bool freeval
Definition: plpgsql.h:315
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition: datum.c:130
#define get_eval_mcontext(estate)
Definition: pl_exec.c:121
uintptr_t Datum
Definition: postgres.h:367
Datum value
Definition: plpgsql.h:313
void DeleteExpandedObject(Datum d)
#define Assert(condition)
Definition: c.h:732
#define DatumIsReadWriteExpandedObject(d, isnull, typlen)
#define DatumGetPointer(X)
Definition: postgres.h:549
Definition: c.h:549
int16 typlen
Definition: plpgsql.h:204
bool isnull
Definition: plpgsql.h:314

◆ assign_text_var()

static void assign_text_var ( PLpgSQL_execstate estate,
PLpgSQL_var var,
const char *  str 
)
static

Definition at line 8385 of file pl_exec.c.

References assign_simple_var(), and CStringGetTextDatum.

Referenced by exec_stmt_block(), exec_stmt_forc(), exec_stmt_open(), and plpgsql_fulfill_promise().

8386 {
8387  assign_simple_var(estate, var, CStringGetTextDatum(str), false, true);
8388 }
static void assign_simple_var(PLpgSQL_execstate *estate, PLpgSQL_var *var, Datum newvalue, bool isnull, bool freeable)
Definition: pl_exec.c:8318
#define CStringGetTextDatum(s)
Definition: builtins.h:83

◆ coerce_function_result_tuple()

static void coerce_function_result_tuple ( PLpgSQL_execstate estate,
TupleDesc  tupdesc 
)
static

Definition at line 775 of file pl_exec.c.

References Assert, convert_tuples_by_position(), DatumGetEOHP(), DatumGetPointer, deconstruct_composite_datum(), EOH_flatten_into(), EOH_get_flat_size(), ExpandedRecordHeader::er_decltypeid, ER_MAGIC, ExpandedRecordHeader::er_magic, execute_attr_map_tuple(), expanded_record_get_tupdesc(), expanded_record_get_tuple(), ExpandedRecordIsDomain, gettext_noop, ExpandedRecordHeader::hdr, HeapTupleHeaderSetTypeId, HeapTupleHeaderSetTypMod, PointerGetDatum, ReleaseTupleDesc, PLpgSQL_execstate::rettype, PLpgSQL_execstate::retval, SPI_datumTransfer(), SPI_palloc(), SPI_returntuple(), TupleDescData::tdtypeid, TupleDescData::tdtypmod, type_is_rowtype(), and VARATT_IS_EXTERNAL_EXPANDED.

Referenced by plpgsql_exec_function().

776 {
777  HeapTuple rettup;
778  TupleDesc retdesc;
779  TupleConversionMap *tupmap;
780 
781  /* We assume exec_stmt_return verified that result is composite */
782  Assert(type_is_rowtype(estate->rettype));
783 
784  /* We can special-case expanded records for speed */
786  {
788 
789  Assert(erh->er_magic == ER_MAGIC);
790 
791  /* Extract record's TupleDesc */
792  retdesc = expanded_record_get_tupdesc(erh);
793 
794  /* check rowtype compatibility */
795  tupmap = convert_tuples_by_position(retdesc,
796  tupdesc,
797  gettext_noop("returned record type does not match expected record type"));
798 
799  /* it might need conversion */
800  if (tupmap)
801  {
802  rettup = expanded_record_get_tuple(erh);
803  Assert(rettup);
804  rettup = execute_attr_map_tuple(rettup, tupmap);
805 
806  /*
807  * Copy tuple to upper executor memory, as a tuple Datum. Make
808  * sure it is labeled with the caller-supplied tuple type.
809  */
810  estate->retval = PointerGetDatum(SPI_returntuple(rettup, tupdesc));
811  /* no need to free map, we're about to return anyway */
812  }
813  else if (!(tupdesc->tdtypeid == erh->er_decltypeid ||
814  (tupdesc->tdtypeid == RECORDOID &&
815  !ExpandedRecordIsDomain(erh))))
816  {
817  /*
818  * The expanded record has the right physical tupdesc, but the
819  * wrong type ID. (Typically, the expanded record is RECORDOID
820  * but the function is declared to return a named composite type.
821  * As in exec_move_row_from_datum, we don't allow returning a
822  * composite-domain record from a function declared to return
823  * RECORD.) So we must flatten the record to a tuple datum and
824  * overwrite its type fields with the right thing. spi.c doesn't
825  * provide any easy way to deal with this case, so we end up
826  * duplicating the guts of datumCopy() :-(
827  */
828  Size resultsize;
829  HeapTupleHeader tuphdr;
830 
831  resultsize = EOH_get_flat_size(&erh->hdr);
832  tuphdr = (HeapTupleHeader) SPI_palloc(resultsize);
833  EOH_flatten_into(&erh->hdr, (void *) tuphdr, resultsize);
834  HeapTupleHeaderSetTypeId(tuphdr, tupdesc->tdtypeid);
835  HeapTupleHeaderSetTypMod(tuphdr, tupdesc->tdtypmod);
836  estate->retval = PointerGetDatum(tuphdr);
837  }
838  else
839  {
840  /*
841  * We need only copy result into upper executor memory context.
842  * However, if we have a R/W expanded datum, we can just transfer
843  * its ownership out to the upper executor context.
844  */
845  estate->retval = SPI_datumTransfer(estate->retval,
846  false,
847  -1);
848  }
849  }
850  else
851  {
852  /* Convert composite datum to a HeapTuple and TupleDesc */
853  HeapTupleData tmptup;
854 
855  retdesc = deconstruct_composite_datum(estate->retval, &tmptup);
856  rettup = &tmptup;
857 
858  /* check rowtype compatibility */
859  tupmap = convert_tuples_by_position(retdesc,
860  tupdesc,
861  gettext_noop("returned record type does not match expected record type"));
862 
863  /* it might need conversion */
864  if (tupmap)
865  rettup = execute_attr_map_tuple(rettup, tupmap);
866 
867  /*
868  * Copy tuple to upper executor memory, as a tuple Datum. Make sure
869  * it is labeled with the caller-supplied tuple type.
870  */
871  estate->retval = PointerGetDatum(SPI_returntuple(rettup, tupdesc));
872 
873  /* no need to free map, we're about to return anyway */
874 
875  ReleaseTupleDesc(retdesc);
876  }
877 }
HeapTuple expanded_record_get_tuple(ExpandedRecordHeader *erh)
#define HeapTupleHeaderSetTypeId(tup, typeid)
Definition: htup_details.h:463
HeapTupleHeader SPI_returntuple(HeapTuple tuple, TupleDesc tupdesc)
Definition: spi.c:850
#define VARATT_IS_EXTERNAL_EXPANDED(PTR)
Definition: postgres.h:322
TupleConversionMap * convert_tuples_by_position(TupleDesc indesc, TupleDesc outdesc, const char *msg)
Definition: tupconvert.c:65
#define PointerGetDatum(X)
Definition: postgres.h:556
HeapTupleHeaderData * HeapTupleHeader
Definition: htup.h:23
#define gettext_noop(x)
Definition: c.h:1117
static TupleDesc deconstruct_composite_datum(Datum value, HeapTupleData *tmptup)
Definition: pl_exec.c:7345
ExpandedObjectHeader hdr
Datum SPI_datumTransfer(Datum value, bool typByVal, int typLen)
Definition: spi.c:1137
int32 tdtypmod
Definition: tupdesc.h:83
Size EOH_get_flat_size(ExpandedObjectHeader *eohptr)
Definition: expandeddatum.c:75
bool type_is_rowtype(Oid typid)
Definition: lsyscache.c:2433
HeapTuple execute_attr_map_tuple(HeapTuple tuple, TupleConversionMap *map)
Definition: tupconvert.c:390
static TupleDesc expanded_record_get_tupdesc(ExpandedRecordHeader *erh)
void * SPI_palloc(Size size)
Definition: spi.c:1114
ExpandedObjectHeader * DatumGetEOHP(Datum d)
Definition: expandeddatum.c:29
#define ER_MAGIC
#define HeapTupleHeaderSetTypMod(tup, typmod)
Definition: htup_details.h:473
void EOH_flatten_into(ExpandedObjectHeader *eohptr, void *result, Size allocated_size)
Definition: expandeddatum.c:81
#define Assert(condition)
Definition: c.h:732
size_t Size
Definition: c.h:466
#define DatumGetPointer(X)
Definition: postgres.h:549
Oid tdtypeid
Definition: tupdesc.h:82
#define ReleaseTupleDesc(tupdesc)
Definition: tupdesc.h:122
#define ExpandedRecordIsDomain(erh)

◆ compatible_tupdescs()

static bool compatible_tupdescs ( TupleDesc  src_tupdesc,
TupleDesc  dst_tupdesc 
)
static

Definition at line 7246 of file pl_exec.c.

References i, TupleDescData::natts, and TupleDescAttr.

Referenced by exec_for_query(), and exec_move_row().

7247 {
7248  int i;
7249 
7250  /* Possibly we could allow src_tupdesc to have extra columns? */
7251  if (dst_tupdesc->natts != src_tupdesc->natts)
7252  return false;
7253 
7254  for (i = 0; i < dst_tupdesc->natts; i++)
7255  {
7256  Form_pg_attribute dattr = TupleDescAttr(dst_tupdesc, i);
7257  Form_pg_attribute sattr = TupleDescAttr(src_tupdesc, i);
7258 
7259  if (dattr->attisdropped != sattr->attisdropped)
7260  return false;
7261  if (!dattr->attisdropped)
7262  {
7263  /* Normal columns must match by type and typmod */
7264  if (dattr->atttypid != sattr->atttypid ||
7265  (dattr->atttypmod >= 0 &&
7266  dattr->atttypmod != sattr->atttypmod))
7267  return false;
7268  }
7269  else
7270  {
7271  /* Dropped columns are OK as long as length/alignment match */
7272  if (dattr->attlen != sattr->attlen ||
7273  dattr->attalign != sattr->attalign)
7274  return false;
7275  }
7276  }
7277  return true;
7278 }
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:200
int i

◆ contains_target_param()

static bool contains_target_param ( Node node,
int *  target_dno 
)
static

Definition at line 8148 of file pl_exec.c.

References expression_tree_walker(), IsA, PARAM_EXTERN, Param::paramid, and Param::paramkind.

Referenced by exec_check_rw_parameter().

8149 {
8150  if (node == NULL)
8151  return false;
8152  if (IsA(node, Param))
8153  {
8154  Param *param = (Param *) node;
8155 
8156  if (param->paramkind == PARAM_EXTERN &&
8157  param->paramid == *target_dno + 1)
8158  return true;
8159  return false;
8160  }
8162  (void *) target_dno);
8163 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:575
ParamKind paramkind
Definition: primnodes.h:248
static bool contains_target_param(Node *node, int *target_dno)
Definition: pl_exec.c:8148
int paramid
Definition: primnodes.h:249
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1840

◆ convert_value_to_string()

static char * convert_value_to_string ( PLpgSQL_execstate estate,
Datum  value,
Oid  valtype 
)
static

Definition at line 7644 of file pl_exec.c.

References get_eval_mcontext, getTypeOutputInfo(), MemoryContextSwitchTo(), and OidOutputFunctionCall().

Referenced by exec_dynquery_with_params(), exec_stmt_assert(), exec_stmt_dynexecute(), exec_stmt_raise(), format_expr_params(), and format_preparedparamsdata().

7645 {
7646  char *result;
7647  MemoryContext oldcontext;
7648  Oid typoutput;
7649  bool typIsVarlena;
7650 
7651  oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
7652  getTypeOutputInfo(valtype, &typoutput, &typIsVarlena);
7653  result = OidOutputFunctionCall(typoutput, value);
7654  MemoryContextSwitchTo(oldcontext);
7655 
7656  return result;
7657 }
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:2674
static struct @144 value
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
unsigned int Oid
Definition: postgres_ext.h:31
#define get_eval_mcontext(estate)
Definition: pl_exec.c:121
char * OidOutputFunctionCall(Oid functionId, Datum val)
Definition: fmgr.c:1655

◆ copy_plpgsql_datums()

static void copy_plpgsql_datums ( PLpgSQL_execstate estate,
PLpgSQL_function func 
)
static

Definition at line 1260 of file pl_exec.c.

References Assert, PLpgSQL_function::copiable_size, PLpgSQL_function::datums, PLpgSQL_execstate::datums, PLpgSQL_datum::dtype, elog, ERROR, i, MAXALIGN, PLpgSQL_execstate::ndatums, palloc(), PLPGSQL_DTYPE_ARRAYELEM, PLPGSQL_DTYPE_PROMISE, PLPGSQL_DTYPE_REC, PLPGSQL_DTYPE_RECFIELD, PLPGSQL_DTYPE_ROW, and PLPGSQL_DTYPE_VAR.

Referenced by plpgsql_exec_event_trigger(), plpgsql_exec_function(), and plpgsql_exec_trigger().

1262 {
1263  int ndatums = estate->ndatums;
1264  PLpgSQL_datum **indatums;
1265  PLpgSQL_datum **outdatums;
1266  char *workspace;
1267  char *ws_next;
1268  int i;
1269 
1270  /* Allocate local datum-pointer array */
1271  estate->datums = (PLpgSQL_datum **)
1272  palloc(sizeof(PLpgSQL_datum *) * ndatums);
1273 
1274  /*
1275  * To reduce palloc overhead, we make a single palloc request for all the
1276  * space needed for locally-instantiated datums.
1277  */
1278  workspace = palloc(func->copiable_size);
1279  ws_next = workspace;
1280 
1281  /* Fill datum-pointer array, copying datums into workspace as needed */
1282  indatums = func->datums;
1283  outdatums = estate->datums;
1284  for (i = 0; i < ndatums; i++)
1285  {
1286  PLpgSQL_datum *indatum = indatums[i];
1287  PLpgSQL_datum *outdatum;
1288 
1289  /* This must agree with plpgsql_finish_datums on what is copiable */
1290  switch (indatum->dtype)
1291  {
1292  case PLPGSQL_DTYPE_VAR:
1293  case PLPGSQL_DTYPE_PROMISE:
1294  outdatum = (PLpgSQL_datum *) ws_next;
1295  memcpy(outdatum, indatum, sizeof(PLpgSQL_var));
1296  ws_next += MAXALIGN(sizeof(PLpgSQL_var));
1297  break;
1298 
1299  case PLPGSQL_DTYPE_REC:
1300  outdatum = (PLpgSQL_datum *) ws_next;
1301  memcpy(outdatum, indatum, sizeof(PLpgSQL_rec));
1302  ws_next += MAXALIGN(sizeof(PLpgSQL_rec));
1303  break;
1304 
1305  case PLPGSQL_DTYPE_ROW:
1308 
1309  /*
1310  * These datum records are read-only at runtime, so no need to
1311  * copy them (well, RECFIELD and ARRAYELEM contain cached
1312  * data, but we'd just as soon centralize the caching anyway).
1313  */
1314  outdatum = indatum;
1315  break;
1316 
1317  default:
1318  elog(ERROR, "unrecognized dtype: %d", indatum->dtype);
1319  outdatum = NULL; /* keep compiler quiet */
1320  break;
1321  }
1322 
1323  outdatums[i] = outdatum;
1324  }
1325 
1326  Assert(ws_next == workspace + func->copiable_size);
1327 }
PLpgSQL_datum ** datums
Definition: plpgsql.h:1020
PLpgSQL_datum_type dtype
Definition: plpgsql.h:257
PLpgSQL_datum ** datums
Definition: plpgsql.h:1071
#define ERROR
Definition: elog.h:43
#define Assert(condition)
Definition: c.h:732
#define MAXALIGN(LEN)
Definition: c.h:685
void * palloc(Size size)
Definition: mcxt.c:924
#define elog(elevel,...)
Definition: elog.h:226
int i
Size copiable_size
Definition: plpgsql.h:1021

◆ deconstruct_composite_datum()

static TupleDesc deconstruct_composite_datum ( Datum  value,
HeapTupleData tmptup 
)
static

Definition at line 7345 of file pl_exec.c.

References DatumGetHeapTupleHeader, HeapTupleHeaderGetDatumLength, HeapTupleHeaderGetTypeId, HeapTupleHeaderGetTypMod, InvalidOid, ItemPointerSetInvalid, lookup_rowtype_tupdesc(), HeapTupleData::t_data, HeapTupleData::t_len, HeapTupleData::t_self, and HeapTupleData::t_tableOid.

Referenced by coerce_function_result_tuple(), exec_stmt_return_next(), and plpgsql_exec_trigger().

7346 {
7347  HeapTupleHeader td;
7348  Oid tupType;
7349  int32 tupTypmod;
7350 
7351  /* Get tuple body (note this could involve detoasting) */
7353 
7354  /* Build a temporary HeapTuple control structure */
7355  tmptup->t_len = HeapTupleHeaderGetDatumLength(td);
7356  ItemPointerSetInvalid(&(tmptup->t_self));
7357  tmptup->t_tableOid = InvalidOid;
7358  tmptup->t_data = td;
7359 
7360  /* Extract rowtype info and find a tupdesc */
7361  tupType = HeapTupleHeaderGetTypeId(td);
7362  tupTypmod = HeapTupleHeaderGetTypMod(td);
7363  return lookup_rowtype_tupdesc(tupType, tupTypmod);
7364 }
TupleDesc lookup_rowtype_tupdesc(Oid type_id, int32 typmod)
Definition: typcache.c:1652
static struct @144 value
unsigned int Oid
Definition: postgres_ext.h:31
#define DatumGetHeapTupleHeader(X)
Definition: fmgr.h:289
signed int int32
Definition: c.h:346
HeapTupleHeader t_data
Definition: htup.h:68
#define HeapTupleHeaderGetTypMod(tup)
Definition: htup_details.h:468
ItemPointerData t_self
Definition: htup.h:65
uint32 t_len
Definition: htup.h:64
Oid t_tableOid
Definition: htup.h:66
#define HeapTupleHeaderGetTypeId(tup)
Definition: htup_details.h:458
#define InvalidOid
Definition: postgres_ext.h:36
#define ItemPointerSetInvalid(pointer)
Definition: itemptr.h:172
#define HeapTupleHeaderGetDatumLength(tup)
Definition: htup_details.h:452

◆ exception_matches_conditions()

static bool exception_matches_conditions ( ErrorData edata,
PLpgSQL_condition cond 
)
static

Definition at line 1546 of file pl_exec.c.

References ERRCODE_IS_CATEGORY, ERRCODE_TO_CATEGORY, PLpgSQL_condition::next, ErrorData::sqlerrcode, and PLpgSQL_condition::sqlerrstate.

Referenced by exec_stmt_block().

1547 {
1548  for (; cond != NULL; cond = cond->next)
1549  {
1550  int sqlerrstate = cond->sqlerrstate;
1551 
1552  /*
1553  * OTHERS matches everything *except* query-canceled and
1554  * assert-failure. If you're foolish enough, you can match those
1555  * explicitly.
1556  */
1557  if (sqlerrstate == 0)
1558  {
1559  if (edata->sqlerrcode != ERRCODE_QUERY_CANCELED &&
1560  edata->sqlerrcode != ERRCODE_ASSERT_FAILURE)
1561  return true;
1562  }
1563  /* Exact match? */
1564  else if (edata->sqlerrcode == sqlerrstate)
1565  return true;
1566  /* Category match? */
1567  else if (ERRCODE_IS_CATEGORY(sqlerrstate) &&
1568  ERRCODE_TO_CATEGORY(edata->sqlerrcode) == sqlerrstate)
1569  return true;
1570  }
1571  return false;
1572 }
#define ERRCODE_IS_CATEGORY(ec)
Definition: elog.h:68
int sqlerrcode
Definition: elog.h:359
struct PLpgSQL_condition * next
Definition: plpgsql.h:477
#define ERRCODE_TO_CATEGORY(ec)
Definition: elog.h:67

◆ exec_assign_c_string()

static void exec_assign_c_string ( PLpgSQL_execstate estate,
PLpgSQL_datum target,
const char *  str 
)
static

Definition at line 4929 of file pl_exec.c.

References cstring_to_text(), exec_assign_value(), get_eval_mcontext, MemoryContextSwitchTo(), PointerGetDatum, and value.

Referenced by exec_stmt_getdiag().

4931 {
4932  text *value;
4933  MemoryContext oldcontext;
4934 
4935  /* Use eval_mcontext for short-lived text value */
4936  oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
4937  if (str != NULL)
4938  value = cstring_to_text(str);
4939  else
4940  value = cstring_to_text("");
4941  MemoryContextSwitchTo(oldcontext);
4942 
4943  exec_assign_value(estate, target, PointerGetDatum(value), false,
4944  TEXTOID, -1);
4945 }
#define PointerGetDatum(X)
Definition: postgres.h:556
static struct @144 value
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define get_eval_mcontext(estate)
Definition: pl_exec.c:121
text * cstring_to_text(const char *s)
Definition: varlena.c:171
Definition: c.h:549
static void exec_assign_value(PLpgSQL_execstate *estate, PLpgSQL_datum *target, Datum value, bool isNull, Oid valtype, int32 valtypmod)
Definition: pl_exec.c:4957

◆ exec_assign_expr()

static void exec_assign_expr ( PLpgSQL_execstate estate,
PLpgSQL_datum target,
PLpgSQL_expr expr 
)
static

Definition at line 4892 of file pl_exec.c.

References PLpgSQL_datum::dno, PLpgSQL_datum::dtype, exec_assign_value(), exec_check_rw_parameter(), exec_eval_cleanup(), exec_eval_expr(), exec_prepare_plan(), PLpgSQL_expr::plan, PLPGSQL_DTYPE_VAR, and value.

Referenced by exec_stmt_assign(), exec_stmt_block(), and plpgsql_estate_setup().

4894 {
4895  Datum value;
4896  bool isnull;
4897  Oid valtype;
4898  int32 valtypmod;
4899 
4900  /*
4901  * If first time through, create a plan for this expression, and then see
4902  * if we can pass the target variable as a read-write parameter to the
4903  * expression. (This is a bit messy, but it seems cleaner than modifying
4904  * the API of exec_eval_expr for the purpose.)
4905  */
4906  if (expr->plan == NULL)
4907  {
4908  exec_prepare_plan(estate, expr, 0, true);
4909  if (target->dtype == PLPGSQL_DTYPE_VAR)
4910  exec_check_rw_parameter(expr, target->dno);
4911  }
4912 
4913  value = exec_eval_expr(estate, expr, &isnull, &valtype, &valtypmod);
4914  exec_assign_value(estate, target, value, isnull, valtype, valtypmod);
4915  exec_eval_cleanup(estate);
4916 }
static void exec_prepare_plan(PLpgSQL_execstate *estate, PLpgSQL_expr *expr, int cursorOptions, bool keepplan)
Definition: pl_exec.c:4041
static void exec_check_rw_parameter(PLpgSQL_expr *expr, int target_dno)
Definition: pl_exec.c:8071
static struct @144 value
static void exec_eval_cleanup(PLpgSQL_execstate *estate)
Definition: pl_exec.c:4020
unsigned int Oid
Definition: postgres_ext.h:31
PLpgSQL_datum_type dtype
Definition: plpgsql.h:257
SPIPlanPtr plan
Definition: plpgsql.h:222
signed int int32
Definition: c.h:346
static Datum exec_eval_expr(PLpgSQL_execstate *estate, PLpgSQL_expr *expr, bool *isNull, Oid *rettype, int32 *rettypmod)
Definition: pl_exec.c:5753
uintptr_t Datum
Definition: postgres.h:367
static void exec_assign_value(PLpgSQL_execstate *estate, PLpgSQL_datum *target, Datum value, bool isNull, Oid valtype, int32 valtypmod)
Definition: pl_exec.c:4957

◆ exec_assign_value()

static void exec_assign_value ( PLpgSQL_execstate estate,
PLpgSQL_datum target,
Datum  value,
bool  isNull,
Oid  valtype,
int32  valtypmod 
)
static

Definition at line 4957 of file pl_exec.c.

References array_set_element(), PLpgSQL_arrayelem::arrayparentno, PLpgSQL_arrayelem::arraytyplen, PLpgSQL_arrayelem::arraytypmod, PLpgSQL_arrayelem::arraytypoid, Assert, assign_simple_var(), PLpgSQL_execstate::atomic, PLpgSQL_type::atttypmod, construct_empty_array(), PLpgSQL_var::datatype, PLpgSQL_execstate::datum_context, DatumGetPointer, PLpgSQL_execstate::datums, datumTransfer(), PLpgSQL_datum::dtype, PLpgSQL_arrayelem::elemtypalign, PLpgSQL_arrayelem::elemtypbyval, PLpgSQL_arrayelem::elemtyplen, PLpgSQL_arrayelem::elemtypoid, elog, ExpandedRecordHeader::er_tupdesc_id, ereport, PLpgSQL_rec::erh, errcode(), errmsg(), ERROR, PLpgSQL_execstate::eval_tuptable, exec_cast_value(), exec_eval_datum(), exec_eval_integer(), exec_move_row(), exec_move_row_from_datum(), expand_array(), expanded_record_lookup_field(), expanded_record_set_field, PLpgSQL_recfield::fieldname, PLpgSQL_recfield::finfo, ExpandedRecordFieldInfo::fnumber, ExpandedRecordFieldInfo::ftypeid, ExpandedRecordFieldInfo::ftypmod, get_element_type(), get_eval_mcontext, get_typlen(), get_typlenbyvalalign(), getBaseTypeAndTypmod(), i, instantiate_empty_record_variable(), PLpgSQL_var::isnull, MAXDIM, MemoryContextSwitchTo(), PLpgSQL_var::notnull, PLpgSQL_rec::notnull, OidIsValid, PLpgSQL_arrayelem::parenttypmod, PLpgSQL_arrayelem::parenttypoid, PLPGSQL_DTYPE_ARRAYELEM, PLPGSQL_DTYPE_PROMISE, PLPGSQL_DTYPE_REC, PLPGSQL_DTYPE_RECFIELD, PLPGSQL_DTYPE_ROW, PLPGSQL_DTYPE_VAR, PLPGSQL_PROMISE_NONE, PointerGetDatum, PLpgSQL_var::promise, PLpgSQL_recfield::recparentno, PLpgSQL_recfield::rectupledescid, PLpgSQL_var::refname, PLpgSQL_rec::refname, SPI_freetuptable(), PLpgSQL_arrayelem::subscript, PLpgSQL_type::typbyval, type_is_rowtype(), PLpgSQL_type::typisarray, PLpgSQL_type::typlen, PLpgSQL_type::typoid, unlikely, PLpgSQL_var::value, and VARATT_IS_EXTERNAL_EXPANDED_RW.

Referenced by exec_assign_c_string(), exec_assign_expr(), exec_move_row_from_fields(), exec_stmt_block(), exec_stmt_case(), exec_stmt_foreach_a(), and exec_stmt_getdiag().

4961 {
4962  switch (target->dtype)
4963  {
4964  case PLPGSQL_DTYPE_VAR:
4965  case PLPGSQL_DTYPE_PROMISE:
4966  {
4967  /*
4968  * Target is a variable
4969  */
4970  PLpgSQL_var *var = (PLpgSQL_var *) target;
4971  Datum newvalue;
4972 
4973  newvalue = exec_cast_value(estate,
4974  value,
4975  &isNull,
4976  valtype,
4977  valtypmod,
4978  var->datatype->typoid,
4979  var->datatype->atttypmod);
4980 
4981  if (isNull && var->notnull)
4982  ereport(ERROR,
4983  (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
4984  errmsg("null value cannot be assigned to variable \"%s\" declared NOT NULL",
4985  var->refname)));
4986 
4987  /*
4988  * If type is by-reference, copy the new value (which is
4989  * probably in the eval_mcontext) into the procedure's main
4990  * memory context. But if it's a read/write reference to an
4991  * expanded object, no physical copy needs to happen; at most
4992  * we need to reparent the object's memory context.
4993  *
4994  * If it's an array, we force the value to be stored in R/W
4995  * expanded form. This wins if the function later does, say,
4996  * a lot of array subscripting operations on the variable, and
4997  * otherwise might lose. We might need to use a different
4998  * heuristic, but it's too soon to tell. Also, are there
4999  * cases where it'd be useful to force non-array values into
5000  * expanded form?
5001  */
5002  if (!var->datatype->typbyval && !isNull)
5003  {
5004  if (var->datatype->typisarray &&
5006  {
5007  /* array and not already R/W, so apply expand_array */
5008  newvalue = expand_array(newvalue,
5009  estate->datum_context,
5010  NULL);
5011  }
5012  else
5013  {
5014  /* else transfer value if R/W, else just datumCopy */
5015  newvalue = datumTransfer(newvalue,
5016  false,
5017  var->datatype->typlen);
5018  }
5019  }
5020 
5021  /*
5022  * Now free the old value, if any, and assign the new one. But
5023  * skip the assignment if old and new values are the same.
5024  * Note that for expanded objects, this test is necessary and
5025  * cannot reliably be made any earlier; we have to be looking
5026  * at the object's standard R/W pointer to be sure pointer
5027  * equality is meaningful.
5028  *
5029  * Also, if it's a promise variable, we should disarm the
5030  * promise in any case --- otherwise, assigning null to an
5031  * armed promise variable would fail to disarm the promise.
5032  */
5033  if (var->value != newvalue || var->isnull || isNull)
5034  assign_simple_var(estate, var, newvalue, isNull,
5035  (!var->datatype->typbyval && !isNull));
5036  else
5038  break;
5039  }
5040 
5041  case PLPGSQL_DTYPE_ROW:
5042  {
5043  /*
5044  * Target is a row variable
5045  */
5046  PLpgSQL_row *row = (PLpgSQL_row *) target;
5047 
5048  if (isNull)
5049  {
5050  /* If source is null, just assign nulls to the row */
5051  exec_move_row(estate, (PLpgSQL_variable *) row,
5052  NULL, NULL);
5053  }
5054  else
5055  {
5056  /* Source must be of RECORD or composite type */
5057  if (!type_is_rowtype(valtype))
5058  ereport(ERROR,
5059  (errcode(ERRCODE_DATATYPE_MISMATCH),
5060  errmsg("cannot assign non-composite value to a row variable")));
5062  value);
5063  }
5064  break;
5065  }
5066 
5067  case PLPGSQL_DTYPE_REC:
5068  {
5069  /*
5070  * Target is a record variable
5071  */
5072  PLpgSQL_rec *rec = (PLpgSQL_rec *) target;
5073 
5074  if (isNull)
5075  {
5076  if (rec->notnull)
5077  ereport(ERROR,
5078  (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
5079  errmsg("null value cannot be assigned to variable \"%s\" declared NOT NULL",
5080  rec->refname)));
5081 
5082  /* Set variable to a simple NULL */
5083  exec_move_row(estate, (PLpgSQL_variable *) rec,
5084  NULL, NULL);
5085  }
5086  else
5087  {
5088  /* Source must be of RECORD or composite type */
5089  if (!type_is_rowtype(valtype))
5090  ereport(ERROR,
5091  (errcode(ERRCODE_DATATYPE_MISMATCH),
5092  errmsg("cannot assign non-composite value to a record variable")));
5094  value);
5095  }
5096  break;
5097  }
5098 
5100  {
5101  /*
5102  * Target is a field of a record
5103  */
5104  PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) target;
5105  PLpgSQL_rec *rec;
5106  ExpandedRecordHeader *erh;
5107 
5108  rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
5109  erh = rec->erh;
5110 
5111  /*
5112  * If record variable is NULL, instantiate it if it has a
5113  * named composite type, else complain. (This won't change
5114  * the logical state of the record, but if we successfully
5115  * assign below, the unassigned fields will all become NULLs.)
5116  */
5117  if (erh == NULL)
5118  {
5119  instantiate_empty_record_variable(estate, rec);
5120  erh = rec->erh;
5121  }
5122 
5123  /*
5124  * Look up the field's properties if we have not already, or
5125  * if the tuple descriptor ID changed since last time.
5126  */
5127  if (unlikely(recfield->rectupledescid != erh->er_tupdesc_id))
5128  {
5130  recfield->fieldname,
5131  &recfield->finfo))
5132  ereport(ERROR,
5133  (errcode(ERRCODE_UNDEFINED_COLUMN),
5134  errmsg("record \"%s\" has no field \"%s\"",
5135  rec->refname, recfield->fieldname)));
5136  recfield->rectupledescid = erh->er_tupdesc_id;
5137  }
5138 
5139  /* We don't support assignments to system columns. */
5140  if (recfield->finfo.fnumber <= 0)
5141  ereport(ERROR,
5142  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5143  errmsg("cannot assign to system column \"%s\"",
5144  recfield->fieldname)));
5145 
5146  /* Cast the new value to the right type, if needed. */
5147  value = exec_cast_value(estate,
5148  value,
5149  &isNull,
5150  valtype,
5151  valtypmod,
5152  recfield->finfo.ftypeid,
5153  recfield->finfo.ftypmod);
5154 
5155  /* And assign it. */
5156  expanded_record_set_field(erh, recfield->finfo.fnumber,
5157  value, isNull, !estate->atomic);
5158  break;
5159  }
5160 
5162  {
5163  /*
5164  * Target is an element of an array
5165  */
5166  PLpgSQL_arrayelem *arrayelem;
5167  int nsubscripts;
5168  int i;
5169  PLpgSQL_expr *subscripts[MAXDIM];
5170  int subscriptvals[MAXDIM];
5171  Datum oldarraydatum,
5172  newarraydatum,
5173  coerced_value;
5174  bool oldarrayisnull;
5175  Oid parenttypoid;
5176  int32 parenttypmod;
5177  SPITupleTable *save_eval_tuptable;
5178  MemoryContext oldcontext;
5179 
5180  /*
5181  * We need to do subscript evaluation, which might require
5182  * evaluating general expressions; and the caller might have
5183  * done that too in order to prepare the input Datum. We have
5184  * to save and restore the caller's SPI_execute result, if
5185  * any.
5186  */
5187  save_eval_tuptable = estate->eval_tuptable;
5188  estate->eval_tuptable = NULL;
5189 
5190  /*
5191  * To handle constructs like x[1][2] := something, we have to
5192  * be prepared to deal with a chain of arrayelem datums. Chase
5193  * back to find the base array datum, and save the subscript
5194  * expressions as we go. (We are scanning right to left here,
5195  * but want to evaluate the subscripts left-to-right to
5196  * minimize surprises.) Note that arrayelem is left pointing
5197  * to the leftmost arrayelem datum, where we will cache the
5198  * array element type data.
5199  */
5200  nsubscripts = 0;
5201  do
5202  {
5203  arrayelem = (PLpgSQL_arrayelem *) target;
5204  if (nsubscripts >= MAXDIM)
5205  ereport(ERROR,
5206  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5207  errmsg("number of array dimensions (%d) exceeds the maximum allowed (%d)",
5208  nsubscripts + 1, MAXDIM)));
5209  subscripts[nsubscripts++] = arrayelem->subscript;
5210  target = estate->datums[arrayelem->arrayparentno];
5211  } while (target->dtype == PLPGSQL_DTYPE_ARRAYELEM);
5212 
5213  /* Fetch current value of array datum */
5214  exec_eval_datum(estate, target,
5215  &parenttypoid, &parenttypmod,
5216  &oldarraydatum, &oldarrayisnull);
5217 
5218  /* Update cached type data if necessary */
5219  if (arrayelem->parenttypoid != parenttypoid ||
5220  arrayelem->parenttypmod != parenttypmod)
5221  {
5222  Oid arraytypoid;
5223  int32 arraytypmod = parenttypmod;
5224  int16 arraytyplen;
5225  Oid elemtypoid;
5226  int16 elemtyplen;
5227  bool elemtypbyval;
5228  char elemtypalign;
5229 
5230  /* If target is domain over array, reduce to base type */
5231  arraytypoid = getBaseTypeAndTypmod(parenttypoid,
5232  &arraytypmod);
5233 
5234  /* ... and identify the element type */
5235  elemtypoid = get_element_type(arraytypoid);
5236  if (!OidIsValid(elemtypoid))
5237  ereport(ERROR,
5238  (errcode(ERRCODE_DATATYPE_MISMATCH),
5239  errmsg("subscripted object is not an array")));
5240 
5241  /* Collect needed data about the types */
5242  arraytyplen = get_typlen(arraytypoid);
5243 
5244  get_typlenbyvalalign(elemtypoid,
5245  &elemtyplen,
5246  &elemtypbyval,
5247  &elemtypalign);
5248 
5249  /* Now safe to update the cached data */
5250  arrayelem->parenttypoid = parenttypoid;
5251  arrayelem->parenttypmod = parenttypmod;
5252  arrayelem->arraytypoid = arraytypoid;
5253  arrayelem->arraytypmod = arraytypmod;
5254  arrayelem->arraytyplen = arraytyplen;
5255  arrayelem->elemtypoid = elemtypoid;
5256  arrayelem->elemtyplen = elemtyplen;
5257  arrayelem->elemtypbyval = elemtypbyval;
5258  arrayelem->elemtypalign = elemtypalign;
5259  }
5260 
5261  /*
5262  * Evaluate the subscripts, switch into left-to-right order.
5263  * Like the expression built by ExecInitSubscriptingRef(),
5264  * complain if any subscript is null.
5265  */
5266  for (i = 0; i < nsubscripts; i++)
5267  {
5268  bool subisnull;
5269 
5270  subscriptvals[i] =
5271  exec_eval_integer(estate,
5272  subscripts[nsubscripts - 1 - i],
5273  &subisnull);
5274  if (subisnull)
5275  ereport(ERROR,
5276  (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
5277  errmsg("array subscript in assignment must not be null")));
5278 
5279  /*
5280  * Clean up in case the subscript expression wasn't
5281  * simple. We can't do exec_eval_cleanup, but we can do
5282  * this much (which is safe because the integer subscript
5283  * value is surely pass-by-value), and we must do it in
5284  * case the next subscript expression isn't simple either.
5285  */
5286  if (estate->eval_tuptable != NULL)
5288  estate->eval_tuptable = NULL;
5289  }
5290 
5291  /* Now we can restore caller's SPI_execute result if any. */
5292  Assert(estate->eval_tuptable == NULL);
5293  estate->eval_tuptable = save_eval_tuptable;
5294 
5295  /* Coerce source value to match array element type. */
5296  coerced_value = exec_cast_value(estate,
5297  value,
5298  &isNull,
5299  valtype,
5300  valtypmod,
5301  arrayelem->elemtypoid,
5302  arrayelem->arraytypmod);
5303 
5304  /*
5305  * If the original array is null, cons up an empty array so
5306  * that the assignment can proceed; we'll end with a
5307  * one-element array containing just the assigned-to
5308  * subscript. This only works for varlena arrays, though; for
5309  * fixed-length array types we skip the assignment. We can't
5310  * support assignment of a null entry into a fixed-length
5311  * array, either, so that's a no-op too. This is all ugly but
5312  * corresponds to the current behavior of execExpr*.c.
5313  */
5314  if (arrayelem->arraytyplen > 0 && /* fixed-length array? */
5315  (oldarrayisnull || isNull))
5316  return;
5317 
5318  /* empty array, if any, and newarraydatum are short-lived */
5319  oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
5320 
5321  if (oldarrayisnull)
5322  oldarraydatum = PointerGetDatum(construct_empty_array(arrayelem->elemtypoid));
5323 
5324  /*
5325  * Build the modified array value.
5326  */
5327  newarraydatum = array_set_element(oldarraydatum,
5328  nsubscripts,
5329  subscriptvals,
5330  coerced_value,
5331  isNull,
5332  arrayelem->arraytyplen,
5333  arrayelem->elemtyplen,
5334  arrayelem->elemtypbyval,
5335  arrayelem->elemtypalign);
5336 
5337  MemoryContextSwitchTo(oldcontext);
5338 
5339  /*
5340  * Assign the new array to the base variable. It's never NULL
5341  * at this point. Note that if the target is a domain,
5342  * coercing the base array type back up to the domain will
5343  * happen within exec_assign_value.
5344  */
5345  exec_assign_value(estate, target,
5346  newarraydatum,
5347  false,
5348  arrayelem->arraytypoid,
5349  arrayelem->arraytypmod);
5350  break;
5351  }
5352 
5353  default:
5354  elog(ERROR, "unrecognized dtype: %d", target->dtype);
5355  }
5356 }
PLpgSQL_promise_type promise
Definition: plpgsql.h:322
signed short int16
Definition: c.h:345
int16 elemtyplen
Definition: plpgsql.h:433
#define expanded_record_set_field(erh, fnumber, newValue, isnull, expand_external)
Oid getBaseTypeAndTypmod(Oid typid, int32 *typmod)
Definition: lsyscache.c:2316
SPITupleTable * eval_tuptable
Definition: plpgsql.h:1095
char * refname
Definition: plpgsql.h:293
static void exec_eval_datum(PLpgSQL_execstate *estate, PLpgSQL_datum *datum, Oid *typeid, int32 *typetypmod, Datum *value, bool *isnull)
Definition: pl_exec.c:5376
bool expanded_record_lookup_field(ExpandedRecordHeader *erh, const char *fieldname, ExpandedRecordFieldInfo *finfo)
#define MAXDIM
Definition: c.h:529
Oid get_element_type(Oid typid)
Definition: lsyscache.c:2526
void get_typlenbyvalalign(Oid typid, int16 *typlen, bool *typbyval, char *typalign)
Definition: lsyscache.c:2049
#define PointerGetDatum(X)
Definition: postgres.h:556
PLpgSQL_type * datatype
Definition: plpgsql.h:300
static struct @144 value
Datum expand_array(Datum arraydatum, MemoryContext parentcontext, ArrayMetaState *metacache)
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
static void instantiate_empty_record_variable(PLpgSQL_execstate *estate, PLpgSQL_rec *rec)
Definition: pl_exec.c:7609
ExpandedRecordHeader * erh
Definition: plpgsql.h:394
int errcode(int sqlerrcode)
Definition: elog.c:570
static void assign_simple_var(PLpgSQL_execstate *estate, PLpgSQL_var *var, Datum newvalue, bool isnull, bool freeable)
Definition: pl_exec.c:8318
Datum array_set_element(Datum arraydatum, int nSubscripts, int *indx, Datum dataValue, bool isNull, int arraytyplen, int elmlen, bool elmbyval, char elmalign)
Definition: arrayfuncs.c:2199
ArrayType * construct_empty_array(Oid elmtype)
Definition: arrayfuncs.c:3410
unsigned int Oid
Definition: postgres_ext.h:31
static void exec_move_row_from_datum(PLpgSQL_execstate *estate, PLpgSQL_variable *target, Datum value)
Definition: pl_exec.c:7376
PLpgSQL_datum_type dtype
Definition: plpgsql.h:257
#define OidIsValid(objectId)
Definition: c.h:638
char * refname
Definition: plpgsql.h:373
signed int int32
Definition: c.h:346
PLpgSQL_datum ** datums
Definition: plpgsql.h:1071
int32 arraytypmod
Definition: plpgsql.h:430
bool notnull
Definition: plpgsql.h:296
static Datum exec_cast_value(PLpgSQL_execstate *estate, Datum value, bool *isnull, Oid valtype, int32 valtypmod, Oid reqtype, int32 reqtypmod)
Definition: pl_exec.c:7673
#define ERROR
Definition: elog.h:43
bool type_is_rowtype(Oid typid)
Definition: lsyscache.c:2433
#define ereport(elevel, rest)
Definition: elog.h:141
uint64 rectupledescid
Definition: plpgsql.h:409
bool typbyval
Definition: plpgsql.h:205
#define get_eval_mcontext(estate)
Definition: pl_exec.c:121
void SPI_freetuptable(SPITupleTable *tuptable)
Definition: spi.c:1162
bool typisarray
Definition: plpgsql.h:208
uintptr_t Datum
Definition: postgres.h:367
static int exec_eval_integer(PLpgSQL_execstate *estate, PLpgSQL_expr *expr, bool *isNull)
Definition: pl_exec.c:5707
ExpandedRecordFieldInfo finfo
Definition: plpgsql.h:410
int32 parenttypmod
Definition: plpgsql.h:428
Datum value
Definition: plpgsql.h:313
Datum datumTransfer(Datum value, bool typByVal, int typLen)
Definition: datum.c:192
#define Assert(condition)
Definition: c.h:732
int16 arraytyplen
Definition: plpgsql.h:431
#define DatumGetPointer(X)
Definition: postgres.h:549
MemoryContext datum_context
Definition: plpgsql.h:1073
int16 get_typlen(Oid typid)
Definition: lsyscache.c:1975
int errmsg(const char *fmt,...)
Definition: elog.c:784
int32 atttypmod
Definition: plpgsql.h:209
static void exec_move_row(PLpgSQL_execstate *estate, PLpgSQL_variable *target, HeapTuple tup, TupleDesc tupdesc)
Definition: pl_exec.c:6711
#define elog(elevel,...)
Definition: elog.h:226
int i
PLpgSQL_expr * subscript
Definition: plpgsql.h:423
#define VARATT_IS_EXTERNAL_EXPANDED_RW(PTR)
Definition: postgres.h:320
#define unlikely(x)
Definition: c.h:208
int16 typlen
Definition: plpgsql.h:204
bool notnull
Definition: plpgsql.h:376
char * fieldname
Definition: plpgsql.h:406
static void exec_assign_value(PLpgSQL_execstate *estate, PLpgSQL_datum *target, Datum value, bool isNull, Oid valtype, int32 valtypmod)
Definition: pl_exec.c:4957
bool isnull
Definition: plpgsql.h:314
Oid typoid
Definition: plpgsql.h:202

◆ exec_cast_value()

static Datum exec_cast_value ( PLpgSQL_execstate estate,
Datum  value,
bool isnull,
Oid  valtype,
int32  valtypmod,
Oid  reqtype,
int32  reqtypmod 
)
static

Definition at line 7673 of file pl_exec.c.

References ExprContext::caseValue_datum, ExprContext::caseValue_isNull, plpgsql_CastHashEntry::cast_exprstate, plpgsql_CastHashEntry::cast_in_use, PLpgSQL_execstate::eval_econtext, ExecEvalExpr(), get_cast_hashentry(), get_eval_mcontext, MemoryContextSwitchTo(), and value.

Referenced by exec_assign_value(), exec_eval_boolean(), exec_eval_integer(), exec_move_row_from_fields(), exec_stmt_fori(), exec_stmt_return_next(), and plpgsql_exec_function().

7677 {
7678  /*
7679  * If the type of the given value isn't what's requested, convert it.
7680  */
7681  if (valtype != reqtype ||
7682  (valtypmod != reqtypmod && reqtypmod != -1))
7683  {
7684  plpgsql_CastHashEntry *cast_entry;
7685 
7686  cast_entry = get_cast_hashentry(estate,
7687  valtype, valtypmod,
7688  reqtype, reqtypmod);
7689  if (cast_entry)
7690  {
7691  ExprContext *econtext = estate->eval_econtext;
7692  MemoryContext oldcontext;
7693 
7694  oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
7695 
7696  econtext->caseValue_datum = value;
7697  econtext->caseValue_isNull = *isnull;
7698 
7699  cast_entry->cast_in_use = true;
7700 
7701  value = ExecEvalExpr(cast_entry->cast_exprstate, econtext,
7702  isnull);
7703 
7704  cast_entry->cast_in_use = false;
7705 
7706  MemoryContextSwitchTo(oldcontext);
7707  }
7708  }
7709 
7710  return value;
7711 }
static struct @144 value
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
static plpgsql_CastHashEntry * get_cast_hashentry(PLpgSQL_execstate *estate, Oid srctype, int32 srctypmod, Oid dsttype, int32 dsttypmod)
Definition: pl_exec.c:7724
Datum caseValue_datum
Definition: execnodes.h:249
static Datum ExecEvalExpr(ExprState *state, ExprContext *econtext, bool *isNull)
Definition: executor.h:285
#define get_eval_mcontext(estate)
Definition: pl_exec.c:121
ExprContext * eval_econtext
Definition: plpgsql.h:1097
bool caseValue_isNull
Definition: execnodes.h:251
ExprState * cast_exprstate
Definition: pl_exec.c:157

◆ exec_check_rw_parameter()

static void exec_check_rw_parameter ( PLpgSQL_expr expr,
int  target_dno 
)
static

Definition at line 8071 of file pl_exec.c.

References arg, FuncExpr::args, OpExpr::args, bms_is_member(), contains_target_param(), PLpgSQL_expr::expr_simple_expr, FuncExpr::funcid, IsA, lfirst, OpExpr::opfuncid, PLpgSQL_expr::paramnos, and PLpgSQL_expr::rwparam.

Referenced by exec_assign_expr(), and exec_eval_simple_expr().

8072 {
8073  Oid funcid;
8074  List *fargs;
8075  ListCell *lc;
8076 
8077  /* Assume unsafe */
8078  expr->rwparam = -1;
8079 
8080  /*
8081  * If the expression isn't simple, there's no point in trying to optimize
8082  * (because the exec_run_select code path will flatten any expanded result
8083  * anyway). Even without that, this seems like a good safety restriction.
8084  */
8085  if (expr->expr_simple_expr == NULL)
8086  return;
8087 
8088  /*
8089  * If target variable isn't referenced by expression, no need to look
8090  * further.
8091  */
8092  if (!bms_is_member(target_dno, expr->paramnos))
8093  return;
8094 
8095  /*
8096  * Top level of expression must be a simple FuncExpr or OpExpr.
8097  */
8098  if (IsA(expr->expr_simple_expr, FuncExpr))
8099  {
8100  FuncExpr *fexpr = (FuncExpr *) expr->expr_simple_expr;
8101 
8102  funcid = fexpr->funcid;
8103  fargs = fexpr->args;
8104  }
8105  else if (IsA(expr->expr_simple_expr, OpExpr))
8106  {
8107  OpExpr *opexpr = (OpExpr *) expr->expr_simple_expr;
8108 
8109  funcid = opexpr->opfuncid;
8110  fargs = opexpr->args;
8111  }
8112  else
8113  return;
8114 
8115  /*
8116  * The top-level function must be one that we trust to be "safe".
8117  * Currently we hard-wire the list, but it would be very desirable to
8118  * allow extensions to mark their functions as safe ...
8119  */
8120  if (!(funcid == F_ARRAY_APPEND ||
8121  funcid == F_ARRAY_PREPEND))
8122  return;
8123 
8124  /*
8125  * The target variable (in the form of a Param) must only appear as a
8126  * direct argument of the top-level function.
8127  */
8128  foreach(lc, fargs)
8129  {
8130  Node *arg = (Node *) lfirst(lc);
8131 
8132  /* A Param is OK, whether it's the target variable or not */
8133  if (arg && IsA(arg, Param))
8134  continue;
8135  /* Otherwise, argument expression must not reference target */
8136  if (contains_target_param(arg, &target_dno))
8137  return;
8138  }
8139 
8140  /* OK, we can pass target as a read-write parameter */
8141  expr->rwparam = target_dno;
8142 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:575
List * args
Definition: primnodes.h:463
Definition: nodes.h:524
unsigned int Oid
Definition: postgres_ext.h:31
Bitmapset * paramnos
Definition: plpgsql.h:223
Oid funcid
Definition: primnodes.h:455
static bool contains_target_param(Node *node, int *target_dno)
Definition: pl_exec.c:8148
Expr * expr_simple_expr
Definition: plpgsql.h:233
int rwparam
Definition: plpgsql.h:224
Oid opfuncid
Definition: primnodes.h:503
#define lfirst(lc)
Definition: pg_list.h:190
void * arg
List * args
Definition: primnodes.h:508
Definition: pg_list.h:50
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:427

◆ exec_dynquery_with_params()

static Portal exec_dynquery_with_params ( PLpgSQL_execstate estate,
PLpgSQL_expr dynquery,
List params,
const char *  portalname,
int  cursorOptions 
)
static

Definition at line 8496 of file pl_exec.c.

References convert_value_to_string(), elog, ereport, errcode(), errmsg(), ERROR, exec_eval_cleanup(), exec_eval_expr(), exec_eval_using_params(), get_stmt_mcontext(), MemoryContextReset(), MemoryContextStrdup(), PreparedParamsData::nargs, PreparedParamsData::nulls, PLpgSQL_execstate::readonly_func, SPI_cursor_open_with_args(), SPI_result, SPI_result_code_string(), PreparedParamsData::types, and PreparedParamsData::values.

Referenced by exec_stmt_dynfors(), exec_stmt_open(), and exec_stmt_return_query().

8501 {
8502  Portal portal;
8503  Datum query;
8504  bool isnull;
8505  Oid restype;
8506  int32 restypmod;
8507  char *querystr;
8508  MemoryContext stmt_mcontext = get_stmt_mcontext(estate);
8509 
8510  /*
8511  * Evaluate the string expression after the EXECUTE keyword. Its result is
8512  * the querystring we have to execute.
8513  */
8514  query = exec_eval_expr(estate, dynquery, &isnull, &restype, &restypmod);
8515  if (isnull)
8516  ereport(ERROR,
8517  (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
8518  errmsg("query string argument of EXECUTE is null")));
8519 
8520  /* Get the C-String representation */
8521  querystr = convert_value_to_string(estate, query, restype);
8522 
8523  /* copy it into the stmt_mcontext before we clean up */
8524  querystr = MemoryContextStrdup(stmt_mcontext, querystr);
8525 
8526  exec_eval_cleanup(estate);
8527 
8528  /*
8529  * Open an implicit cursor for the query. We use
8530  * SPI_cursor_open_with_args even when there are no params, because this
8531  * avoids making and freeing one copy of the plan.
8532  */
8533  if (params)
8534  {
8535  PreparedParamsData *ppd;
8536 
8537  ppd = exec_eval_using_params(estate, params);
8538  portal = SPI_cursor_open_with_args(portalname,
8539  querystr,
8540  ppd->nargs, ppd->types,
8541  ppd->values, ppd->nulls,
8542  estate->readonly_func,
8543  cursorOptions);
8544  }
8545  else
8546  {
8547  portal = SPI_cursor_open_with_args(portalname,
8548  querystr,
8549  0, NULL,
8550  NULL, NULL,
8551  estate->readonly_func,
8552  cursorOptions);
8553  }
8554 
8555  if (portal == NULL)
8556  elog(ERROR, "could not open implicit cursor for query \"%s\": %s",
8557  querystr, SPI_result_code_string(SPI_result));
8558 
8559  /* Release transient data */
8560  MemoryContextReset(stmt_mcontext);
8561 
8562  return portal;
8563 }
int errcode(int sqlerrcode)
Definition: elog.c:570
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:136
static void exec_eval_cleanup(PLpgSQL_execstate *estate)
Definition: pl_exec.c:4020
Datum * values
Definition: pl_exec.c:58
unsigned int Oid
Definition: postgres_ext.h:31
signed int int32
Definition: c.h:346
int SPI_result
Definition: spi.c:47
#define ERROR
Definition: elog.h:43
static Datum exec_eval_expr(PLpgSQL_execstate *estate, PLpgSQL_expr *expr, bool *isNull, Oid *rettype, int32 *rettypmod)
Definition: pl_exec.c:5753
static PreparedParamsData * exec_eval_using_params(PLpgSQL_execstate *estate, List *params)
Definition: pl_exec.c:8417
const char * SPI_result_code_string(int code)
Definition: spi.c:1705
static MemoryContext get_stmt_mcontext(PLpgSQL_execstate *estate)
Definition: pl_exec.c:1495
#define ereport(elevel, rest)
Definition: elog.h:141
uintptr_t Datum
Definition: postgres.h:367
Portal SPI_cursor_open_with_args(const char *name, const char *src, int nargs, Oid *argtypes, Datum *Values, const char *Nulls, bool read_only, int cursorOptions)
Definition: spi.c:1248
int errmsg(const char *fmt,...)
Definition: elog.c:784
char * MemoryContextStrdup(MemoryContext context, const char *string)
Definition: mcxt.c:1148
#define elog(elevel,...)
Definition: elog.h:226
static char * convert_value_to_string(PLpgSQL_execstate *estate, Datum value, Oid valtype)
Definition: pl_exec.c:7644

◆ exec_eval_boolean()

static bool exec_eval_boolean ( PLpgSQL_execstate estate,
PLpgSQL_expr expr,
bool isNull 
)
static

Definition at line 5730 of file pl_exec.c.

References DatumGetBool, exec_cast_value(), and exec_eval_expr().

Referenced by exec_stmt_assert(), exec_stmt_case(), exec_stmt_exit(), exec_stmt_if(), and exec_stmt_while().

5733 {
5734  Datum exprdatum;
5735  Oid exprtypeid;
5736  int32 exprtypmod;
5737 
5738  exprdatum = exec_eval_expr(estate, expr, isNull, &exprtypeid, &exprtypmod);
5739  exprdatum = exec_cast_value(estate, exprdatum, isNull,
5740  exprtypeid, exprtypmod,
5741  BOOLOID, -1);
5742  return DatumGetBool(exprdatum);
5743 }
unsigned int Oid
Definition: postgres_ext.h:31
signed int int32
Definition: c.h:346
static Datum exec_cast_value(PLpgSQL_execstate *estate, Datum value, bool *isnull, Oid valtype, int32 valtypmod, Oid reqtype, int32 reqtypmod)
Definition: pl_exec.c:7673
static Datum exec_eval_expr(PLpgSQL_execstate *estate, PLpgSQL_expr *expr, bool *isNull, Oid *rettype, int32 *rettypmod)
Definition: pl_exec.c:5753
#define DatumGetBool(X)
Definition: postgres.h:393
uintptr_t Datum
Definition: postgres.h:367

◆ exec_eval_cleanup()

static void exec_eval_cleanup ( PLpgSQL_execstate estate)
static

Definition at line 4020 of file pl_exec.c.

References PLpgSQL_execstate::eval_econtext, PLpgSQL_execstate::eval_tuptable, ResetExprContext, and SPI_freetuptable().

Referenced by exec_assign_expr(), exec_dynquery_with_params(), exec_eval_using_params(), exec_for_query(), exec_run_select(), exec_stmt_assert(), exec_stmt_block(), exec_stmt_call(), exec_stmt_case(), exec_stmt_dynexecute(), exec_stmt_execsql(), exec_stmt_exit(), exec_stmt_fetch(), exec_stmt_forc(), exec_stmt_foreach_a(), exec_stmt_fori(), exec_stmt_getdiag(), exec_stmt_if(), exec_stmt_open(), exec_stmt_perform(), exec_stmt_raise(), exec_stmt_return_next(), exec_stmt_return_query(), exec_stmt_while(), plpgsql_exec_event_trigger(), plpgsql_exec_function(), and plpgsql_exec_trigger().

4021 {
4022  /* Clear result of a full SPI_execute */
4023  if (estate->eval_tuptable != NULL)
4025  estate->eval_tuptable = NULL;
4026 
4027  /*
4028  * Clear result of exec_eval_simple_expr (but keep the econtext). This
4029  * also clears any short-lived allocations done via get_eval_mcontext.
4030  */
4031  if (estate->eval_econtext != NULL)
4033 }
SPITupleTable * eval_tuptable
Definition: plpgsql.h:1095
void SPI_freetuptable(SPITupleTable *tuptable)
Definition: spi.c:1162
ExprContext * eval_econtext
Definition: plpgsql.h:1097
#define ResetExprContext(econtext)
Definition: executor.h:495

◆ exec_eval_datum()

static void exec_eval_datum ( PLpgSQL_execstate estate,
PLpgSQL_datum datum,
Oid typeid,
int32 typetypmod,
Datum value,
bool isnull 
)
static

Definition at line 5376 of file pl_exec.c.

References PLpgSQL_type::atttypmod, BlessTupleDesc(), PLpgSQL_var::datatype, PLpgSQL_execstate::datums, PLpgSQL_datum::dtype, PLpgSQL_var::dtype, elog, ExpandedRecordHeader::er_tupdesc_id, ExpandedRecordHeader::er_typeid, ExpandedRecordHeader::er_typmod, ereport, PLpgSQL_rec::erh, errcode(), errmsg(), ERROR, expanded_record_get_field(), expanded_record_lookup_field(), ExpandedRecordGetDatum, ExpandedRecordIsEmpty, PLpgSQL_recfield::fieldname, PLpgSQL_recfield::finfo, ExpandedRecordFieldInfo::fnumber, ExpandedRecordFieldInfo::ftypeid, ExpandedRecordFieldInfo::ftypmod, get_eval_mcontext, HeapTupleGetDatum, instantiate_empty_record_variable(), PLpgSQL_var::isnull, make_tuple_from_row(), MemoryContextSwitchTo(), PLPGSQL_DTYPE_PROMISE, PLPGSQL_DTYPE_REC, PLPGSQL_DTYPE_RECFIELD, PLPGSQL_DTYPE_ROW, PLPGSQL_DTYPE_VAR, plpgsql_fulfill_promise(), PLpgSQL_recfield::recparentno, PLpgSQL_recfield::rectupledescid, PLpgSQL_rec::rectypeid, PLpgSQL_rec::refname, PLpgSQL_row::rowtupdesc, TupleDescData::tdtypeid, TupleDescData::tdtypmod, PLpgSQL_type::typoid, unlikely, and PLpgSQL_var::value.

Referenced by exec_assign_value(), exec_stmt_return(), format_expr_params(), make_tuple_from_row(), plpgsql_param_eval_generic(), plpgsql_param_eval_generic_ro(), and plpgsql_param_fetch().

5382 {
5383  MemoryContext oldcontext;
5384 
5385  switch (datum->dtype)
5386  {
5387  case PLPGSQL_DTYPE_PROMISE:
5388  /* fulfill promise if needed, then handle like regular var */
5389  plpgsql_fulfill_promise(estate, (PLpgSQL_var *) datum);
5390 
5391  /* FALL THRU */
5392 
5393  case PLPGSQL_DTYPE_VAR:
5394  {
5395  PLpgSQL_var *var = (PLpgSQL_var *) datum;
5396 
5397  *typeid = var->datatype->typoid;
5398  *typetypmod = var->datatype->atttypmod;
5399  *value = var->value;
5400  *isnull = var->isnull;
5401  break;
5402  }
5403 
5404  case PLPGSQL_DTYPE_ROW:
5405  {
5406  PLpgSQL_row *row = (PLpgSQL_row *) datum;
5407  HeapTuple tup;
5408 
5409  /* We get here if there are multiple OUT parameters */
5410  if (!row->rowtupdesc) /* should not happen */
5411  elog(ERROR, "row variable has no tupdesc");
5412  /* Make sure we have a valid type/typmod setting */
5413  BlessTupleDesc(row->rowtupdesc);
5414  oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
5415  tup = make_tuple_from_row(estate, row, row->rowtupdesc);
5416  if (tup == NULL) /* should not happen */
5417  elog(ERROR, "row not compatible with its own tupdesc");
5418  *typeid = row->rowtupdesc->tdtypeid;
5419  *typetypmod = row->rowtupdesc->tdtypmod;
5420  *value = HeapTupleGetDatum(tup);
5421  *isnull = false;
5422  MemoryContextSwitchTo(oldcontext);
5423  break;
5424  }
5425 
5426  case PLPGSQL_DTYPE_REC:
5427  {
5428  PLpgSQL_rec *rec = (PLpgSQL_rec *) datum;
5429 
5430  if (rec->erh == NULL)
5431  {
5432  /* Treat uninstantiated record as a simple NULL */
5433  *value = (Datum) 0;
5434  *isnull = true;
5435  /* Report variable's declared type */
5436  *typeid = rec->rectypeid;
5437  *typetypmod = -1;
5438  }
5439  else
5440  {
5441  if (ExpandedRecordIsEmpty(rec->erh))
5442  {
5443  /* Empty record is also a NULL */
5444  *value = (Datum) 0;
5445  *isnull = true;
5446  }
5447  else
5448  {
5449  *value = ExpandedRecordGetDatum(rec->erh);
5450  *isnull = false;
5451  }
5452  if (rec->rectypeid != RECORDOID)
5453  {
5454  /* Report variable's declared type, if not RECORD */
5455  *typeid = rec->rectypeid;
5456  *typetypmod = -1;
5457  }
5458  else
5459  {
5460  /* Report record's actual type if declared RECORD */
5461  *typeid = rec->erh->er_typeid;
5462  *typetypmod = rec->erh->er_typmod;
5463  }
5464  }
5465  break;
5466  }
5467 
5469  {
5470  PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) datum;
5471  PLpgSQL_rec *rec;
5472  ExpandedRecordHeader *erh;
5473 
5474  rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
5475  erh = rec->erh;
5476 
5477  /*
5478  * If record variable is NULL, instantiate it if it has a
5479  * named composite type, else complain. (This won't change
5480  * the logical state of the record: it's still NULL.)
5481  */
5482  if (erh == NULL)
5483  {
5484  instantiate_empty_record_variable(estate, rec);
5485  erh = rec->erh;
5486  }
5487 
5488  /*
5489  * Look up the field's properties if we have not already, or
5490  * if the tuple descriptor ID changed since last time.
5491  */
5492  if (unlikely(recfield->rectupledescid != erh->er_tupdesc_id))
5493  {
5495  recfield->fieldname,
5496  &recfield->finfo))
5497  ereport(ERROR,
5498  (errcode(ERRCODE_UNDEFINED_COLUMN),
5499  errmsg("record \"%s\" has no field \"%s\"",
5500  rec->refname, recfield->fieldname)));
5501  recfield->rectupledescid = erh->er_tupdesc_id;
5502  }
5503 
5504  /* Report type data. */
5505  *typeid = recfield->finfo.ftypeid;
5506  *typetypmod = recfield->finfo.ftypmod;
5507 
5508  /* And fetch the field value. */
5510  recfield->finfo.fnumber,
5511  isnull);
5512  break;
5513  }
5514 
5515  default:
5516  elog(ERROR, "unrecognized dtype: %d", datum->dtype);
5517  }
5518 }
static HeapTuple make_tuple_from_row(PLpgSQL_execstate *estate, PLpgSQL_row *row, TupleDesc tupdesc)
Definition: pl_exec.c:7290
#define ExpandedRecordIsEmpty(erh)
bool expanded_record_lookup_field(ExpandedRecordHeader *erh, const char *fieldname, ExpandedRecordFieldInfo *finfo)
static Datum expanded_record_get_field(ExpandedRecordHeader *erh, int fnumber, bool *isnull)
PLpgSQL_type * datatype
Definition: plpgsql.h:300
static struct @144 value
static void plpgsql_fulfill_promise(PLpgSQL_execstate *estate, PLpgSQL_var *var)
Definition: pl_exec.c:1335
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
static void instantiate_empty_record_variable(PLpgSQL_execstate *estate, PLpgSQL_rec *rec)
Definition: pl_exec.c:7609
ExpandedRecordHeader * erh
Definition: plpgsql.h:394
int errcode(int sqlerrcode)
Definition: elog.c:570
PLpgSQL_datum_type dtype
Definition: plpgsql.h:257
char * refname
Definition: plpgsql.h:373
PLpgSQL_datum ** datums
Definition: plpgsql.h:1071
#define ERROR
Definition: elog.h:43
int32 tdtypmod
Definition: tupdesc.h:83
TupleDesc BlessTupleDesc(TupleDesc tupdesc)
Definition: execTuples.c:2048
#define ereport(elevel, rest)
Definition: elog.h:141
uint64 rectupledescid
Definition: plpgsql.h:409
#define get_eval_mcontext(estate)
Definition: pl_exec.c:121
uintptr_t Datum
Definition: postgres.h:367
ExpandedRecordFieldInfo finfo
Definition: plpgsql.h:410
Datum value
Definition: plpgsql.h:313
#define HeapTupleGetDatum(tuple)
Definition: funcapi.h:221
Oid tdtypeid
Definition: tupdesc.h:82
int errmsg(const char *fmt,...)
Definition: elog.c:784
int32 atttypmod
Definition: plpgsql.h:209
#define elog(elevel,...)
Definition: elog.h:226
TupleDesc rowtupdesc
Definition: plpgsql.h:359
#define unlikely(x)
Definition: c.h:208
Oid rectypeid
Definition: plpgsql.h:387
#define ExpandedRecordGetDatum(erh)
char * fieldname
Definition: plpgsql.h:406
bool isnull
Definition: plpgsql.h:314
Oid typoid
Definition: plpgsql.h:202

◆ exec_eval_expr()

static Datum exec_eval_expr ( PLpgSQL_execstate estate,
PLpgSQL_expr expr,
bool isNull,
Oid rettype,
int32 rettypmod 
)
static

Definition at line 5753 of file pl_exec.c.

References CURSOR_OPT_PARALLEL_OK, ereport, errcode(), errmsg(), errmsg_plural(), ERROR, PLpgSQL_execstate::eval_processed, PLpgSQL_execstate::eval_tuptable, exec_eval_simple_expr(), exec_prepare_plan(), exec_run_select(), TupleDescData::natts, PLpgSQL_expr::plan, PLpgSQL_expr::query, SPI_getbinval(), SPI_OK_SELECT, SPITupleTable::tupdesc, TupleDescAttr, and SPITupleTable::vals.

Referenced by exec_assign_expr(), exec_dynquery_with_params(), exec_eval_boolean(), exec_eval_integer(), exec_eval_using_params(), exec_stmt_assert(), exec_stmt_case(), exec_stmt_dynexecute(), exec_stmt_foreach_a(), exec_stmt_fori(), exec_stmt_raise(), exec_stmt_return(), and exec_stmt_return_next().

5758 {
5759  Datum result = 0;
5760  int rc;
5761  Form_pg_attribute attr;
5762 
5763  /*
5764  * If first time through, create a plan for this expression.
5765  */
5766  if (expr->plan == NULL)
5767  exec_prepare_plan(estate, expr, CURSOR_OPT_PARALLEL_OK, true);
5768 
5769  /*
5770  * If this is a simple expression, bypass SPI and use the executor
5771  * directly
5772  */
5773  if (exec_eval_simple_expr(estate, expr,
5774  &result, isNull, rettype, rettypmod))
5775  return result;
5776 
5777  /*
5778  * Else do it the hard way via exec_run_select
5779  */
5780  rc = exec_run_select(estate, expr, 2, NULL);
5781  if (rc != SPI_OK_SELECT)
5782  ereport(ERROR,
5783  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5784  errmsg("query \"%s\" did not return data", expr->query)));
5785 
5786  /*
5787  * Check that the expression returns exactly one column...
5788  */
5789  if (estate->eval_tuptable->tupdesc->natts != 1)
5790  ereport(ERROR,
5791  (errcode(ERRCODE_SYNTAX_ERROR),
5792  errmsg_plural("query \"%s\" returned %d column",
5793  "query \"%s\" returned %d columns",
5794  estate->eval_tuptable->tupdesc->natts,
5795  expr->query,
5796  estate->eval_tuptable->tupdesc->natts)));
5797 
5798  /*
5799  * ... and get the column's datatype.
5800  */
5801  attr = TupleDescAttr(estate->eval_tuptable->tupdesc, 0);
5802  *rettype = attr->atttypid;
5803  *rettypmod = attr->atttypmod;
5804 
5805  /*
5806  * If there are no rows selected, the result is a NULL of that type.
5807  */
5808  if (estate->eval_processed == 0)
5809  {
5810  *isNull = true;
5811  return (Datum) 0;
5812  }
5813 
5814  /*
5815  * Check that the expression returned no more than one row.
5816  */
5817  if (estate->eval_processed != 1)
5818  ereport(ERROR,
5819  (errcode(ERRCODE_CARDINALITY_VIOLATION),
5820  errmsg("query \"%s\" returned more than one row",
5821  expr->query)));
5822 
5823  /*
5824  * Return the single result Datum.
5825  */
5826  return SPI_getbinval(estate->eval_tuptable->vals[0],
5827  estate->eval_tuptable->tupdesc, 1, isNull);
5828 }
char * query
Definition: plpgsql.h:221
static void exec_prepare_plan(PLpgSQL_execstate *estate, PLpgSQL_expr *expr, int cursorOptions, bool keepplan)
Definition: pl_exec.c:4041
SPITupleTable * eval_tuptable
Definition: plpgsql.h:1095
uint64 eval_processed
Definition: plpgsql.h:1096
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:837
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
int errcode(int sqlerrcode)
Definition: elog.c:570
HeapTuple * vals
Definition: spi.h:26
SPIPlanPtr plan
Definition: plpgsql.h:222
#define ERROR
Definition: elog.h:43
Datum SPI_getbinval(HeapTuple tuple, TupleDesc tupdesc, int fnumber, bool *isnull)
Definition: spi.c:1028
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:200
#define ereport(elevel, rest)
Definition: elog.h:141
uintptr_t Datum
Definition: postgres.h:367
TupleDesc tupdesc
Definition: spi.h:25
#define SPI_OK_SELECT
Definition: spi.h:57
static int exec_run_select(PLpgSQL_execstate *estate, PLpgSQL_expr *expr, long maxtuples, Portal *portalP)
Definition: pl_exec.c:5836
static bool exec_eval_simple_expr(PLpgSQL_execstate *estate, PLpgSQL_expr *expr, Datum *result, bool *isNull, Oid *rettype, int32 *rettypmod)
Definition: pl_exec.c:6073
#define CURSOR_OPT_PARALLEL_OK
Definition: parsenodes.h:2692
int errmsg(const char *fmt,...)
Definition: elog.c:784

◆ exec_eval_integer()

static int exec_eval_integer ( PLpgSQL_execstate estate,
PLpgSQL_expr expr,
bool isNull 
)
static

Definition at line 5707 of file pl_exec.c.

References DatumGetInt32, exec_cast_value(), and exec_eval_expr().

Referenced by exec_assign_value(), and exec_stmt_fetch().

5710 {
5711  Datum exprdatum;
5712  Oid exprtypeid;
5713  int32 exprtypmod;
5714 
5715  exprdatum = exec_eval_expr(estate, expr, isNull, &exprtypeid, &exprtypmod);
5716  exprdatum = exec_cast_value(estate, exprdatum, isNull,
5717  exprtypeid, exprtypmod,
5718  INT4OID, -1);
5719  return DatumGetInt32(exprdatum);
5720 }
#define DatumGetInt32(X)
Definition: postgres.h:472
unsigned int Oid
Definition: postgres_ext.h:31
signed int int32
Definition: c.h:346
static Datum exec_cast_value(PLpgSQL_execstate *estate, Datum value, bool *isnull, Oid valtype, int32 valtypmod, Oid reqtype, int32 reqtypmod)
Definition: pl_exec.c:7673
static Datum exec_eval_expr(PLpgSQL_execstate *estate, PLpgSQL_expr *expr, bool *isNull, Oid *rettype, int32 *rettypmod)
Definition: pl_exec.c:5753
uintptr_t Datum
Definition: postgres.h:367

◆ exec_eval_simple_expr()

static bool exec_eval_simple_expr ( PLpgSQL_execstate estate,
PLpgSQL_expr expr,
Datum result,
bool isNull,
Oid rettype,
int32 rettypmod 
)
static

Definition at line 6073 of file pl_exec.c.

References Assert, CommandCounterIncrement(), ExprContext::ecxt_param_list_info, EState::es_query_cxt, PLpgSQL_execstate::eval_econtext, exec_check_rw_parameter(), exec_save_simple_expr(), ExecEvalExpr(), ExecInitExprWithParams(), PLpgSQL_expr::expr_simple_expr, PLpgSQL_expr::expr_simple_generation, PLpgSQL_expr::expr_simple_in_use, PLpgSQL_expr::expr_simple_lxid, PLpgSQL_expr::expr_simple_state, PLpgSQL_expr::expr_simple_type, PLpgSQL_expr::expr_simple_typmod, CachedPlan::generation, get_eval_mcontext, GetTransactionSnapshot(), PGPROC::lxid, MemoryContextSwitchTo(), MyProc, PLpgSQL_execstate::paramLI, ParamListInfoData::parserSetupArg, PLpgSQL_expr::plan, PopActiveSnapshot(), PushActiveSnapshot(), PLpgSQL_execstate::readonly_func, ReleaseCachedPlan(), PLpgSQL_expr::rwparam, setup_param_list(), PLpgSQL_execstate::simple_eval_estate, and SPI_plan_get_cached_plan().

Referenced by exec_eval_expr().

6079 {
6080  ExprContext *econtext = estate->eval_econtext;
6081  LocalTransactionId curlxid = MyProc->lxid;
6082  CachedPlan *cplan;
6083  void *save_setup_arg;
6084  MemoryContext oldcontext;
6085 
6086  /*
6087  * Forget it if expression wasn't simple before.
6088  */
6089  if (expr->expr_simple_expr == NULL)
6090  return false;
6091 
6092  /*
6093  * If expression is in use in current xact, don't touch it.
6094  */
6095  if (expr->expr_simple_in_use && expr->expr_simple_lxid == curlxid)
6096  return false;
6097 
6098  /*
6099  * Revalidate cached plan, so that we will notice if it became stale. (We
6100  * need to hold a refcount while using the plan, anyway.) If replanning
6101  * is needed, do that work in the eval_mcontext.
6102  */
6103  oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
6104  cplan = SPI_plan_get_cached_plan(expr->plan);
6105  MemoryContextSwitchTo(oldcontext);
6106 
6107  /*
6108  * We can't get a failure here, because the number of CachedPlanSources in
6109  * the SPI plan can't change from what exec_simple_check_plan saw; it's a
6110  * property of the raw parsetree generated from the query text.
6111  */
6112  Assert(cplan != NULL);
6113 
6114  /* If it got replanned, update our copy of the simple expression */
6115  if (cplan->generation != expr->expr_simple_generation)
6116  {
6117  exec_save_simple_expr(expr, cplan);
6118  /* better recheck r/w safety, as it could change due to inlining */
6119  if (expr->rwparam >= 0)
6120  exec_check_rw_parameter(expr, expr->rwparam);
6121  }
6122 
6123  /*
6124  * Pass back previously-determined result type.
6125  */
6126  *rettype = expr->expr_simple_type;
6127  *rettypmod = expr->expr_simple_typmod;
6128 
6129  /*
6130  * Set up ParamListInfo to pass to executor. For safety, save and restore
6131  * estate->paramLI->parserSetupArg around our use of the param list.
6132  */
6133  save_setup_arg = estate->paramLI->parserSetupArg;
6134 
6135  econtext->ecxt_param_list_info = setup_param_list(estate, expr);
6136 
6137  /*
6138  * Prepare the expression for execution, if it's not been done already in
6139  * the current transaction. (This will be forced to happen if we called
6140  * exec_save_simple_expr above.)
6141  */
6142  if (expr->expr_simple_lxid != curlxid)
6143  {
6144  oldcontext = MemoryContextSwitchTo(estate->simple_eval_estate->es_query_cxt);
6145  expr->expr_simple_state =
6147  econtext->ecxt_param_list_info);
6148  expr->expr_simple_in_use = false;
6149  expr->expr_simple_lxid = curlxid;
6150  MemoryContextSwitchTo(oldcontext);
6151  }
6152 
6153  /*
6154  * We have to do some of the things SPI_execute_plan would do, in
6155  * particular advance the snapshot if we are in a non-read-only function.
6156  * Without this, stable functions within the expression would fail to see
6157  * updates made so far by our own function.
6158  */
6159  oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
6160  if (!estate->readonly_func)
6161  {
6164  }
6165 
6166  /*
6167  * Mark expression as busy for the duration of the ExecEvalExpr call.
6168  */
6169  expr->expr_simple_in_use = true;
6170 
6171  /*
6172  * Finally we can call the executor to evaluate the expression
6173  */
6174  *result = ExecEvalExpr(expr->expr_simple_state,
6175  econtext,
6176  isNull);
6177 
6178  /* Assorted cleanup */
6179  expr->expr_simple_in_use = false;
6180 
6181  econtext->ecxt_param_list_info = NULL;
6182 
6183  estate->paramLI->parserSetupArg = save_setup_arg;
6184 
6185  if (!estate->readonly_func)
6187 
6188  MemoryContextSwitchTo(oldcontext);
6189 
6190  /*
6191  * Now we can release our refcount on the cached plan.
6192  */
6193  ReleaseCachedPlan(cplan, true);
6194 
6195  /*
6196  * That's it.
6197  */
6198  return true;
6199 }
int expr_simple_generation
Definition: plpgsql.h:234
void * parserSetupArg
Definition: params.h:117
static void exec_check_rw_parameter(PLpgSQL_expr *expr, int target_dno)
Definition: pl_exec.c:8071
PGPROC * MyProc
Definition: proc.c:68
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void PopActiveSnapshot(void)
Definition: snapmgr.c:814
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:306
static void exec_save_simple_expr(PLpgSQL_expr *expr, CachedPlan *cplan)
Definition: pl_exec.c:7984
SPIPlanPtr plan
Definition: plpgsql.h:222
CachedPlan * SPI_plan_get_cached_plan(SPIPlanPtr plan)
Definition: spi.c:1798
MemoryContext es_query_cxt
Definition: execnodes.h:550
ParamListInfo paramLI
Definition: plpgsql.h:1081
EState * simple_eval_estate
Definition: plpgsql.h:1084
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:735
static Datum ExecEvalExpr(ExprState *state, ExprContext *econtext, bool *isNull)
Definition: executor.h:285
ExprState * ExecInitExprWithParams(Expr *node, ParamListInfo ext_params)
Definition: execExpr.c:158
void ReleaseCachedPlan(CachedPlan *plan, bool useResOwner)
Definition: plancache.c:1259
Expr * expr_simple_expr
Definition: plpgsql.h:233
uint32 LocalTransactionId
Definition: c.h:509
static ParamListInfo setup_param_list(PLpgSQL_execstate *estate, PLpgSQL_expr *expr)
Definition: pl_exec.c:6218
int rwparam
Definition: plpgsql.h:224
#define get_eval_mcontext(estate)
Definition: pl_exec.c:121
ExprState * expr_simple_state
Definition: plpgsql.h:244
void CommandCounterIncrement(void)
Definition: xact.c:1003
LocalTransactionId expr_simple_lxid
Definition: plpgsql.h:246
#define Assert(condition)
Definition: c.h:732
ExprContext * eval_econtext
Definition: plpgsql.h:1097
int generation
Definition: plancache.h:154
int32 expr_simple_typmod
Definition: plpgsql.h:236
bool expr_simple_in_use
Definition: plpgsql.h:245
ParamListInfo ecxt_param_list_info
Definition: execnodes.h:236
Oid expr_simple_type
Definition: plpgsql.h:235
LocalTransactionId lxid
Definition: proc.h:106

◆ exec_eval_using_params()

static PreparedParamsData * exec_eval_using_params ( PLpgSQL_execstate estate,
List params 
)
static

Definition at line 8417 of file pl_exec.c.

References CStringGetTextDatum, datumCopy(), DatumGetCString, exec_eval_cleanup(), exec_eval_expr(), get_stmt_mcontext(), get_typlenbyval(), i, lfirst, list_length(), MemoryContextAlloc(), MemoryContextSwitchTo(), PreparedParamsData::nargs, PreparedParamsData::nulls, PreparedParamsData::types, and PreparedParamsData::values.

Referenced by exec_dynquery_with_params(), and exec_stmt_dynexecute().

8418 {
8419  PreparedParamsData *ppd;
8420  MemoryContext stmt_mcontext = get_stmt_mcontext(estate);
8421  int nargs;
8422  int i;
8423  ListCell *lc;
8424 
8425  ppd = (PreparedParamsData *)
8426  MemoryContextAlloc(stmt_mcontext, sizeof(PreparedParamsData));
8427  nargs = list_length(params);
8428 
8429  ppd->nargs = nargs;
8430  ppd->types = (Oid *)
8431  MemoryContextAlloc(stmt_mcontext, nargs * sizeof(Oid));
8432  ppd->values = (Datum *)
8433  MemoryContextAlloc(stmt_mcontext, nargs * sizeof(Datum));
8434  ppd->nulls = (char *)
8435  MemoryContextAlloc(stmt_mcontext, nargs * sizeof(char));
8436 
8437  i = 0;
8438  foreach(lc, params)
8439  {
8440  PLpgSQL_expr *param = (PLpgSQL_expr *) lfirst(lc);
8441  bool isnull;
8442  int32 ppdtypmod;
8443  MemoryContext oldcontext;
8444 
8445  ppd->values[i] = exec_eval_expr(estate, param,
8446  &isnull,
8447  &ppd->types[i],
8448  &ppdtypmod);
8449  ppd->nulls[i] = isnull ? 'n' : ' ';
8450 
8451  oldcontext = MemoryContextSwitchTo(stmt_mcontext);
8452 
8453  if (ppd->types[i] == UNKNOWNOID)
8454  {
8455  /*
8456  * Treat 'unknown' parameters as text, since that's what most
8457  * people would expect. SPI_execute_with_args can coerce unknown
8458  * constants in a more intelligent way, but not unknown Params.
8459  * This code also takes care of copying into the right context.
8460  * Note we assume 'unknown' has the representation of C-string.
8461  */
8462  ppd->types[i] = TEXTOID;
8463  if (!isnull)
8465  }
8466  /* pass-by-ref non null values must be copied into stmt_mcontext */
8467  else if (!isnull)
8468  {
8469  int16 typLen;
8470  bool typByVal;
8471 
8472  get_typlenbyval(ppd->types[i], &typLen, &typByVal);
8473  if (!typByVal)
8474  ppd->values[i] = datumCopy(ppd->values[i], typByVal, typLen);
8475  }
8476 
8477  MemoryContextSwitchTo(oldcontext);
8478 
8479  exec_eval_cleanup(estate);
8480 
8481  i++;
8482  }
8483 
8484  return ppd;
8485 }
signed short int16
Definition: c.h:345
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
static void exec_eval_cleanup(PLpgSQL_execstate *estate)
Definition: pl_exec.c:4020
Datum * values
Definition: pl_exec.c:58
unsigned int Oid
Definition: postgres_ext.h:31
signed int int32
Definition: c.h:346
#define DatumGetCString(X)
Definition: postgres.h:566
static Datum exec_eval_expr(PLpgSQL_execstate *estate, PLpgSQL_expr *expr, bool *isNull, Oid *rettype, int32 *rettypmod)
Definition: pl_exec.c:5753
static MemoryContext get_stmt_mcontext(PLpgSQL_execstate *estate)
Definition: pl_exec.c:1495
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition: datum.c:130
uintptr_t Datum
Definition: postgres.h:367
#define lfirst(lc)
Definition: pg_list.h:190
static int list_length(const List *l)
Definition: pg_list.h:169
void get_typlenbyval(Oid typid, int16 *typlen, bool *typbyval)
Definition: lsyscache.c:2029
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:771
int i
#define CStringGetTextDatum(s)
Definition: builtins.h:83

◆ exec_for_query()

static int exec_for_query ( PLpgSQL_execstate estate,
PLpgSQL_stmt_forq stmt,
Portal  portal,
bool  prefetch_ok 
)
static

Definition at line 5900 of file pl_exec.c.

References PLpgSQL_execstate::atomic, PLpgSQL_stmt_forq::body, compatible_tupdescs(), PLpgSQL_execstate::datums, PLpgSQL_variable::dno, PLpgSQL_variable::dtype, ExpandedRecordHeader::er_tupdesc_id, PLpgSQL_rec::erh, exec_eval_cleanup(), exec_move_row(), exec_set_found(), exec_stmts(), expanded_record_get_tupdesc(), expanded_record_set_tuple(), i, INVALID_TUPLEDESC_IDENTIFIER, PLpgSQL_stmt_forq::label, LOOP_RC_PROCESSING, PinPortal(), PLPGSQL_DTYPE_REC, PLPGSQL_RC_OK, PLpgSQL_rec::rectypeid, SPI_cursor_fetch(), SPI_freetuptable(), SPI_processed, SPI_tuptable, TupleDescData::tdtypeid, SPITupleTable::tupdesc, UnpinPortal(), SPITupleTable::vals, and PLpgSQL_stmt_forq::var.

Referenced by exec_stmt_dynfors(), exec_stmt_forc(), and exec_stmt_fors().

5902 {
5903  PLpgSQL_variable *var;
5904  SPITupleTable *tuptab;
5905  bool found = false;
5906  int rc = PLPGSQL_RC_OK;
5907  uint64 previous_id = INVALID_TUPLEDESC_IDENTIFIER;
5908  bool tupdescs_match = true;
5909  uint64 n;
5910 
5911  /* Fetch loop variable's datum entry */
5912  var = (PLpgSQL_variable *) estate->datums[stmt->var->dno];
5913 
5914  /*
5915  * Make sure the portal doesn't get closed by the user statements we
5916  * execute.
5917  */
5918  PinPortal(portal);
5919 
5920  /*
5921  * Fetch the initial tuple(s). If prefetching is allowed then we grab a
5922  * few more rows to avoid multiple trips through executor startup
5923  * overhead.
5924  */
5925  SPI_cursor_fetch(portal, true, prefetch_ok ? 10 : 1);
5926  tuptab = SPI_tuptable;
5927  n = SPI_processed;
5928 
5929  /*
5930  * If the query didn't return any rows, set the target to NULL and fall
5931  * through with found = false.
5932  */
5933  if (n == 0)
5934  {
5935  exec_move_row(estate, var, NULL, tuptab->tupdesc);
5936  exec_eval_cleanup(estate);
5937  }
5938  else
5939  found = true; /* processed at least one tuple */
5940 
5941  /*
5942  * Now do the loop
5943  */
5944  while (n > 0)
5945  {
5946  uint64 i;
5947 
5948  for (i = 0; i < n; i++)
5949  {
5950  /*
5951  * Assign the tuple to the target. Here, because we know that all
5952  * loop iterations should be assigning the same tupdesc, we can
5953  * optimize away repeated creations of expanded records with
5954  * identical tupdescs. Testing for changes of er_tupdesc_id is
5955  * reliable even if the loop body contains assignments that
5956  * replace the target's value entirely, because it's assigned from
5957  * a process-global counter. The case where the tupdescs don't
5958  * match could possibly be handled more efficiently than this
5959  * coding does, but it's not clear extra effort is worthwhile.
5960  */
5961  if (var->dtype == PLPGSQL_DTYPE_REC)
5962  {
5963  PLpgSQL_rec *rec = (PLpgSQL_rec *) var;
5964 
5965  if (rec->erh &&
5966  rec->erh->er_tupdesc_id == previous_id &&
5967  tupdescs_match)
5968  {
5969  /* Only need to assign a new tuple value */
5970  expanded_record_set_tuple(rec->erh, tuptab->vals[i],
5971  true, !estate->atomic);
5972  }
5973  else
5974  {
5975  /*
5976  * First time through, or var's tupdesc changed in loop,
5977  * or we have to do it the hard way because type coercion
5978  * is needed.
5979  */
5980  exec_move_row(estate, var,
5981  tuptab->vals[i], tuptab->tupdesc);
5982 
5983  /*
5984  * Check to see if physical assignment is OK next time.
5985  * Once the tupdesc comparison has failed once, we don't
5986  * bother rechecking in subsequent loop iterations.
5987  */
5988  if (tupdescs_match)
5989  {
5990  tupdescs_match =
5991  (rec->rectypeid == RECORDOID ||
5992  rec->rectypeid == tuptab->tupdesc->tdtypeid ||
5993  compatible_tupdescs(tuptab->tupdesc,
5995  }
5996  previous_id = rec->erh->er_tupdesc_id;
5997  }
5998  }
5999  else
6000  exec_move_row(estate, var, tuptab->vals[i], tuptab->tupdesc);
6001 
6002  exec_eval_cleanup(estate);
6003 
6004  /*
6005  * Execute the statements
6006  */
6007  rc = exec_stmts(estate, stmt->body);
6008 
6009  LOOP_RC_PROCESSING(stmt->label, goto loop_exit);
6010  }
6011 
6012  SPI_freetuptable(tuptab);
6013 
6014  /*
6015  * Fetch more tuples. If prefetching is allowed, grab 50 at a time.
6016  */
6017  SPI_cursor_fetch(portal, true, prefetch_ok ? 50 : 1);
6018  tuptab = SPI_tuptable;
6019  n = SPI_processed;
6020  }
6021 
6022 loop_exit:
6023 
6024  /*
6025  * Release last group of tuples (if any)
6026  */
6027  SPI_freetuptable(tuptab);
6028 
6029  UnpinPortal(portal);
6030 
6031  /*
6032  * Set the FOUND variable to indicate the result of executing the loop
6033  * (namely, whether we looped one or more times). This must be set last so
6034  * that it does not interfere with the value of the FOUND variable inside
6035  * the loop processing itself.
6036  */
6037  exec_set_found(estate, found);
6038 
6039  return rc;
6040 }
void UnpinPortal(Portal portal)
Definition: portalmem.c:377
void expanded_record_set_tuple(ExpandedRecordHeader *erh, HeapTuple tuple, bool copy, bool expand_external)
SPITupleTable * SPI_tuptable
Definition: spi.c:46
ExpandedRecordHeader * erh
Definition: plpgsql.h:394
static void exec_eval_cleanup(PLpgSQL_execstate *estate)
Definition: pl_exec.c:4020
HeapTuple * vals
Definition: spi.h:26
#define INVALID_TUPLEDESC_IDENTIFIER
Definition: typcache.h:146
uint64 SPI_processed
Definition: spi.c:45
PLpgSQL_datum ** datums
Definition: plpgsql.h:1071
void PinPortal(Portal portal)
Definition: portalmem.c:368
#define LOOP_RC_PROCESSING(looplabel, exit_action)
Definition: pl_exec.c:188
static TupleDesc expanded_record_get_tupdesc(ExpandedRecordHeader *erh)
void SPI_freetuptable(SPITupleTable *tuptable)
Definition: spi.c:1162
static bool compatible_tupdescs(TupleDesc src_tupdesc, TupleDesc dst_tupdesc)
Definition: pl_exec.c:7246
TupleDesc tupdesc
Definition: spi.h:25
PLpgSQL_datum_type dtype
Definition: plpgsql.h:269
PLpgSQL_variable * var
Definition: plpgsql.h:707
static void exec_set_found(PLpgSQL_execstate *estate, bool state)
Definition: pl_exec.c:8170
Oid tdtypeid
Definition: tupdesc.h:82
static void exec_move_row(PLpgSQL_execstate *estate, PLpgSQL_variable *target, HeapTuple tup, TupleDesc tupdesc)
Definition: pl_exec.c:6711
int i
void SPI_cursor_fetch(Portal portal, bool forward, long count)
Definition: spi.c:1539
Oid rectypeid
Definition: plpgsql.h:387
static int exec_stmts(PLpgSQL_execstate *estate, List *stmts)
Definition: pl_exec.c:1906

◆ exec_init_tuple_store()

static void exec_init_tuple_store ( PLpgSQL_execstate estate)
static

Definition at line 3570 of file pl_exec.c.

References ReturnSetInfo::allowedModes, CurrentResourceOwner, ereport, errcode(), errmsg(), ERROR, ReturnSetInfo::expectedDesc, IsA, MemoryContextSwitchTo(), PLpgSQL_execstate::rsi, SFRM_Materialize, SFRM_Materialize_Random, PLpgSQL_execstate::tuple_store, PLpgSQL_execstate::tuple_store_cxt, PLpgSQL_execstate::tuple_store_desc, PLpgSQL_execstate::tuple_store_owner, tuplestore_begin_heap(), and work_mem.

Referenced by exec_stmt_return_next(), and exec_stmt_return_query().

3571 {
3572  ReturnSetInfo *rsi = estate->rsi;
3573  MemoryContext oldcxt;
3574  ResourceOwner oldowner;
3575 
3576  /*
3577  * Check caller can handle a set result in the way we want
3578  */
3579  if (!rsi || !IsA(rsi, ReturnSetInfo) ||
3580  (rsi->allowedModes & SFRM_Materialize) == 0 ||
3581  rsi->expectedDesc == NULL)
3582  ereport(ERROR,
3583  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3584  errmsg("set-valued function called in context that cannot accept a set")));
3585 
3586  /*
3587  * Switch to the right memory context and resource owner for storing the
3588  * tuplestore for return set. If we're within a subtransaction opened for
3589  * an exception-block, for example, we must still create the tuplestore in
3590  * the resource owner that was active when this function was entered, and
3591  * not in the subtransaction resource owner.
3592  */
3593  oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
3594  oldowner = CurrentResourceOwner;
3596 
3597  estate->tuple_store =
3599  false, work_mem);
3600 
3601  CurrentResourceOwner = oldowner;
3602  MemoryContextSwitchTo(oldcxt);
3603 
3604  estate->tuple_store_desc = rsi->expectedDesc;
3605 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:575
ResourceOwner tuple_store_owner
Definition: plpgsql.h:1059
ResourceOwner CurrentResourceOwner
Definition: resowner.c:142
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
int errcode(int sqlerrcode)
Definition: elog.c:570
TupleDesc expectedDesc
Definition: execnodes.h:302
TupleDesc tuple_store_desc
Definition: plpgsql.h:1057
#define ERROR
Definition: elog.h:43
MemoryContext tuple_store_cxt
Definition: plpgsql.h:1058
ReturnSetInfo * rsi
Definition: plpgsql.h:1060
#define ereport(elevel, rest)
Definition: elog.h:141
Tuplestorestate * tuple_store
Definition: plpgsql.h:1056
Tuplestorestate * tuplestore_begin_heap(bool randomAccess, bool interXact, int maxKBytes)
Definition: tuplestore.c:318
int work_mem
Definition: globals.c:121
int allowedModes
Definition: execnodes.h:303
int errmsg(const char *fmt,...)
Definition: elog.c:784

◆ exec_move_row()

static void exec_move_row ( PLpgSQL_execstate estate,
PLpgSQL_variable target,
HeapTuple  tup,
TupleDesc  tupdesc 
)
static

Definition at line 6711 of file pl_exec.c.

References assign_record_var(), PLpgSQL_execstate::atomic, compatible_tupdescs(), PLpgSQL_rec::datatype, deconstruct_expanded_record(), DeleteExpandedObject(), PLpgSQL_variable::dtype, PLpgSQL_rec::erh, eval_mcontext_alloc, exec_move_row_from_fields(), expanded_record_get_tupdesc(), expanded_record_set_tuple(), ExpandedRecordGetDatum, heap_deform_tuple(), HeapTupleIsValid, lengthof, make_expanded_record_for_rec(), TupleDescData::natts, PLPGSQL_DTYPE_REC, PLpgSQL_rec::rectypeid, TupleDescData::tdtypeid, PLpgSQL_type::typtype, and values.

Referenced by exec_assign_value(), exec_for_query(), exec_move_row_from_datum(), exec_stmt_block(), exec_stmt_call(), exec_stmt_dynexecute(), exec_stmt_execsql(), exec_stmt_fetch(), and plpgsql_exec_function().

6714 {
6715  ExpandedRecordHeader *newerh = NULL;
6716 
6717  /*
6718  * If target is RECORD, we may be able to avoid field-by-field processing.
6719  */
6720  if (target->dtype == PLPGSQL_DTYPE_REC)
6721  {
6722  PLpgSQL_rec *rec = (PLpgSQL_rec *) target;
6723 
6724  /*
6725  * If we have no source tupdesc, just set the record variable to NULL.
6726  * (If we have a source tupdesc but not a tuple, we'll set the
6727  * variable to a row of nulls, instead. This is odd perhaps, but
6728  * backwards compatible.)
6729  */
6730  if (tupdesc == NULL)
6731  {
6732  if (rec->datatype &&
6733  rec->datatype->typtype == TYPTYPE_DOMAIN)
6734  {
6735  /*
6736  * If it's a composite domain, NULL might not be a legal
6737  * value, so we instead need to make an empty expanded record
6738  * and ensure that domain type checking gets done. If there
6739  * is already an expanded record, piggyback on its lookups.
6740  */
6741  newerh = make_expanded_record_for_rec(estate, rec,
6742  NULL, rec->erh);
6743  expanded_record_set_tuple(newerh, NULL, false, false);
6744  assign_record_var(estate, rec, newerh);
6745  }
6746  else
6747  {
6748  /* Just clear it to NULL */
6749  if (rec->erh)
6751  rec->erh = NULL;
6752  }
6753  return;
6754  }
6755 
6756  /*
6757  * Build a new expanded record with appropriate tupdesc.
6758  */
6759  newerh = make_expanded_record_for_rec(estate, rec, tupdesc, NULL);
6760 
6761  /*
6762  * If the rowtypes match, or if we have no tuple anyway, we can
6763  * complete the assignment without field-by-field processing.
6764  *
6765  * The tests here are ordered more or less in order of cheapness. We
6766  * can easily detect it will work if the target is declared RECORD or
6767  * has the same typeid as the source. But when assigning from a query
6768  * result, it's common to have a source tupdesc that's labeled RECORD
6769  * but is actually physically compatible with a named-composite-type
6770  * target, so it's worth spending extra cycles to check for that.
6771  */
6772  if (rec->rectypeid == RECORDOID ||
6773  rec->rectypeid == tupdesc->tdtypeid ||
6774  !HeapTupleIsValid(tup) ||
6776  {
6777  if (!HeapTupleIsValid(tup))
6778  {
6779  /* No data, so force the record into all-nulls state */
6781  }
6782  else
6783  {
6784  /* No coercion is needed, so just assign the row value */
6785  expanded_record_set_tuple(newerh, tup, true, !estate->atomic);
6786  }
6787 
6788  /* Complete the assignment */
6789  assign_record_var(estate, rec, newerh);
6790 
6791  return;
6792  }
6793  }
6794 
6795  /*
6796  * Otherwise, deconstruct the tuple and do field-by-field assignment,
6797  * using exec_move_row_from_fields.
6798  */
6799  if (tupdesc && HeapTupleIsValid(tup))
6800  {
6801  int td_natts = tupdesc->natts;
6802  Datum *values;
6803  bool *nulls;
6804  Datum values_local[64];
6805  bool nulls_local[64];
6806 
6807  /*
6808  * Need workspace arrays. If td_natts is small enough, use local
6809  * arrays to save doing a palloc. Even if it's not small, we can
6810  * allocate both the Datum and isnull arrays in one palloc chunk.
6811  */
6812  if (td_natts <= lengthof(values_local))
6813  {
6814  values = values_local;
6815  nulls = nulls_local;
6816  }
6817  else
6818  {
6819  char *chunk;
6820 
6821  chunk = eval_mcontext_alloc(estate,
6822  td_natts * (sizeof(Datum) + sizeof(bool)));
6823  values = (Datum *) chunk;
6824  nulls = (bool *) (chunk + td_natts * sizeof(Datum));
6825  }
6826 
6827  heap_deform_tuple(tup, tupdesc, values, nulls);
6828 
6829  exec_move_row_from_fields(estate, target, newerh,
6830  values, nulls, tupdesc);
6831  }
6832  else
6833  {
6834  /*
6835  * Assign all-nulls.
6836  */
6837  exec_move_row_from_fields(estate, target, newerh,
6838  NULL, NULL, NULL);
6839  }
6840 }
PLpgSQL_type * datatype
Definition: plpgsql.h:386
static void assign_record_var(PLpgSQL_execstate *estate, PLpgSQL_rec *rec, ExpandedRecordHeader *erh)
Definition: pl_exec.c:8394
void expanded_record_set_tuple(ExpandedRecordHeader *erh, HeapTuple tuple, bool copy, bool expand_external)
ExpandedRecordHeader * erh
Definition: plpgsql.h:394
static void exec_move_row_from_fields(PLpgSQL_execstate *estate, PLpgSQL_variable *target, ExpandedRecordHeader *newerh, Datum *values, bool *nulls, TupleDesc tupdesc)
Definition: pl_exec.c:6980
#define lengthof(array)
Definition: c.h:662
static ExpandedRecordHeader * make_expanded_record_for_rec(PLpgSQL_execstate *estate, PLpgSQL_rec *rec, TupleDesc srctupdesc, ExpandedRecordHeader *srcerh)
Definition: pl_exec.c:6917
#define eval_mcontext_alloc(estate, sz)
Definition: pl_exec.c:123
static TupleDesc expanded_record_get_tupdesc(ExpandedRecordHeader *erh)
uintptr_t Datum
Definition: postgres.h:367
static bool compatible_tupdescs(TupleDesc src_tupdesc, TupleDesc dst_tupdesc)
Definition: pl_exec.c:7246
void DeleteExpandedObject(Datum d)
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
PLpgSQL_datum_type dtype
Definition: plpgsql.h:269
char typtype
Definition: plpgsql.h:206
void heap_deform_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *values, bool *isnull)
Definition: heaptuple.c:1249
static Datum values[MAXATTR]
Definition: bootstrap.c:167
Oid tdtypeid
Definition: tupdesc.h:82
Oid rectypeid
Definition: plpgsql.h:387
#define ExpandedRecordGetDatum(erh)
void deconstruct_expanded_record(ExpandedRecordHeader *erh)

◆ exec_move_row_from_datum()

static void exec_move_row_from_datum ( PLpgSQL_execstate estate,
PLpgSQL_variable target,
Datum  value 
)
static

Definition at line 7376 of file pl_exec.c.

References Assert, assign_record_var(), PLpgSQL_execstate::atomic, DatumGetEOHP(), DatumGetHeapTupleHeader, DatumGetPointer, deconstruct_expanded_record(), ExpandedRecordHeader::dnulls, PLpgSQL_variable::dtype, ExpandedRecordHeader::dvalues, ExpandedRecordHeader::er_decltypeid, ER_FLAG_FVALUE_VALID, ER_MAGIC, ExpandedRecordHeader::er_magic, ExpandedRecordHeader::er_typeid, ExpandedRecordHeader::er_typmod, PLpgSQL_rec::erh, exec_move_row(), exec_move_row_from_fields(), expanded_record_get_tupdesc(), expanded_record_set_tuple(), ExpandedRecordIsDomain, ExpandedRecordIsEmpty, ExpandedRecordHeader::flags, ExpandedRecordHeader::fvalue, get_eval_mcontext, HeapTupleHeaderGetDatumLength, HeapTupleHeaderGetTypeId, HeapTupleHeaderGetTypMod, InvalidOid, ItemPointerSetInvalid, lookup_rowtype_tupdesc(), make_expanded_record_for_rec(), make_expanded_record_from_typeid(), MemoryContextSwitchTo(), PLPGSQL_DTYPE_REC, PLpgSQL_rec::rectypeid, ReleaseTupleDesc, revalidate_rectypeid(), HeapTupleData::t_data, HeapTupleData::t_len, HeapTupleData::t_self, HeapTupleData::t_tableOid, VARATT_IS_EXTERNAL_EXPANDED, and VARATT_IS_EXTERNAL_EXPANDED_RW.

Referenced by exec_assign_value(), and plpgsql_exec_function().

7379 {
7380  /* Check to see if source is an expanded record */
7382  {
7384  ExpandedRecordHeader *newerh = NULL;
7385 
7386  Assert(erh->er_magic == ER_MAGIC);
7387 
7388  /* These cases apply if the target is record not row... */
7389  if (target->dtype == PLPGSQL_DTYPE_REC)
7390  {
7391  PLpgSQL_rec *rec = (PLpgSQL_rec *) target;
7392 
7393  /*
7394  * If it's the same record already stored in the variable, do
7395  * nothing. This would happen only in silly cases like "r := r",
7396  * but we need some check to avoid possibly freeing the variable's
7397  * live value below. Note that this applies even if what we have
7398  * is a R/O pointer.
7399  */
7400  if (erh == rec->erh)
7401  return;
7402 
7403  /*
7404  * Make sure rec->rectypeid is up-to-date before using it.
7405  */
7406  revalidate_rectypeid(rec);
7407 
7408  /*
7409  * If we have a R/W pointer, we're allowed to just commandeer
7410  * ownership of the expanded record. If it's of the right type to
7411  * put into the record variable, do that. (Note we don't accept
7412  * an expanded record of a composite-domain type as a RECORD
7413  * value. We'll treat it as the base composite type instead;
7414  * compare logic in make_expanded_record_for_rec.)
7415  */
7417  (rec->rectypeid == erh->er_decltypeid ||
7418  (rec->rectypeid == RECORDOID &&
7419  !ExpandedRecordIsDomain(erh))))
7420  {
7421  assign_record_var(estate, rec, erh);
7422  return;
7423  }
7424 
7425  /*
7426  * If we already have an expanded record object in the target
7427  * variable, and the source record contains a valid tuple
7428  * representation with the right rowtype, then we can skip making
7429  * a new expanded record and just assign the tuple with
7430  * expanded_record_set_tuple. (We can't do the equivalent if we
7431  * have to do field-by-field assignment, since that wouldn't be
7432  * atomic if there's an error.) We consider that there's a
7433  * rowtype match only if it's the same named composite type or
7434  * same registered rowtype; checking for matches of anonymous
7435  * rowtypes would be more expensive than this is worth.
7436  */
7437  if (rec->erh &&
7438  (erh->flags & ER_FLAG_FVALUE_VALID) &&
7439  erh->er_typeid == rec->erh->er_typeid &&
7440  (erh->er_typeid != RECORDOID ||
7441  (erh->er_typmod == rec->erh->er_typmod &&
7442  erh->er_typmod >= 0)))
7443  {
7445  true, !estate->atomic);
7446  return;
7447  }
7448 
7449  /*
7450  * Otherwise we're gonna need a new expanded record object. Make
7451  * it here in hopes of piggybacking on the source object's
7452  * previous typcache lookup.
7453  */
7454  newerh = make_expanded_record_for_rec(estate, rec, NULL, erh);
7455 
7456  /*
7457  * If the expanded record contains a valid tuple representation,
7458  * and we don't need rowtype conversion, then just copying the
7459  * tuple is probably faster than field-by-field processing. (This
7460  * isn't duplicative of the previous check, since here we will
7461  * catch the case where the record variable was previously empty.)
7462  */
7463  if ((erh->flags & ER_FLAG_FVALUE_VALID) &&
7464  (rec->rectypeid == RECORDOID ||
7465  rec->rectypeid == erh->er_typeid))
7466  {
7467  expanded_record_set_tuple(newerh, erh->fvalue,
7468  true, !estate->atomic);
7469  assign_record_var(estate, rec, newerh);
7470  return;
7471  }
7472 
7473  /*
7474  * Need to special-case empty source record, else code below would
7475  * leak newerh.
7476  */
7477  if (ExpandedRecordIsEmpty(erh))
7478  {
7479  /* Set newerh to a row of NULLs */
7481  assign_record_var(estate, rec, newerh);
7482  return;
7483  }
7484  } /* end of record-target-only cases */
7485 
7486  /*
7487  * If the source expanded record is empty, we should treat that like a
7488  * NULL tuple value. (We're unlikely to see such a case, but we must
7489  * check this; deconstruct_expanded_record would cause a change of
7490  * logical state, which is not OK.)
7491  */
7492  if (ExpandedRecordIsEmpty(erh))
7493  {
7494  exec_move_row(estate, target, NULL,
7496  return;
7497  }
7498 
7499  /*
7500  * Otherwise, ensure that the source record is deconstructed, and
7501  * assign from its field values.
7502  */
7504  exec_move_row_from_fields(estate, target, newerh,
7505  erh->dvalues, erh->dnulls,
7507  }
7508  else
7509  {
7510  /*
7511  * Nope, we've got a plain composite Datum. Deconstruct it; but we
7512  * don't use deconstruct_composite_datum(), because we may be able to
7513  * skip calling lookup_rowtype_tupdesc().
7514  */
7515  HeapTupleHeader td;
7516  HeapTupleData tmptup;
7517  Oid tupType;
7518  int32 tupTypmod;
7519  TupleDesc tupdesc;
7520  MemoryContext oldcontext;
7521 
7522  /* Ensure that any detoasted data winds up in the eval_mcontext */
7523  oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
7524  /* Get tuple body (note this could involve detoasting) */
7526  MemoryContextSwitchTo(oldcontext);
7527 
7528  /* Build a temporary HeapTuple control structure */
7529  tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
7530  ItemPointerSetInvalid(&(tmptup.t_self));
7531  tmptup.t_tableOid = InvalidOid;
7532  tmptup.t_data = td;
7533 
7534  /* Extract rowtype info */
7535  tupType = HeapTupleHeaderGetTypeId(td);
7536  tupTypmod = HeapTupleHeaderGetTypMod(td);
7537 
7538  /* Now, if the target is record not row, maybe we can optimize ... */
7539  if (target->dtype == PLPGSQL_DTYPE_REC)
7540  {
7541  PLpgSQL_rec *rec = (PLpgSQL_rec *) target;
7542 
7543  /*
7544  * If we already have an expanded record object in the target
7545  * variable, and the source datum has a matching rowtype, then we
7546  * can skip making a new expanded record and just assign the tuple
7547  * with expanded_record_set_tuple. We consider that there's a
7548  * rowtype match only if it's the same named composite type or
7549  * same registered rowtype. (Checking to reject an anonymous
7550  * rowtype here should be redundant, but let's be safe.)
7551  */
7552  if (rec->erh &&
7553  tupType == rec->erh->er_typeid &&
7554  (tupType != RECORDOID ||
7555  (tupTypmod == rec->erh->er_typmod &&
7556  tupTypmod >= 0)))
7557  {
7558  expanded_record_set_tuple(rec->erh, &tmptup,
7559  true, !estate->atomic);
7560  return;
7561  }
7562 
7563  /*
7564  * If the source datum has a rowtype compatible with the target
7565  * variable, just build a new expanded record and assign the tuple
7566  * into it. Using make_expanded_record_from_typeid() here saves
7567  * one typcache lookup compared to the code below.
7568  */
7569  if (rec->rectypeid == RECORDOID || rec->rectypeid == tupType)
7570  {
7571  ExpandedRecordHeader *newerh;
7572  MemoryContext mcontext = get_eval_mcontext(estate);
7573 
7574  newerh = make_expanded_record_from_typeid(tupType, tupTypmod,
7575  mcontext);
7576  expanded_record_set_tuple(newerh, &tmptup,
7577  true, !estate->atomic);
7578  assign_record_var(estate, rec, newerh);
7579  return;
7580  }
7581 
7582  /*
7583  * Otherwise, we're going to need conversion, so fall through to
7584  * do it the hard way.
7585  */
7586  }
7587 
7588  /*
7589  * ROW target, or unoptimizable RECORD target, so we have to expend a
7590  * lookup to obtain the source datum's tupdesc.
7591  */
7592  tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
7593 
7594  /* Do the move */
7595  exec_move_row(estate, target, &tmptup, tupdesc);
7596 
7597  /* Release tupdesc usage count */
7598  ReleaseTupleDesc(tupdesc);
7599  }
7600 }
#define ER_FLAG_FVALUE_VALID
ExpandedRecordHeader * make_expanded_record_from_typeid(Oid type_id, int32 typmod, MemoryContext parentcontext)
#define ExpandedRecordIsEmpty(erh)
#define VARATT_IS_EXTERNAL_EXPANDED(PTR)
Definition: postgres.h:322
TupleDesc lookup_rowtype_tupdesc(Oid type_id, int32 typmod)
Definition: typcache.c:1652
static void assign_record_var(PLpgSQL_execstate *estate, PLpgSQL_rec *rec, ExpandedRecordHeader *erh)
Definition: pl_exec.c:8394
void expanded_record_set_tuple(ExpandedRecordHeader *erh, HeapTuple tuple, bool copy, bool expand_external)
static struct @144 value
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
ExpandedRecordHeader * erh
Definition: plpgsql.h:394
static void exec_move_row_from_fields(PLpgSQL_execstate *estate, PLpgSQL_variable *target, ExpandedRecordHeader *newerh, Datum *values, bool *nulls, TupleDesc tupdesc)
Definition: pl_exec.c:6980
unsigned int Oid
Definition: postgres_ext.h:31
#define DatumGetHeapTupleHeader(X)
Definition: fmgr.h:289
signed int int32
Definition: c.h:346
HeapTupleHeader t_data
Definition: htup.h:68
#define HeapTupleHeaderGetTypMod(tup)
Definition: htup_details.h:468
static ExpandedRecordHeader * make_expanded_record_for_rec(PLpgSQL_execstate *estate, PLpgSQL_rec *rec, TupleDesc srctupdesc, ExpandedRecordHeader *srcerh)
Definition: pl_exec.c:6917
ItemPointerData t_self
Definition: htup.h:65
uint32 t_len
Definition: htup.h:64
Oid t_tableOid
Definition: htup.h:66
static TupleDesc expanded_record_get_tupdesc(ExpandedRecordHeader *erh)
ExpandedObjectHeader * DatumGetEOHP(Datum d)
Definition: expandeddatum.c:29
#define get_eval_mcontext(estate)
Definition: pl_exec.c:121
#define ER_MAGIC
#define HeapTupleHeaderGetTypeId(tup)
Definition: htup_details.h:458
#define InvalidOid
Definition: postgres_ext.h:36
#define Assert(condition)
Definition: c.h:732
PLpgSQL_datum_type dtype
Definition: plpgsql.h:269
#define DatumGetPointer(X)
Definition: postgres.h:549
#define ItemPointerSetInvalid(pointer)
Definition: itemptr.h:172
static void exec_move_row(PLpgSQL_execstate *estate, PLpgSQL_variable *target, HeapTuple tup, TupleDesc tupdesc)
Definition: pl_exec.c:6711
static void revalidate_rectypeid(PLpgSQL_rec *rec)
Definition: pl_exec.c:6846
#define VARATT_IS_EXTERNAL_EXPANDED_RW(PTR)
Definition: postgres.h:320
Oid rectypeid
Definition: plpgsql.h:387
#define ReleaseTupleDesc(tupdesc)
Definition: tupdesc.h:122
#define ExpandedRecordIsDomain(erh)
void deconstruct_expanded_record(ExpandedRecordHeader *erh)
#define HeapTupleHeaderGetDatumLength(tup)
Definition: htup_details.h:452

◆ exec_move_row_from_fields()

static void exec_move_row_from_fields ( PLpgSQL_execstate estate,
PLpgSQL_variable target,
ExpandedRecordHeader newerh,
Datum values,
bool nulls,
TupleDesc  tupdesc 
)
static

Definition at line 6980 of file pl_exec.c.

References Assert, assign_record_var(), PLpgSQL_execstate::atomic, PLpgSQL_execstate::datums, PLpgSQL_variable::dtype, elog, ereport, errcode(), errdetail(), errhint(), errmsg(), ERROR, eval_mcontext_alloc, exec_assign_value(), exec_cast_value(), expanded_record_get_tupdesc(), expanded_record_set_fields(), lengthof, TupleDescData::natts, PLpgSQL_row::nfields, PLPGSQL_DTYPE_REC, PLPGSQL_DTYPE_ROW, plpgsql_extra_errors, plpgsql_extra_warnings, PLPGSQL_XCHECK_STRICTMULTIASSIGNMENT, TupleDescAttr, value, PLpgSQL_row::varnos, and WARNING.

Referenced by exec_move_row(), and exec_move_row_from_datum().

6985 {
6986  int td_natts = tupdesc ? tupdesc->natts : 0;
6987  int fnum;
6988  int anum;
6989  int strict_multiassignment_level = 0;
6990 
6991  /*
6992  * The extra check strict strict_multi_assignment can be active, only when
6993  * input tupdesc is specified.
6994  */
6995  if (tupdesc != NULL)
6996  {
6998  strict_multiassignment_level = ERROR;
6999  else if (plpgsql_extra_warnings & PLPGSQL_XCHECK_STRICTMULTIASSIGNMENT)
7000  strict_multiassignment_level = WARNING;
7001  }
7002 
7003  /* Handle RECORD-target case */
7004  if (target->dtype == PLPGSQL_DTYPE_REC)
7005  {
7006  PLpgSQL_rec *rec = (PLpgSQL_rec *) target;
7007  TupleDesc var_tupdesc;
7008  Datum newvalues_local[64];
7009  bool newnulls_local[64];
7010 
7011  Assert(newerh != NULL); /* caller must have built new object */
7012 
7013  var_tupdesc = expanded_record_get_tupdesc(newerh);
7014 
7015  /*
7016  * Coerce field values if needed. This might involve dealing with
7017  * different sets of dropped columns and/or coercing individual column
7018  * types. That's sort of a pain, but historically plpgsql has allowed
7019  * it, so we preserve the behavior. However, it's worth a quick check
7020  * to see if the tupdescs are identical. (Since expandedrecord.c
7021  * prefers to use refcounted tupdescs from the typcache, expanded
7022  * records with the same rowtype will have pointer-equal tupdescs.)
7023  */
7024  if (var_tupdesc != tupdesc)
7025  {
7026  int vtd_natts = var_tupdesc->natts;
7027  Datum *newvalues;
7028  bool *newnulls;
7029 
7030  /*
7031  * Need workspace arrays. If vtd_natts is small enough, use local
7032  * arrays to save doing a palloc. Even if it's not small, we can
7033  * allocate both the Datum and isnull arrays in one palloc chunk.
7034  */
7035  if (vtd_natts <= lengthof(newvalues_local))
7036  {
7037  newvalues = newvalues_local;
7038  newnulls = newnulls_local;
7039  }
7040  else
7041  {
7042  char *chunk;
7043 
7044  chunk = eval_mcontext_alloc(estate,
7045  vtd_natts * (sizeof(Datum) + sizeof(bool)));
7046  newvalues = (Datum *) chunk;
7047  newnulls = (bool *) (chunk + vtd_natts * sizeof(Datum));
7048  }
7049 
7050  /* Walk over destination columns */
7051  anum = 0;
7052  for (fnum = 0; fnum < vtd_natts; fnum++)
7053  {
7054  Form_pg_attribute attr = TupleDescAttr(var_tupdesc, fnum);
7055  Datum value;
7056  bool isnull;
7057  Oid valtype;
7058  int32 valtypmod;
7059 
7060  if (attr->attisdropped)
7061  {
7062  /* expanded_record_set_fields should ignore this column */
7063  continue; /* skip dropped column in record */
7064  }
7065 
7066  while (anum < td_natts &&
7067  TupleDescAttr(tupdesc, anum)->attisdropped)
7068  anum++; /* skip dropped column in tuple */
7069 
7070  if (anum < td_natts)
7071  {
7072  value = values[anum];
7073  isnull = nulls[anum];
7074  valtype = TupleDescAttr(tupdesc, anum)->atttypid;
7075  valtypmod = TupleDescAttr(tupdesc, anum)->atttypmod;
7076  anum++;
7077  }
7078  else
7079  {
7080  /* no source for destination column */
7081  value = (Datum) 0;
7082  isnull = true;
7083  valtype = UNKNOWNOID;
7084  valtypmod = -1;
7085 
7086  /* When source value is missing */
7087  if (strict_multiassignment_level)
7088  ereport(strict_multiassignment_level,
7089  (errcode(ERRCODE_DATATYPE_MISMATCH),
7090  errmsg("number of source and target fields in assignment does not match"),
7091  /* translator: %s represents a name of an extra check */
7092  errdetail("%s check of %s is active.",
7093  "strict_multi_assignment",
7094  strict_multiassignment_level == ERROR ? "extra_errors" :
7095  "extra_warnings"),
7096  errhint("Make sure the query returns the exact list of columns.")));
7097  }
7098 
7099  /* Cast the new value to the right type, if needed. */
7100  newvalues[fnum] = exec_cast_value(estate,
7101  value,
7102  &isnull,
7103  valtype,
7104  valtypmod,
7105  attr->atttypid,
7106  attr->atttypmod);
7107  newnulls[fnum] = isnull;
7108  }
7109 
7110  /*
7111  * When strict_multiassignment extra check is active, then ensure
7112  * there are no unassigned source attributes.
7113  */
7114  if (strict_multiassignment_level && anum < td_natts)
7115  {
7116  /* skip dropped columns in the source descriptor */
7117  while (anum < td_natts &&
7118  TupleDescAttr(tupdesc, anum)->attisdropped)
7119  anum++;
7120 
7121  if (anum < td_natts)
7122  ereport(strict_multiassignment_level,
7123  (errcode(ERRCODE_DATATYPE_MISMATCH),
7124  errmsg("number of source and target fields in assignment does not match"),
7125  /* translator: %s represents a name of an extra check */
7126  errdetail("%s check of %s is active.",
7127  "strict_multi_assignment",
7128  strict_multiassignment_level == ERROR ? "extra_errors" :
7129  "extra_warnings"),
7130  errhint("Make sure the query returns the exact list of columns.")));
7131  }
7132 
7133  values = newvalues;
7134  nulls = newnulls;
7135  }
7136 
7137  /* Insert the coerced field values into the new expanded record */
7138  expanded_record_set_fields(newerh, values, nulls, !estate->atomic);
7139 
7140  /* Complete the assignment */
7141  assign_record_var(estate, rec, newerh);
7142 
7143  return;
7144  }
7145 
7146  /* newerh should not have been passed in non-RECORD cases */
7147  Assert(newerh == NULL);
7148 
7149  /*
7150  * For a row, we assign the individual field values to the variables the
7151  * row points to.
7152  *
7153  * NOTE: both this code and the record code above silently ignore extra
7154  * columns in the source and assume NULL for missing columns. This is
7155  * pretty dubious but it's the historical behavior.
7156  *
7157  * If we have no input data at all, we'll assign NULL to all columns of
7158  * the row variable.
7159  */
7160  if (target->dtype == PLPGSQL_DTYPE_ROW)
7161  {
7162  PLpgSQL_row *row = (PLpgSQL_row *) target;
7163 
7164  anum = 0;
7165  for (fnum = 0; fnum < row->nfields; fnum++)
7166  {
7167  PLpgSQL_var *var;
7168  Datum value;
7169  bool isnull;
7170  Oid valtype;
7171  int32 valtypmod;
7172 
7173  var = (PLpgSQL_var *) (estate->datums[row->varnos[fnum]]);
7174 
7175  while (anum < td_natts &&
7176  TupleDescAttr(tupdesc, anum)->attisdropped)
7177  anum++; /* skip dropped column in tuple */
7178 
7179  if (anum < td_natts)
7180  {
7181  value = values[anum];
7182  isnull = nulls[anum];
7183  valtype = TupleDescAttr(tupdesc, anum)->atttypid;
7184  valtypmod = TupleDescAttr(tupdesc, anum)->atttypmod;
7185  anum++;
7186  }
7187  else
7188  {
7189  /* no source for destination column */
7190  value = (Datum) 0;
7191  isnull = true;
7192  valtype = UNKNOWNOID;
7193  valtypmod = -1;
7194 
7195  if (strict_multiassignment_level)
7196  ereport(strict_multiassignment_level,
7197  (errcode(ERRCODE_DATATYPE_MISMATCH),
7198  errmsg("number of source and target fields in assignment does not match"),
7199  /* translator: %s represents a name of an extra check */
7200  errdetail("%s check of %s is active.",
7201  "strict_multi_assignment",
7202  strict_multiassignment_level == ERROR ? "extra_errors" :
7203  "extra_warnings"),
7204  errhint("Make sure the query returns the exact list of columns.")));
7205  }
7206 
7207  exec_assign_value(estate, (PLpgSQL_datum *) var,
7208  value, isnull, valtype, valtypmod);
7209  }
7210 
7211  /*
7212  * When strict_multiassignment extra check is active, ensure there are
7213  * no unassigned source attributes.
7214  */
7215  if (strict_multiassignment_level && anum < td_natts)
7216  {
7217  while (anum < td_natts &&
7218  TupleDescAttr(tupdesc, anum)->attisdropped)
7219  anum++; /* skip dropped column in tuple */
7220 
7221  if (anum < td_natts)
7222  ereport(strict_multiassignment_level,
7223  (errcode(ERRCODE_DATATYPE_MISMATCH),
7224  errmsg("number of source and target fields in assignment does not match"),
7225  /* translator: %s represents a name of an extra check */
7226  errdetail("%s check of %s is active.",
7227  "strict_multi_assignment",
7228  strict_multiassignment_level == ERROR ? "extra_errors" :
7229  "extra_warnings"),
7230  errhint("Make sure the query returns the exact list of columns.")));
7231  }
7232 
7233  return;
7234  }
7235 
7236  elog(ERROR, "unsupported target type: %d", target->dtype);
7237 }
int errhint(const char *fmt,...)
Definition: elog.c:974
static void assign_record_var(PLpgSQL_execstate *estate, PLpgSQL_rec *rec, ExpandedRecordHeader *erh)
Definition: pl_exec.c:8394
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
#define PLPGSQL_XCHECK_STRICTMULTIASSIGNMENT
Definition: plpgsql.h:1197
static struct @144 value
int plpgsql_extra_errors
Definition: pl_handler.c:55
int errcode(int sqlerrcode)
Definition: elog.c:570
void expanded_record_set_fields(ExpandedRecordHeader *erh, const Datum *newValues, const bool *isnulls, bool expand_external)
#define lengthof(array)
Definition: c.h:662
unsigned int Oid
Definition: postgres_ext.h:31
signed int int32
Definition: c.h:346
PLpgSQL_datum ** datums
Definition: plpgsql.h:1071
static Datum exec_cast_value(PLpgSQL_execstate *estate, Datum value, bool *isnull, Oid valtype, int32 valtypmod, Oid reqtype, int32 reqtypmod)
Definition: pl_exec.c:7673
#define ERROR
Definition: elog.h:43
#define eval_mcontext_alloc(estate, sz)
Definition: pl_exec.c:123
int plpgsql_extra_warnings
Definition: pl_handler.c:54
int errdetail(const char *fmt,...)
Definition: elog.c:860
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:200
#define ereport(elevel, rest)
Definition: elog.h:141
static TupleDesc expanded_record_get_tupdesc(ExpandedRecordHeader *erh)
int * varnos
Definition: plpgsql.h:363
#define WARNING
Definition: elog.h:40
uintptr_t Datum
Definition: postgres.h:367
#define Assert(condition)
Definition: c.h:732
int nfields
Definition: plpgsql.h:361
PLpgSQL_datum_type dtype
Definition: plpgsql.h:269
static Datum values[MAXATTR]
Definition: bootstrap.c:167
int errmsg(const char *fmt,...)
Definition: elog.c:784
#define elog(elevel,...)
Definition: elog.h:226
static void exec_assign_value(PLpgSQL_execstate *estate, PLpgSQL_datum *target, Datum value, bool isNull, Oid valtype, int32 valtypmod)
Definition: pl_exec.c:4957

◆ exec_prepare_plan()

static void exec_prepare_plan ( PLpgSQL_execstate estate,
PLpgSQL_expr expr,
int  cursorOptions,
bool  keepplan 
)
static

Definition at line 4041 of file pl_exec.c.

References elog, ERROR, exec_simple_check_plan(), PLpgSQL_expr::func, PLpgSQL_execstate::func, plpgsql_parser_setup(), PLpgSQL_expr::query, SPI_keepplan(), SPI_prepare_params(), SPI_result, and SPI_result_code_string().

Referenced by exec_assign_expr(), exec_eval_expr(), exec_run_select(), exec_stmt_call(), exec_stmt_execsql(), exec_stmt_forc(), exec_stmt_open(), and exec_stmt_set().

4044 {
4045  SPIPlanPtr plan;
4046 
4047  /*
4048  * The grammar can't conveniently set expr->func while building the parse
4049  * tree, so make sure it's set before parser hooks need it.
4050  */
4051  expr->func = estate->func;
4052 
4053  /*
4054  * Generate and save the plan
4055  */
4056  plan = SPI_prepare_params(expr->query,
4058  (void *) expr,
4059  cursorOptions);
4060  if (plan == NULL)
4061  elog(ERROR, "SPI_prepare_params failed for \"%s\": %s",
4063  if (keepplan)
4064  SPI_keepplan(plan);
4065  expr->plan = plan;
4066 
4067  /* Check to see if it's a simple expression */
4068  exec_simple_check_plan(estate, expr);
4069 
4070  /*
4071  * Mark expression as not using a read-write param. exec_assign_value has
4072  * to take steps to override this if appropriate; that seems cleaner than
4073  * adding parameters to all other callers.
4074  */
4075  expr->rwparam = -1;
4076 }
char * query
Definition: plpgsql.h:221
PLpgSQL_function * func
Definition: plpgsql.h:1036
static void exec_simple_check_plan(PLpgSQL_execstate *estate, PLpgSQL_expr *expr)
Definition: pl_exec.c:7885
SPIPlanPtr plan
Definition: plpgsql.h:222
int SPI_result
Definition: spi.c:47
#define ERROR
Definition: elog.h:43
const char * SPI_result_code_string(int code)
Definition: spi.c:1705
void(* ParserSetupHook)(struct ParseState *pstate, void *arg)
Definition: params.h:108
void plpgsql_parser_setup(struct ParseState *pstate, PLpgSQL_expr *expr)
Definition: pl_comp.c:1074
int SPI_keepplan(SPIPlanPtr plan)
Definition: spi.c:752
int rwparam
Definition: plpgsql.h:224
struct PLpgSQL_function * func
Definition: plpgsql.h:227
#define elog(elevel,...)
Definition: elog.h:226
SPIPlanPtr SPI_prepare_params(const char *src, ParserSetupHook parserSetup, void *parserSetupArg, int cursorOptions)
Definition: spi.c:715

◆ exec_run_select()

static int exec_run_select ( PLpgSQL_execstate estate,
PLpgSQL_expr expr,
long  maxtuples,
Portal portalP 
)
static

Definition at line 5836 of file pl_exec.c.

References Assert, CURSOR_OPT_PARALLEL_OK, elog, ereport, errcode(), errmsg(), ERROR, PLpgSQL_execstate::eval_processed, PLpgSQL_execstate::eval_tuptable, exec_eval_cleanup(), exec_prepare_plan(), PLpgSQL_expr::plan, PLpgSQL_expr::query, PLpgSQL_execstate::readonly_func, setup_param_list(), SPI_cursor_open_with_paramlist(), SPI_execute_plan_with_paramlist(), SPI_OK_CURSOR, SPI_OK_SELECT, SPI_processed, SPI_result, SPI_result_code_string(), and SPI_tuptable.

Referenced by exec_eval_expr(), exec_stmt_fors(), exec_stmt_perform(), and exec_stmt_return_query().

5838 {
5839  ParamListInfo paramLI;
5840  int rc;
5841 
5842  /*
5843  * On the first call for this expression generate the plan.
5844  *
5845  * If we don't need to return a portal, then we're just going to execute
5846  * the query once, which means it's OK to use a parallel plan, even if the
5847  * number of rows being fetched is limited. If we do need to return a
5848  * portal, the caller might do cursor operations, which parallel query
5849  * can't support.
5850  */
5851  if (expr->plan == NULL)
5852  exec_prepare_plan(estate, expr,
5853  portalP == NULL ? CURSOR_OPT_PARALLEL_OK : 0, true);
5854 
5855  /*
5856  * Set up ParamListInfo to pass to executor
5857  */
5858  paramLI = setup_param_list(estate, expr);
5859 
5860  /*
5861  * If a portal was requested, put the query and paramlist into the portal
5862  */
5863  if (portalP != NULL)
5864  {
5865  *portalP = SPI_cursor_open_with_paramlist(NULL, expr->plan,
5866  paramLI,
5867  estate->readonly_func);
5868  if (*portalP == NULL)
5869  elog(ERROR, "could not open implicit cursor for query \"%s\": %s",
5871  exec_eval_cleanup(estate);
5872  return SPI_OK_CURSOR;
5873  }
5874 
5875  /*
5876  * Execute the query
5877  */
5878  rc = SPI_execute_plan_with_paramlist(expr->plan, paramLI,
5879  estate->readonly_func, maxtuples);
5880  if (rc != SPI_OK_SELECT)
5881  ereport(ERROR,
5882  (errcode(ERRCODE_SYNTAX_ERROR),
5883  errmsg("query \"%s\" is not a SELECT", expr->query)));
5884 
5885  /* Save query results for eventual cleanup */
5886  Assert(estate->eval_tuptable == NULL);
5887  estate->eval_tuptable = SPI_tuptable;
5888  estate->eval_processed = SPI_processed;
5889 
5890  return rc;
5891 }
char * query
Definition: plpgsql.h:221
static void exec_prepare_plan(PLpgSQL_execstate *estate, PLpgSQL_expr *expr, int cursorOptions, bool keepplan)
Definition: pl_exec.c:4041
SPITupleTable * eval_tuptable
Definition: plpgsql.h:1095
uint64 eval_processed
Definition: plpgsql.h:1096
Portal SPI_cursor_open_with_paramlist(const char *name, SPIPlanPtr plan, ParamListInfo params, bool read_only)
Definition: spi.c:1300
SPITupleTable * SPI_tuptable
Definition: spi.c:46
int errcode(int sqlerrcode)
Definition: elog.c:570
static void exec_eval_cleanup(PLpgSQL_execstate *estate)
Definition: pl_exec.c:4020
#define SPI_OK_CURSOR
Definition: spi.h:62
uint64 SPI_processed
Definition: spi.c:45
SPIPlanPtr plan
Definition: plpgsql.h:222
int SPI_result
Definition: spi.c:47
#define ERROR
Definition: elog.h:43
int SPI_execute_plan_with_paramlist(SPIPlanPtr plan, ParamListInfo params, bool read_only, long tcount)
Definition: spi.c:565
const char * SPI_result_code_string(int code)
Definition: spi.c:1705
static ParamListInfo setup_param_list(PLpgSQL_execstate *estate, PLpgSQL_expr *expr)
Definition: pl_exec.c:6218
#define ereport(elevel, rest)
Definition: elog.h:141
#define SPI_OK_SELECT
Definition: spi.h:57
#define Assert(condition)
Definition: c.h:732
#define CURSOR_OPT_PARALLEL_OK
Definition: parsenodes.h:2692
int errmsg(const char *fmt,...)
Definition: elog.c:784
#define elog(elevel,...)
Definition: elog.h:226

◆ exec_save_simple_expr()

static void exec_save_simple_expr ( PLpgSQL_expr expr,
CachedPlan cplan 
)
static

Definition at line 7984 of file pl_exec.c.

References Assert, castNode, CMD_SELECT, PlannedStmt::commandType, elog, ERROR, PLpgSQL_expr::expr_simple_expr, PLpgSQL_expr::expr_simple_generation, PLpgSQL_expr::expr_simple_in_use, PLpgSQL_expr::expr_simple_lxid, PLpgSQL_expr::expr_simple_state, PLpgSQL_expr::expr_simple_type, PLpgSQL_expr::expr_simple_typmod, exprType(), exprTypmod(), CachedPlan::generation, Plan::initPlan, InvalidLocalTransactionId, IsA, Plan::lefttree, linitial, linitial_node, list_length(), nodeTag, OUTER_VAR, PlannedStmt::planTree, Plan::qual, Plan::righttree, CachedPlan::stmt_list, and Plan::targetlist.

Referenced by exec_eval_simple_expr(), and exec_simple_check_plan().

7985 {
7986  PlannedStmt *stmt;
7987  Plan *plan;
7988  Expr *tle_expr;
7989 
7990  /*
7991  * Given the checks that exec_simple_check_plan did, none of the Asserts
7992  * here should ever fail.
7993  */
7994 
7995  /* Extract the single PlannedStmt */
7996  Assert(list_length(cplan->stmt_list) == 1);
7997  stmt = linitial_node(PlannedStmt, cplan->stmt_list);
7998  Assert(stmt->commandType == CMD_SELECT);
7999 
8000  /*
8001  * Ordinarily, the plan node should be a simple Result. However, if
8002  * force_parallel_mode is on, the planner might've stuck a Gather node
8003  * atop that. The simplest way to deal with this is to look through the
8004  * Gather node. The Gather node's tlist would normally contain a Var
8005  * referencing the child node's output, but it could also be a Param, or
8006  * it could be a Const that setrefs.c copied as-is.
8007  */
8008  plan = stmt->planTree;
8009  for (;;)
8010  {
8011  /* Extract the single tlist expression */
8012  Assert(list_length(plan->targetlist) == 1);
8013  tle_expr = castNode(TargetEntry, linitial(plan->targetlist))->expr;
8014 
8015  if (IsA(plan, Result))
8016  {
8017  Assert(plan->lefttree == NULL &&
8018  plan->righttree == NULL &&
8019  plan->initPlan == NULL &&
8020  plan->qual == NULL &&
8021  ((Result *) plan)->resconstantqual == NULL);
8022  break;
8023  }
8024  else if (IsA(plan, Gather))
8025  {
8026  Assert(plan->lefttree != NULL &&
8027  plan->righttree == NULL &&
8028  plan->initPlan == NULL &&
8029  plan->qual == NULL);
8030  /* If setrefs.c copied up a Const, no need to look further */
8031  if (IsA(tle_expr, Const))
8032  break;
8033  /* Otherwise, it had better be a Param or an outer Var */
8034  Assert(IsA(tle_expr, Param) ||(IsA(tle_expr, Var) &&
8035  ((Var *) tle_expr)->varno == OUTER_VAR));
8036  /* Descend to the child node */
8037  plan = plan->lefttree;
8038  }
8039  else
8040  elog(ERROR, "unexpected plan node type: %d",
8041  (int) nodeTag(plan));
8042  }
8043 
8044  /*
8045  * Save the simple expression, and initialize state to "not valid in
8046  * current transaction".
8047  */
8048  expr->expr_simple_expr = tle_expr;
8049  expr->expr_simple_generation = cplan->generation;
8050  expr->expr_simple_state = NULL;
8051  expr->expr_simple_in_use = false;
8053  /* Also stash away the expression result type */
8054  expr->expr_simple_type = exprType((Node *) tle_expr);
8055  expr->expr_simple_typmod = exprTypmod((Node *) tle_expr);
8056 }
int expr_simple_generation
Definition: plpgsql.h:234
List * qual
Definition: plannodes.h:141
#define IsA(nodeptr, _type_)
Definition: nodes.h:575
#define castNode(_type_, nodeptr)
Definition: nodes.h:593
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:276
Definition: nodes.h:524
Definition: primnodes.h:167
#define linitial_node(type, l)
Definition: pg_list.h:198
struct Plan * planTree
Definition: plannodes.h:64
struct Plan * righttree
Definition: plannodes.h:143
#define linitial(l)
Definition: pg_list.h:195
#define ERROR
Definition: elog.h:43
Expr * expr_simple_expr
Definition: plpgsql.h:233
ExprState * expr_simple_state
Definition: plpgsql.h:244
CmdType commandType
Definition: plannodes.h:46
LocalTransactionId expr_simple_lxid
Definition: plpgsql.h:246
#define Assert(condition)
Definition: c.h:732
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
int generation
Definition: plancache.h:154
static int list_length(const List *l)
Definition: pg_list.h:169
struct Plan * lefttree
Definition: plannodes.h:142
#define nodeTag(nodeptr)
Definition: nodes.h:529
List * targetlist
Definition: plannodes.h:140
int32 expr_simple_typmod
Definition: plpgsql.h:236
List * initPlan
Definition: plannodes.h:144
#define elog(elevel,...)
Definition: elog.h:226
#define InvalidLocalTransactionId
Definition: lock.h:69
List * stmt_list
Definition: plancache.h:146
bool expr_simple_in_use
Definition: plpgsql.h:245
#define OUTER_VAR
Definition: primnodes.h:158
Oid expr_simple_type
Definition: plpgsql.h:235

◆ exec_set_found()

static void exec_set_found ( PLpgSQL_execstate estate,
bool  state 
)
static

Definition at line 8170 of file pl_exec.c.

References assign_simple_var(), BoolGetDatum, PLpgSQL_execstate::datums, and PLpgSQL_execstate::found_varno.

Referenced by exec_for_query(), exec_stmt_execsql(), exec_stmt_fetch(), exec_stmt_foreach_a(), exec_stmt_fori(), exec_stmt_perform(), exec_stmt_return_query(), plpgsql_exec_function(), and plpgsql_exec_trigger().

8171 {
8172  PLpgSQL_var *var;
8173 
8174  var = (PLpgSQL_var *) (estate->datums[estate->found_varno]);
8175  assign_simple_var(estate, var, BoolGetDatum(state), false, false);
8176 }
static void assign_simple_var(PLpgSQL_execstate *estate, PLpgSQL_var *var, Datum newvalue, bool isnull, bool freeable)
Definition: pl_exec.c:8318
PLpgSQL_datum ** datums
Definition: plpgsql.h:1071
#define BoolGetDatum(X)
Definition: postgres.h:402
Definition: regguts.h:298

◆ exec_simple_check_plan()

static void exec_simple_check_plan ( PLpgSQL_execstate estate,
PLpgSQL_expr expr 
)
static

Definition at line 7885 of file pl_exec.c.

References Assert, CMD_SELECT, Query::commandType, Query::cteList, Query::distinctClause, exec_save_simple_expr(), PLpgSQL_expr::expr_simple_expr, FromExpr::fromlist, get_eval_mcontext, Query::groupClause, Query::groupingSets, Query::hasAggs, Query::hasSubLinks, Query::hasTargetSRFs, Query::hasWindowFuncs, Query::havingQual, IsA, Query::jointree, Query::limitCount, Query::limitOffset, linitial, list_length(), MemoryContextSwitchTo(), NIL, PLpgSQL_expr::plan, FromExpr::quals, CachedPlanSource::query_list, ReleaseCachedPlan(), Query::rtable, Query::setOperations, Query::sortClause, SPI_plan_get_cached_plan(), SPI_plan_get_plan_sources(), Query::targetList, and Query::windowClause.

Referenced by exec_prepare_plan().

7886 {
7887  List *plansources;
7888  CachedPlanSource *plansource;
7889  Query *query;
7890  CachedPlan *cplan;
7891  MemoryContext oldcontext;
7892 
7893  /*
7894  * Initialize to "not simple".
7895  */
7896  expr->expr_simple_expr = NULL;
7897 
7898  /*
7899  * Check the analyzed-and-rewritten form of the query to see if we will be
7900  * able to treat it as a simple expression. Since this function is only
7901  * called immediately after creating the CachedPlanSource, we need not
7902  * worry about the query being stale.
7903  */
7904 
7905  /*
7906  * We can only test queries that resulted in exactly one CachedPlanSource
7907  */
7908  plansources = SPI_plan_get_plan_sources(expr->plan);
7909  if (list_length(plansources) != 1)
7910  return;
7911  plansource = (CachedPlanSource *) linitial(plansources);
7912 
7913  /*
7914  * 1. There must be one single querytree.
7915  */
7916  if (list_length(plansource->query_list) != 1)
7917  return;
7918  query = (Query *) linitial(plansource->query_list);
7919 
7920  /*
7921  * 2. It must be a plain SELECT query without any input tables
7922  */
7923  if (!IsA(query, Query))
7924  return;
7925  if (query->commandType != CMD_SELECT)
7926  return;
7927  if (query->rtable != NIL)
7928  return;
7929 
7930  /*
7931  * 3. Can't have any subplans, aggregates, qual clauses either. (These
7932  * tests should generally match what inline_function() checks before
7933  * inlining a SQL function; otherwise, inlining could change our
7934  * conclusion about whether an expression is simple, which we don't want.)
7935  */
7936  if (query->hasAggs ||
7937  query->hasWindowFuncs ||
7938  query->hasTargetSRFs ||
7939  query->hasSubLinks ||
7940  query->cteList ||
7941  query->jointree->fromlist ||
7942  query->jointree->quals ||
7943  query->groupClause ||
7944  query->groupingSets ||
7945  query->havingQual ||
7946  query->windowClause ||
7947  query->distinctClause ||
7948  query->sortClause ||
7949  query->limitOffset ||
7950  query->limitCount ||
7951  query->setOperations)
7952  return;
7953 
7954  /*
7955  * 4. The query must have a single attribute as result
7956  */
7957  if (list_length(query->targetList) != 1)
7958  return;
7959 
7960  /*
7961  * OK, we can treat it as a simple plan.
7962  *
7963  * Get the generic plan for the query. If replanning is needed, do that
7964  * work in the eval_mcontext.
7965  */
7966  oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
7967  cplan = SPI_plan_get_cached_plan(expr->plan);
7968  MemoryContextSwitchTo(oldcontext);
7969 
7970  /* Can't fail, because we checked for a single CachedPlanSource above */
7971  Assert(cplan != NULL);
7972 
7973  /* Share the remaining work with replan code path */
7974  exec_save_simple_expr(expr, cplan);
7975 
7976  /* Release our plan refcount */
7977  ReleaseCachedPlan(cplan, true);
7978 }
Node * limitOffset
Definition: parsenodes.h:160
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:575
List * sortClause
Definition: parsenodes.h:158
FromExpr * jointree
Definition: parsenodes.h:138
bool hasAggs
Definition: parsenodes.h:125
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
List * groupingSets
Definition: parsenodes.h:150
List * fromlist
Definition: primnodes.h:1496
Node * quals
Definition: primnodes.h:1497
static void exec_save_simple_expr(PLpgSQL_expr *expr, CachedPlan *cplan)
Definition: pl_exec.c:7984
SPIPlanPtr plan
Definition: plpgsql.h:222
List * windowClause
Definition: parsenodes.h:154
List * targetList
Definition: parsenodes.h:140
CachedPlan * SPI_plan_get_cached_plan(SPIPlanPtr plan)
Definition: spi.c:1798
#define linitial(l)
Definition: pg_list.h:195
List * rtable
Definition: parsenodes.h:137
List * distinctClause
Definition: parsenodes.h:156
Node * limitCount
Definition: parsenodes.h:161
void ReleaseCachedPlan(CachedPlan *plan, bool useResOwner)
Definition: plancache.c:1259
Expr * expr_simple_expr
Definition: plpgsql.h:233
#define get_eval_mcontext(estate)
Definition: pl_exec.c:121
CmdType commandType
Definition: parsenodes.h:112
bool hasTargetSRFs
Definition: parsenodes.h:127
#define Assert(condition)
Definition: c.h:732
bool hasWindowFuncs
Definition: parsenodes.h:126
static int list_length(const List *l)
Definition: pg_list.h:169
List * cteList
Definition: parsenodes.h:135
Node * setOperations
Definition: parsenodes.h:165
List * groupClause
Definition: parsenodes.h:148
bool hasSubLinks
Definition: parsenodes.h:128
List * SPI_plan_get_plan_sources(SPIPlanPtr plan)
Definition: spi.c:1782
List * query_list
Definition: plancache.h:108
Node * havingQual
Definition: parsenodes.h:152
Definition: pg_list.h:50

◆ exec_stmt()

static int exec_stmt ( PLpgSQL_execstate estate,
PLpgSQL_stmt stmt 
)
static

Definition at line 1940 of file pl_exec.c.

References CHECK_FOR_INTERRUPTS, PLpgSQL_stmt::cmd_type, PLpgSQL_stmt_set::cmd_type, elog, PLpgSQL_execstate::err_stmt, ERROR, exec_stmt_assert(), exec_stmt_assign(), exec_stmt_block(), exec_stmt_call(), exec_stmt_case(), exec_stmt_close(), exec_stmt_commit(), exec_stmt_dynexecute(), exec_stmt_dynfors(), exec_stmt_execsql(), exec_stmt_exit(), exec_stmt_fetch(), exec_stmt_forc(), exec_stmt_foreach_a(), exec_stmt_fori(), exec_stmt_fors(), exec_stmt_getdiag(), exec_stmt_if(), exec_stmt_loop(), exec_stmt_open(), exec_stmt_perform(), exec_stmt_raise(), exec_stmt_return(), exec_stmt_return_next(), exec_stmt_return_query(), exec_stmt_rollback(), exec_stmt_set(), exec_stmt_while(), plpgsql_plugin_ptr, PLPGSQL_STMT_ASSERT, PLPGSQL_STMT_ASSIGN, PLPGSQL_STMT_BLOCK, PLPGSQL_STMT_CALL, PLPGSQL_STMT_CASE, PLPGSQL_STMT_CLOSE, PLPGSQL_STMT_COMMIT, PLPGSQL_STMT_DYNEXECUTE, PLPGSQL_STMT_DYNFORS, PLPGSQL_STMT_EXECSQL, PLPGSQL_STMT_EXIT, PLPGSQL_STMT_FETCH, PLPGSQL_STMT_FORC, PLPGSQL_STMT_FOREACH_A, PLPGSQL_STMT_FORI, PLPGSQL_STMT_FORS, PLPGSQL_STMT_GETDIAG, PLPGSQL_STMT_IF, PLPGSQL_STMT_LOOP, PLPGSQL_STMT_OPEN, PLPGSQL_STMT_PERFORM, PLPGSQL_STMT_RAISE, PLPGSQL_STMT_RETURN, PLPGSQL_STMT_RETURN_NEXT, PLPGSQL_STMT_RETURN_QUERY, PLPGSQL_STMT_ROLLBACK, PLPGSQL_STMT_SET, PLPGSQL_STMT_WHILE, PLpgSQL_plugin::stmt_beg, and PLpgSQL_plugin::stmt_end.

Referenced by exec_stmts(), plpgsql_exec_event_trigger(), plpgsql_exec_function(), and plpgsql_exec_trigger().

1941 {
1942  PLpgSQL_stmt *save_estmt;
1943  int rc = -1;
1944 
1945  save_estmt = estate->err_stmt;
1946  estate->err_stmt = stmt;
1947 
1948  /* Let the plugin know that we are about to execute this statement */
1949  if (*plpgsql_plugin_ptr && (*plpgsql_plugin_ptr)->stmt_beg)
1950  ((*plpgsql_plugin_ptr)->stmt_beg) (estate, stmt);
1951 
1953 
1954  switch (stmt->cmd_type)
1955  {
1956  case PLPGSQL_STMT_BLOCK:
1957  rc = exec_stmt_block(estate, (PLpgSQL_stmt_block *) stmt);
1958  break;
1959 
1960  case PLPGSQL_STMT_ASSIGN:
1961  rc = exec_stmt_assign(estate, (PLpgSQL_stmt_assign *) stmt);
1962  break;
1963 
1964  case PLPGSQL_STMT_PERFORM:
1965  rc = exec_stmt_perform(estate, (PLpgSQL_stmt_perform *) stmt);
1966  break;
1967 
1968  case PLPGSQL_STMT_CALL:
1969  rc = exec_stmt_call(estate, (PLpgSQL_stmt_call *) stmt);
1970  break;
1971 
1972  case PLPGSQL_STMT_GETDIAG:
1973  rc = exec_stmt_getdiag(estate, (PLpgSQL_stmt_getdiag *) stmt);
1974  break;
1975 
1976  case PLPGSQL_STMT_IF:
1977  rc = exec_stmt_if(estate, (PLpgSQL_stmt_if *) stmt);
1978  break;
1979 
1980  case PLPGSQL_STMT_CASE:
1981  rc = exec_stmt_case(estate, (PLpgSQL_stmt_case *) stmt);
1982  break;
1983 
1984  case PLPGSQL_STMT_LOOP:
1985  rc = exec_stmt_loop(estate, (PLpgSQL_stmt_loop *) stmt);
1986  break;
1987 
1988  case PLPGSQL_STMT_WHILE:
1989  rc = exec_stmt_while(estate, (PLpgSQL_stmt_while *) stmt);
1990  break;
1991 
1992  case PLPGSQL_STMT_FORI:
1993  rc = exec_stmt_fori(estate, (PLpgSQL_stmt_fori *) stmt);
1994  break;
1995 
1996  case PLPGSQL_STMT_FORS:
1997  rc = exec_stmt_fors(estate, (PLpgSQL_stmt_fors *) stmt);
1998  break;
1999 
2000  case PLPGSQL_STMT_FORC:
2001  rc = exec_stmt_forc(estate, (PLpgSQL_stmt_forc *) stmt);
2002  break;
2003 
2005  rc = exec_stmt_foreach_a(estate, (PLpgSQL_stmt_foreach_a *) stmt);
2006  break;
2007 
2008  case PLPGSQL_STMT_EXIT:
2009  rc = exec_stmt_exit(estate, (PLpgSQL_stmt_exit *) stmt);
2010  break;
2011 
2012  case PLPGSQL_STMT_RETURN:
2013  rc = exec_stmt_return(estate, (PLpgSQL_stmt_return *) stmt);
2014  break;
2015 
2017  rc = exec_stmt_return_next(estate, (PLpgSQL_stmt_return_next *) stmt);
2018  break;
2019 
2021  rc = exec_stmt_return_query(estate, (PLpgSQL_stmt_return_query *) stmt);
2022  break;
2023 
2024  case PLPGSQL_STMT_RAISE:
2025  rc = exec_stmt_raise(estate, (PLpgSQL_stmt_raise *) stmt);
2026  break;
2027 
2028  case PLPGSQL_STMT_ASSERT:
2029  rc = exec_stmt_assert(estate, (PLpgSQL_stmt_assert *) stmt);
2030  break;
2031 
2032  case PLPGSQL_STMT_EXECSQL:
2033  rc = exec_stmt_execsql(estate, (PLpgSQL_stmt_execsql *) stmt);
2034  break;
2035 
2037  rc = exec_stmt_dynexecute(estate, (PLpgSQL_stmt_dynexecute *) stmt);
2038  break;
2039 
2040  case PLPGSQL_STMT_DYNFORS:
2041  rc = exec_stmt_dynfors(estate, (PLpgSQL_stmt_dynfors *) stmt);
2042  break;
2043 
2044  case PLPGSQL_STMT_OPEN:
2045  rc = exec_stmt_open(estate, (PLpgSQL_stmt_open *) stmt);
2046  break;
2047 
2048  case PLPGSQL_STMT_FETCH:
2049  rc = exec_stmt_fetch(estate, (PLpgSQL_stmt_fetch *) stmt);
2050  break;
2051 
2052  case PLPGSQL_STMT_CLOSE:
2053  rc = exec_stmt_close(estate, (PLpgSQL_stmt_close *) stmt);
2054  break;
2055 
2056  case PLPGSQL_STMT_COMMIT:
2057  rc = exec_stmt_commit(estate, (PLpgSQL_stmt_commit *) stmt);
2058  break;
2059 
2060  case PLPGSQL_STMT_ROLLBACK:
2061  rc = exec_stmt_rollback(estate, (PLpgSQL_stmt_rollback *) stmt);
2062  break;
2063 
2064  case PLPGSQL_STMT_SET:
2065  rc = exec_stmt_set(estate, (PLpgSQL_stmt_set *) stmt);
2066  break;
2067 
2068  default:
2069  estate->err_stmt = save_estmt;
2070  elog(ERROR, "unrecognized cmd_type: %d", stmt->cmd_type);
2071  }
2072 
2073  /* Let the plugin know that we have finished executing this statement */
2074  if (*plpgsql_plugin_ptr && (*plpgsql_plugin_ptr)->stmt_end)
2075  ((*plpgsql_plugin_ptr)->stmt_end) (estate, stmt);
2076 
2077  estate->err_stmt = save_estmt;
2078 
2079  return rc;
2080 }
static int exec_stmt_set(PLpgSQL_execstate *estate, PLpgSQL_stmt_set *stmt)
Definition: pl_exec.c:4867
static int exec_stmt_execsql(PLpgSQL_execstate *estate, PLpgSQL_stmt_execsql *stmt)
Definition: pl_exec.c:4087
static int exec_stmt_case(PLpgSQL_execstate *estate, PLpgSQL_stmt_case *stmt)
Definition: pl_exec.c:2495
PLpgSQL_stmt * err_stmt
Definition: plpgsql.h:1100
static int exec_stmt_call(PLpgSQL_execstate *estate, PLpgSQL_stmt_call *stmt)
Definition: pl_exec.c:2120
static int exec_stmt_return_query(PLpgSQL_execstate *estate, PLpgSQL_stmt_return_query *stmt)
Definition: pl_exec.c:3493
static int exec_stmt_foreach_a(PLpgSQL_execstate *estate, PLpgSQL_stmt_foreach_a *stmt)
Definition: pl_exec.c:2943
static int exec_stmt_open(PLpgSQL_execstate *estate, PLpgSQL_stmt_open *stmt)
Definition: pl_exec.c:4530
static int exec_stmt_dynfors(PLpgSQL_execstate *estate, PLpgSQL_stmt_dynfors *stmt)
Definition: pl_exec.c:4503
static int exec_stmt_loop(PLpgSQL_execstate *estate, PLpgSQL_stmt_loop *stmt)
Definition: pl_exec.c:2582
static int exec_stmt_fors(PLpgSQL_execstate *estate, PLpgSQL_stmt_fors *stmt)
Definition: pl_exec.c:2778
static int exec_stmt_assign(PLpgSQL_execstate *estate, PLpgSQL_stmt_assign *stmt)
Definition: pl_exec.c:2089
#define ERROR
Definition: elog.h:43
static int exec_stmt_rollback(PLpgSQL_execstate *estate, PLpgSQL_stmt_rollback *stmt)
Definition: pl_exec.c:4842
static int exec_stmt_assert(PLpgSQL_execstate *estate, PLpgSQL_stmt_assert *stmt)
Definition: pl_exec.c:3833
static int exec_stmt_raise(PLpgSQL_execstate *estate, PLpgSQL_stmt_raise *stmt)
Definition: pl_exec.c:3622
static int exec_stmt_fori(PLpgSQL_execstate *estate, PLpgSQL_stmt_fori *stmt)
Definition: pl_exec.c:2635
static int exec_stmt_dynexecute(PLpgSQL_execstate *estate, PLpgSQL_stmt_dynexecute *stmt)
Definition: pl_exec.c:4313
PLpgSQL_plugin ** plpgsql_plugin_ptr
Definition: pl_handler.c:58
static int exec_stmt_getdiag(PLpgSQL_execstate *estate, PLpgSQL_stmt_getdiag *stmt)
Definition: pl_exec.c:2355
static int exec_stmt_exit(PLpgSQL_execstate *estate, PLpgSQL_stmt_exit *stmt)
Definition: pl_exec.c:3099
static int exec_stmt_return(PLpgSQL_execstate *estate, PLpgSQL_stmt_return *stmt)
Definition: pl_exec.c:3132
static int exec_stmt_while(PLpgSQL_execstate *estate, PLpgSQL_stmt_while *stmt)
Definition: pl_exec.c:2604
static int exec_stmt_commit(PLpgSQL_execstate *estate, PLpgSQL_stmt_commit *stmt)
Definition: pl_exec.c:4820
static int exec_stmt_fetch(PLpgSQL_execstate *estate, PLpgSQL_stmt_fetch *stmt)
Definition: pl_exec.c:4686
static int exec_stmt_block(PLpgSQL_execstate *estate, PLpgSQL_stmt_block *block)
Definition: pl_exec.c:1580
static int exec_stmt_return_next(PLpgSQL_execstate *estate, PLpgSQL_stmt_return_next *stmt)
Definition: pl_exec.c:3275
static int exec_stmt_close(PLpgSQL_execstate *estate, PLpgSQL_stmt_close *stmt)
Definition: pl_exec.c:4777
#define elog(elevel,...)
Definition: elog.h:226
static int exec_stmt_if(PLpgSQL_execstate *estate, PLpgSQL_stmt_if *stmt)
Definition: pl_exec.c:2465
static int exec_stmt_perform(PLpgSQL_execstate *estate, PLpgSQL_stmt_perform *stmt)
Definition: pl_exec.c:2105
PLpgSQL_stmt_type cmd_type
Definition: plpgsql.h:459
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
void(* stmt_end)(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
Definition: plpgsql.h:1143
void(* stmt_beg)(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
Definition: plpgsql.h:1142
static int exec_stmt_forc(PLpgSQL_execstate *estate, PLpgSQL_stmt_forc *stmt)
Definition: pl_exec.c:2807

◆ exec_stmt_assert()

static int exec_stmt_assert ( PLpgSQL_execstate estate,
PLpgSQL_stmt_assert stmt 
)
static

Definition at line 3833 of file pl_exec.c.

References PLpgSQL_stmt_assert::cond, convert_value_to_string(), ereport, errcode(), errmsg(), errmsg_internal(), ERROR, exec_eval_boolean(), exec_eval_cleanup(), exec_eval_expr(), PLpgSQL_stmt_assert::message, plpgsql_check_asserts, PLPGSQL_RC_OK, val, and value.

Referenced by exec_stmt().

3834 {
3835  bool value;
3836  bool isnull;
3837 
3838  /* do nothing when asserts are not enabled */
3839  if (!plpgsql_check_asserts)
3840  return PLPGSQL_RC_OK;
3841 
3842  value = exec_eval_boolean(estate, stmt->cond, &isnull);
3843  exec_eval_cleanup(estate);
3844 
3845  if (isnull || !value)
3846  {
3847  char *message = NULL;
3848 
3849  if (stmt->message != NULL)
3850  {
3851  Datum val;
3852  Oid typeid;
3853  int32 typmod;
3854 
3855  val = exec_eval_expr(estate, stmt->message,
3856  &isnull, &typeid, &typmod);
3857  if (!isnull)
3858  message = convert_value_to_string(estate, val, typeid);
3859  /* we mustn't do exec_eval_cleanup here */
3860  }
3861 
3862  ereport(ERROR,
3863  (errcode(ERRCODE_ASSERT_FAILURE),
3864  message ? errmsg_internal("%s", message) :
3865  errmsg("assertion failed")));
3866  }
3867 
3868  return PLPGSQL_RC_OK;
3869 }
static struct @144 value
int errcode(int sqlerrcode)
Definition: elog.c:570
static void exec_eval_cleanup(PLpgSQL_execstate *estate)
Definition: pl_exec.c:4020
unsigned int Oid
Definition: postgres_ext.h:31
signed int int32
Definition: c.h:346
#define ERROR
Definition: elog.h:43
static Datum exec_eval_expr(PLpgSQL_execstate *estate, PLpgSQL_expr *expr, bool *isNull, Oid *rettype, int32 *rettypmod)
Definition: pl_exec.c:5753
PLpgSQL_expr * message
Definition: plpgsql.h:900
static bool exec_eval_boolean(PLpgSQL_execstate *estate, PLpgSQL_expr *expr, bool *isNull)
Definition: pl_exec.c:5730
#define ereport(elevel, rest)
Definition: elog.h:141
uintptr_t Datum
Definition: postgres.h:367
int errmsg_internal(const char *fmt,...)
Definition: elog.c:814
int errmsg(const char *fmt,...)
Definition: elog.c:784
static char * convert_value_to_string(PLpgSQL_execstate *estate, Datum value, Oid valtype)
Definition: pl_exec.c:7644
PLpgSQL_expr * cond
Definition: plpgsql.h:899
bool plpgsql_check_asserts
Definition: pl_handler.c:50
long val
Definition: informix.c:684

◆ exec_stmt_assign()

static int exec_stmt_assign ( PLpgSQL_execstate estate,
PLpgSQL_stmt_assign stmt 
)
static

Definition at line 2089 of file pl_exec.c.

References Assert, PLpgSQL_execstate::datums, exec_assign_expr(), PLpgSQL_stmt_assign::expr, PLPGSQL_RC_OK, and PLpgSQL_stmt_assign::varno.

Referenced by exec_stmt().

2090 {
2091  Assert(stmt->varno >= 0);
2092 
2093  exec_assign_expr(estate, estate->datums[stmt->varno], stmt->expr);
2094 
2095  return PLPGSQL_RC_OK;
2096 }
PLpgSQL_datum ** datums
Definition: plpgsql.h:1071
static void exec_assign_expr(PLpgSQL_execstate *estate, PLpgSQL_datum *target, PLpgSQL_expr *expr)
Definition: pl_exec.c:4892
#define Assert(condition)
Definition: c.h:732
PLpgSQL_expr * expr
Definition: plpgsql.h:524

◆ exec_stmt_block()

static int exec_stmt_block ( PLpgSQL_execstate estate,
PLpgSQL_stmt_block block 
)
static

Definition at line 1580 of file pl_exec.c.

References PLpgSQL_exception::action, Assert, assign_simple_var(), assign_text_var(), BeginInternalSubTransaction(), PLpgSQL_stmt_block::body, PLpgSQL_exception::conditions, CopyErrorData(), PLpgSQL_execstate::cur_error, CurrentMemoryContext, CurrentResourceOwner, PLpgSQL_var::datatype, PLpgSQL_execstate::datums, datumTransfer(), PLpgSQL_var::default_val, PLpgSQL_rec::default_val, PLpgSQL_datum::dtype, elog, PLpgSQL_execstate::err_text, ERROR, PLpgSQL_execstate::eval_econtext, PLpgSQL_execstate::eval_tuptable, PLpgSQL_exception_block::exc_list, exception_matches_conditions(), PLpgSQL_stmt_block::exceptions, exec_assign_expr(), exec_assign_value(), exec_eval_cleanup(), exec_move_row(), exec_stmts(), PLpgSQL_execstate::exitlabel, FlushErrorState(), get_stmt_mcontext(), get_typlenbyval(), gettext_noop, i, PLpgSQL_stmt_block::initvarnos, PLpgSQL_stmt_block::label, lfirst, MemoryContextDeleteChildren(), MemoryContextReset(), MemoryContextSwitchTo(), ErrorData::message, PLpgSQL_stmt_block::n_initvars, PLpgSQL_variable::notnull, PG_CATCH, PG_END_TRY, PG_TRY, plpgsql_create_econtext(), PLPGSQL_DTYPE_REC, PLPGSQL_DTYPE_VAR, PLPGSQL_RC_CONTINUE, PLPGSQL_RC_EXIT, PLPGSQL_RC_OK, PLPGSQL_RC_RETURN, pop_stmt_mcontext(), ReleaseCurrentSubTransaction(), ReThrowError(), PLpgSQL_execstate::retisnull, PLpgSQL_execstate::retisset, PLpgSQL_execstate::rettype, PLpgSQL_execstate::retval, RollbackAndReleaseCurrentSubTransaction(), ErrorData::sqlerrcode, PLpgSQL_exception_block::sqlerrm_varno, PLpgSQL_exception_block::sqlstate_varno, PLpgSQL_execstate::stmt_mcontext, PLpgSQL_execstate::stmt_mcontext_parent, PLpgSQL_type::typtype, and unpack_sql_state().

Referenced by exec_stmt().

1581 {
1582  volatile int rc = -1;
1583  int i;
1584 
1585  /*
1586  * First initialize all variables declared in this block
1587  */
1588  estate->err_text = gettext_noop("during statement block local variable initialization");
1589 
1590  for (i = 0; i < block->n_initvars; i++)
1591  {
1592  int n = block->initvarnos[i];
1593  PLpgSQL_datum *datum = estate->datums[n];
1594 
1595  /*
1596  * The set of dtypes handled here must match plpgsql_add_initdatums().
1597  *
1598  * Note that we currently don't support promise datums within blocks,
1599  * only at a function's outermost scope, so we needn't handle those
1600  * here.
1601  */
1602  switch (datum->dtype)
1603  {
1604  case PLPGSQL_DTYPE_VAR:
1605  {
1606  PLpgSQL_var *var = (PLpgSQL_var *) datum;
1607 
1608  /*
1609  * Free any old value, in case re-entering block, and
1610  * initialize to NULL
1611  */
1612  assign_simple_var(estate, var, (Datum) 0, true, false);
1613 
1614  if (var->default_val == NULL)
1615  {
1616  /*
1617  * If needed, give the datatype a chance to reject
1618  * NULLs, by assigning a NULL to the variable. We
1619  * claim the value is of type UNKNOWN, not the var's
1620  * datatype, else coercion will be skipped.
1621  */
1622  if (var->datatype->typtype == TYPTYPE_DOMAIN)
1623  exec_assign_value(estate,
1624  (PLpgSQL_datum *) var,
1625  (Datum) 0,
1626  true,
1627  UNKNOWNOID,
1628  -1);
1629 
1630  /* parser should have rejected NOT NULL */
1631  Assert(!var->notnull);
1632  }
1633  else
1634  {
1635  exec_assign_expr(estate, (PLpgSQL_datum *) var,
1636  var->default_val);
1637  }
1638  }
1639  break;
1640 
1641  case PLPGSQL_DTYPE_REC:
1642  {
1643  PLpgSQL_rec *rec = (PLpgSQL_rec *) datum;
1644 
1645  /*
1646  * Deletion of any existing object will be handled during
1647  * the assignments below, and in some cases it's more
1648  * efficient for us not to get rid of it beforehand.
1649  */
1650  if (rec->default_val == NULL)
1651  {
1652  /*
1653  * If needed, give the datatype a chance to reject
1654  * NULLs, by assigning a NULL to the variable.
1655  */
1656  exec_move_row(estate, (PLpgSQL_variable *) rec,
1657  NULL, NULL);
1658 
1659  /* parser should have rejected NOT NULL */
1660  Assert(!rec->notnull);
1661  }
1662  else
1663  {
1664  exec_assign_expr(estate, (PLpgSQL_datum *) rec,
1665  rec->default_val);
1666  }
1667  }
1668  break;
1669 
1670  default:
1671  elog(ERROR, "unrecognized dtype: %d", datum->dtype);
1672  }
1673  }
1674 
1675  if (block->exceptions)
1676  {
1677  /*
1678  * Execute the statements in the block's body inside a sub-transaction
1679  */
1680  MemoryContext oldcontext = CurrentMemoryContext;
1682  ExprContext *old_eval_econtext = estate->eval_econtext;
1683  ErrorData *save_cur_error = estate->cur_error;
1684  MemoryContext stmt_mcontext;
1685 
1686  estate->err_text = gettext_noop("during statement block entry");
1687 
1688  /*
1689  * We will need a stmt_mcontext to hold the error data if an error
1690  * occurs. It seems best to force it to exist before entering the
1691  * subtransaction, so that we reduce the risk of out-of-memory during
1692  * error recovery, and because this greatly simplifies restoring the
1693  * stmt_mcontext stack to the correct state after an error. We can
1694  * ameliorate the cost of this by allowing the called statements to
1695  * use this mcontext too; so we don't push it down here.
1696  */
1697  stmt_mcontext = get_stmt_mcontext(estate);
1698 
1700  /* Want to run statements inside function's memory context */
1701  MemoryContextSwitchTo(oldcontext);
1702 
1703  PG_TRY();
1704  {
1705  /*
1706  * We need to run the block's statements with a new eval_econtext
1707  * that belongs to the current subtransaction; if we try to use
1708  * the outer econtext then ExprContext shutdown callbacks will be
1709  * called at the wrong times.
1710  */
1711  plpgsql_create_econtext(estate);
1712 
1713  estate->err_text = NULL;
1714 
1715  /* Run the block's statements */
1716  rc = exec_stmts(estate, block->body);
1717 
1718  estate->err_text = gettext_noop("during statement block exit");
1719 
1720  /*
1721  * If the block ended with RETURN, we may need to copy the return
1722  * value out of the subtransaction eval_context. We can avoid a
1723  * physical copy if the value happens to be a R/W expanded object.
1724  */
1725  if (rc == PLPGSQL_RC_RETURN &&
1726  !estate->retisset &&
1727  !estate->retisnull)
1728  {
1729  int16 resTypLen;
1730  bool resTypByVal;
1731 
1732  get_typlenbyval(estate->rettype, &resTypLen, &resTypByVal);
1733  estate->retval = datumTransfer(estate->retval,
1734  resTypByVal, resTypLen);
1735  }
1736 
1737  /* Commit the inner transaction, return to outer xact context */
1739  MemoryContextSwitchTo(oldcontext);
1740  CurrentResourceOwner = oldowner;
1741 
1742  /* Assert that the stmt_mcontext stack is unchanged */
1743  Assert(stmt_mcontext == estate->stmt_mcontext);
1744 
1745  /*
1746  * Revert to outer eval_econtext. (The inner one was
1747  * automatically cleaned up during subxact exit.)
1748  */
1749  estate->eval_econtext = old_eval_econtext;
1750  }
1751  PG_CATCH();
1752  {
1753  ErrorData *edata;
1754  ListCell *e;
1755 
1756  estate->err_text = gettext_noop("during exception cleanup");
1757 
1758  /* Save error info in our stmt_mcontext */
1759  MemoryContextSwitchTo(stmt_mcontext);
1760  edata = CopyErrorData();
1761  FlushErrorState();
1762 
1763  /* Abort the inner transaction */
1765  MemoryContextSwitchTo(oldcontext);
1766  CurrentResourceOwner = oldowner;
1767 
1768  /*
1769  * Set up the stmt_mcontext stack as though we had restored our
1770  * previous state and then done push_stmt_mcontext(). The push is
1771  * needed so that statements in the exception handler won't
1772  * clobber the error data that's in our stmt_mcontext.
1773  */
1774  estate->stmt_mcontext_parent = stmt_mcontext;
1775  estate->stmt_mcontext = NULL;
1776 
1777  /*
1778  * Now we can delete any nested stmt_mcontexts that might have
1779  * been created as children of ours. (Note: we do not immediately
1780  * release any statement-lifespan data that might have been left
1781  * behind in stmt_mcontext itself. We could attempt that by doing
1782  * a MemoryContextReset on it before collecting the error data
1783  * above, but it seems too risky to do any significant amount of
1784  * work before collecting the error.)
1785  */
1786  MemoryContextDeleteChildren(stmt_mcontext);
1787 
1788  /* Revert to outer eval_econtext */
1789  estate->eval_econtext = old_eval_econtext;
1790 
1791  /*
1792  * Must clean up the econtext too. However, any tuple table made
1793  * in the subxact will have been thrown away by SPI during subxact
1794  * abort, so we don't need to (and mustn't try to) free the
1795  * eval_tuptable.
1796  */
1797  estate->eval_tuptable = NULL;
1798  exec_eval_cleanup(estate);
1799 
1800  /* Look for a matching exception handler */
1801  foreach(e, block->exceptions->exc_list)
1802  {
1803  PLpgSQL_exception *exception = (PLpgSQL_exception *) lfirst(e);
1804 
1805  if (exception_matches_conditions(edata, exception->conditions))
1806  {
1807  /*
1808  * Initialize the magic SQLSTATE and SQLERRM variables for
1809  * the exception block; this also frees values from any
1810  * prior use of the same exception. We needn't do this
1811  * until we have found a matching exception.
1812  */
1813  PLpgSQL_var *state_var;
1814  PLpgSQL_var *errm_var;
1815 
1816  state_var = (PLpgSQL_var *)
1817  estate->datums[block->exceptions->sqlstate_varno];
1818  errm_var = (PLpgSQL_var *)
1819  estate->datums[block->exceptions->sqlerrm_varno];
1820 
1821  assign_text_var(estate, state_var,
1822  unpack_sql_state(edata->sqlerrcode));
1823  assign_text_var(estate, errm_var, edata->message);
1824 
1825  /*
1826  * Also set up cur_error so the error data is accessible
1827  * inside the handler.
1828  */
1829  estate->cur_error = edata;
1830 
1831  estate->err_text = NULL;
1832 
1833  rc = exec_stmts(estate, exception->action);
1834 
1835  break;
1836  }
1837  }
1838 
1839  /*
1840  * Restore previous state of cur_error, whether or not we executed
1841  * a handler. This is needed in case an error got thrown from
1842  * some inner block's exception handler.
1843  */
1844  estate->cur_error = save_cur_error;
1845 
1846  /* If no match found, re-throw the error */
1847  if (e == NULL)
1848  ReThrowError(edata);
1849 
1850  /* Restore stmt_mcontext stack and release the error data */
1851  pop_stmt_mcontext(estate);
1852  MemoryContextReset(stmt_mcontext);
1853  }
1854  PG_END_TRY();
1855 
1856  Assert(save_cur_error == estate->cur_error);
1857  }
1858  else
1859  {
1860  /*
1861  * Just execute the statements in the block's body
1862  */
1863  estate->err_text = NULL;
1864 
1865  rc = exec_stmts(estate, block->body);
1866  }
1867 
1868  estate->err_text = NULL;
1869 
1870  /*
1871  * Handle the return code. This is intentionally different from
1872  * LOOP_RC_PROCESSING(): CONTINUE never matches a block, and EXIT matches
1873  * a block only if there is a label match.
1874  */
1875  switch (rc)
1876  {
1877  case PLPGSQL_RC_OK:
1878  case PLPGSQL_RC_RETURN:
1879  case PLPGSQL_RC_CONTINUE:
1880  return rc;
1881 
1882  case PLPGSQL_RC_EXIT:
1883  if (estate->exitlabel == NULL)
1884  return PLPGSQL_RC_EXIT;
1885  if (block->label == NULL)
1886  return PLPGSQL_RC_EXIT;
1887  if (strcmp(block->label, estate->exitlabel) != 0)
1888  return PLPGSQL_RC_EXIT;
1889  estate->exitlabel = NULL;
1890  return PLPGSQL_RC_OK;
1891 
1892  default:
1893  elog(ERROR, "unrecognized rc: %d", rc);
1894  }
1895 
1896  return PLPGSQL_RC_OK;