PostgreSQL Source Code  git master
pl_exec.c File Reference
#include "postgres.h"
#include <ctype.h>
#include "access/detoast.h"
#include "access/htup_details.h"
#include "access/transam.h"
#include "access/tupconvert.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 "executor/tstoreReceiver.h"
#include "funcapi.h"
#include "mb/stringinfo_mb.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 "plpgsql.h"
#include "storage/proc.h"
#include "tcop/cmdtag.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 dependency graph for pl_exec.c:

Go to the source code of this file.

Data Structures

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_toplevel_block (PLpgSQL_execstate *estate, PLpgSQL_stmt_block *block)
 
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_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, ResourceOwner simple_eval_resowner)
 
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 Datum do_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 ParamListInfo exec_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, ParamListInfo paramLI)
 
Datum plpgsql_exec_function (PLpgSQL_function *func, FunctionCallInfo fcinfo, EState *simple_eval_estate, ResourceOwner simple_eval_resowner, 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 ResourceOwner shared_simple_eval_resowner = 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 135 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:610
#define ERROR
Definition: elog.h:43
const char * name
Definition: encode.c:561
int errmsg(const char *fmt,...)
Definition: elog.c:821
char * MemoryContextStrdup(MemoryContext context, const char *string)
Definition: mcxt.c:1174

Definition at line 3728 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 8667 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().

8669 {
8670  Assert(rec->dtype == PLPGSQL_DTYPE_REC);
8671 
8672  /* Transfer new record object into datum_context */
8673  TransferExpandedRecord(erh, estate->datum_context);
8674 
8675  /* Free the old value ... */
8676  if (rec->erh)
8678 
8679  /* ... and install the new */
8680  rec->erh = erh;
8681 }
PLpgSQL_datum_type dtype
Definition: plpgsql.h:381
ExpandedRecordHeader * erh
Definition: plpgsql.h:404
void DeleteExpandedObject(Datum d)
#define Assert(condition)
Definition: c.h:746
#define TransferExpandedRecord(erh, cxt)
MemoryContext datum_context
Definition: plpgsql.h:1084
#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 8591 of file pl_exec.c.

References Assert, PLpgSQL_execstate::atomic, PLpgSQL_var::datatype, datumCopy(), DatumGetPointer, DatumIsReadWriteExpandedObject, DeleteExpandedObject(), detoast_external_attr(), PLpgSQL_var::dtype, PLpgSQL_var::freeval, get_eval_mcontext, 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().

8593 {
8594  Assert(var->dtype == PLPGSQL_DTYPE_VAR ||
8595  var->dtype == PLPGSQL_DTYPE_PROMISE);
8596 
8597  /*
8598  * In non-atomic contexts, we do not want to store TOAST pointers in
8599  * variables, because such pointers might become stale after a commit.
8600  * Forcibly detoast in such cases. We don't want to detoast (flatten)
8601  * expanded objects, however; those should be OK across a transaction
8602  * boundary since they're just memory-resident objects. (Elsewhere in
8603  * this module, operations on expanded records likewise need to request
8604  * detoasting of record fields when !estate->atomic. Expanded arrays are
8605  * not a problem since all array entries are always detoasted.)
8606  */
8607  if (!estate->atomic && !isnull && var->datatype->typlen == -1 &&
8609  {
8610  MemoryContext oldcxt;
8611  Datum detoasted;
8612 
8613  /*
8614  * Do the detoasting in the eval_mcontext to avoid long-term leakage
8615  * of whatever memory toast fetching might leak. Then we have to copy
8616  * the detoasted datum to the function's main context, which is a
8617  * pain, but there's little choice.
8618  */
8619  oldcxt = MemoryContextSwitchTo(get_eval_mcontext(estate));
8620  detoasted = PointerGetDatum(detoast_external_attr((struct varlena *) DatumGetPointer(newvalue)));
8621  MemoryContextSwitchTo(oldcxt);
8622  /* Now's a good time to not leak the input value if it's freeable */
8623  if (freeable)
8624  pfree(DatumGetPointer(newvalue));
8625  /* Once we copy the value, it's definitely freeable */
8626  newvalue = datumCopy(detoasted, false, -1);
8627  freeable = true;
8628  /* Can't clean up eval_mcontext here, but it'll happen before long */
8629  }
8630 
8631  /* Free the old value if needed */
8632  if (var->freeval)
8633  {
8635  var->isnull,
8636  var->datatype->typlen))
8638  else
8639  pfree(DatumGetPointer(var->value));
8640  }
8641  /* Assign new value to datum */
8642  var->value = newvalue;
8643  var->isnull = isnull;
8644  var->freeval = freeable;
8645 
8646  /*
8647  * If it's a promise variable, then either we just assigned the promised
8648  * value, or the user explicitly assigned an overriding value. Either
8649  * way, cancel the promise.
8650  */
8652 }
PLpgSQL_promise_type promise
Definition: plpgsql.h:332
#define VARATT_IS_EXTERNAL_NON_EXPANDED(PTR)
Definition: postgres.h:324
PLpgSQL_datum_type dtype
Definition: plpgsql.h:301
#define PointerGetDatum(X)
Definition: postgres.h:556
struct varlena * detoast_external_attr(struct varlena *attr)
Definition: detoast.c:44
PLpgSQL_type * datatype
Definition: plpgsql.h:310
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void pfree(void *pointer)
Definition: mcxt.c:1057
bool freeval
Definition: plpgsql.h:325
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition: datum.c:131
#define get_eval_mcontext(estate)
Definition: pl_exec.c:131
uintptr_t Datum
Definition: postgres.h:367
Datum value
Definition: plpgsql.h:323
void DeleteExpandedObject(Datum d)
#define Assert(condition)
Definition: c.h:746
#define DatumIsReadWriteExpandedObject(d, isnull, typlen)
#define DatumGetPointer(X)
Definition: postgres.h:549
Definition: c.h:563
int16 typlen
Definition: plpgsql.h:204
bool isnull
Definition: plpgsql.h:324

◆ assign_text_var()

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

Definition at line 8658 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().

8659 {
8660  assign_simple_var(estate, var, CStringGetTextDatum(str), false, true);
8661 }
static void assign_simple_var(PLpgSQL_execstate *estate, PLpgSQL_var *var, Datum newvalue, bool isnull, bool freeable)
Definition: pl_exec.c:8591
#define CStringGetTextDatum(s)
Definition: builtins.h:86

◆ coerce_function_result_tuple()

static void coerce_function_result_tuple ( PLpgSQL_execstate estate,
TupleDesc  tupdesc 
)
static

Definition at line 790 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().

791 {
792  HeapTuple rettup;
793  TupleDesc retdesc;
794  TupleConversionMap *tupmap;
795 
796  /* We assume exec_stmt_return verified that result is composite */
797  Assert(type_is_rowtype(estate->rettype));
798 
799  /* We can special-case expanded records for speed */
801  {
803 
804  Assert(erh->er_magic == ER_MAGIC);
805 
806  /* Extract record's TupleDesc */
807  retdesc = expanded_record_get_tupdesc(erh);
808 
809  /* check rowtype compatibility */
810  tupmap = convert_tuples_by_position(retdesc,
811  tupdesc,
812  gettext_noop("returned record type does not match expected record type"));
813 
814  /* it might need conversion */
815  if (tupmap)
816  {
817  rettup = expanded_record_get_tuple(erh);
818  Assert(rettup);
819  rettup = execute_attr_map_tuple(rettup, tupmap);
820 
821  /*
822  * Copy tuple to upper executor memory, as a tuple Datum. Make
823  * sure it is labeled with the caller-supplied tuple type.
824  */
825  estate->retval = PointerGetDatum(SPI_returntuple(rettup, tupdesc));
826  /* no need to free map, we're about to return anyway */
827  }
828  else if (!(tupdesc->tdtypeid == erh->er_decltypeid ||
829  (tupdesc->tdtypeid == RECORDOID &&
830  !ExpandedRecordIsDomain(erh))))
831  {
832  /*
833  * The expanded record has the right physical tupdesc, but the
834  * wrong type ID. (Typically, the expanded record is RECORDOID
835  * but the function is declared to return a named composite type.
836  * As in exec_move_row_from_datum, we don't allow returning a
837  * composite-domain record from a function declared to return
838  * RECORD.) So we must flatten the record to a tuple datum and
839  * overwrite its type fields with the right thing. spi.c doesn't
840  * provide any easy way to deal with this case, so we end up
841  * duplicating the guts of datumCopy() :-(
842  */
843  Size resultsize;
844  HeapTupleHeader tuphdr;
845 
846  resultsize = EOH_get_flat_size(&erh->hdr);
847  tuphdr = (HeapTupleHeader) SPI_palloc(resultsize);
848  EOH_flatten_into(&erh->hdr, (void *) tuphdr, resultsize);
849  HeapTupleHeaderSetTypeId(tuphdr, tupdesc->tdtypeid);
850  HeapTupleHeaderSetTypMod(tuphdr, tupdesc->tdtypmod);
851  estate->retval = PointerGetDatum(tuphdr);
852  }
853  else
854  {
855  /*
856  * We need only copy result into upper executor memory context.
857  * However, if we have a R/W expanded datum, we can just transfer
858  * its ownership out to the upper executor context.
859  */
860  estate->retval = SPI_datumTransfer(estate->retval,
861  false,
862  -1);
863  }
864  }
865  else
866  {
867  /* Convert composite datum to a HeapTuple and TupleDesc */
868  HeapTupleData tmptup;
869 
870  retdesc = deconstruct_composite_datum(estate->retval, &tmptup);
871  rettup = &tmptup;
872 
873  /* check rowtype compatibility */
874  tupmap = convert_tuples_by_position(retdesc,
875  tupdesc,
876  gettext_noop("returned record type does not match expected record type"));
877 
878  /* it might need conversion */
879  if (tupmap)
880  rettup = execute_attr_map_tuple(rettup, tupmap);
881 
882  /*
883  * Copy tuple to upper executor memory, as a tuple Datum. Make sure
884  * it is labeled with the caller-supplied tuple type.
885  */
886  estate->retval = PointerGetDatum(SPI_returntuple(rettup, tupdesc));
887 
888  /* no need to free map, we're about to return anyway */
889 
890  ReleaseTupleDesc(retdesc);
891  }
892 }
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:923
#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:59
#define PointerGetDatum(X)
Definition: postgres.h:556
HeapTupleHeaderData * HeapTupleHeader
Definition: htup.h:23
#define gettext_noop(x)
Definition: c.h:1139
static TupleDesc deconstruct_composite_datum(Datum value, HeapTupleData *tmptup)
Definition: pl_exec.c:7554
ExpandedObjectHeader hdr
Datum SPI_datumTransfer(Datum value, bool typByVal, int typLen)
Definition: spi.c:1210
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:2543
HeapTuple execute_attr_map_tuple(HeapTuple tuple, TupleConversionMap *map)
Definition: tupconvert.c:139
static TupleDesc expanded_record_get_tupdesc(ExpandedRecordHeader *erh)
void * SPI_palloc(Size size)
Definition: spi.c:1187
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:746
size_t Size
Definition: c.h:474
#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 7455 of file pl_exec.c.

References i, TupleDescData::natts, and TupleDescAttr.

Referenced by exec_for_query(), and exec_move_row().

7456 {
7457  int i;
7458 
7459  /* Possibly we could allow src_tupdesc to have extra columns? */
7460  if (dst_tupdesc->natts != src_tupdesc->natts)
7461  return false;
7462 
7463  for (i = 0; i < dst_tupdesc->natts; i++)
7464  {
7465  Form_pg_attribute dattr = TupleDescAttr(dst_tupdesc, i);
7466  Form_pg_attribute sattr = TupleDescAttr(src_tupdesc, i);
7467 
7468  if (dattr->attisdropped != sattr->attisdropped)
7469  return false;
7470  if (!dattr->attisdropped)
7471  {
7472  /* Normal columns must match by type and typmod */
7473  if (dattr->atttypid != sattr->atttypid ||
7474  (dattr->atttypmod >= 0 &&
7475  dattr->atttypmod != sattr->atttypmod))
7476  return false;
7477  }
7478  else
7479  {
7480  /* Dropped columns are OK as long as length/alignment match */
7481  if (dattr->attlen != sattr->attlen ||
7482  dattr->attalign != sattr->attalign)
7483  return false;
7484  }
7485  }
7486  return true;
7487 }
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:193
int i

◆ contains_target_param()

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

Definition at line 8393 of file pl_exec.c.

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

Referenced by exec_check_rw_parameter().

8394 {
8395  if (node == NULL)
8396  return false;
8397  if (IsA(node, Param))
8398  {
8399  Param *param = (Param *) node;
8400 
8401  if (param->paramkind == PARAM_EXTERN &&
8402  param->paramid == *target_dno + 1)
8403  return true;
8404  return false;
8405  }
8407  (void *) target_dno);
8408 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:579
ParamKind paramkind
Definition: primnodes.h:262
static bool contains_target_param(Node *node, int *target_dno)
Definition: pl_exec.c:8393
int paramid
Definition: primnodes.h:263
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1888

◆ convert_value_to_string()

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

Definition at line 7853 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(), exec_stmt_return_query(), format_expr_params(), and format_preparedparamsdata().

7854 {
7855  char *result;
7856  MemoryContext oldcontext;
7857  Oid typoutput;
7858  bool typIsVarlena;
7859 
7860  oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
7861  getTypeOutputInfo(valtype, &typoutput, &typIsVarlena);
7862  result = OidOutputFunctionCall(typoutput, value);
7863  MemoryContextSwitchTo(oldcontext);
7864 
7865  return result;
7866 }
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:2784
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:131
static struct @143 value
char * OidOutputFunctionCall(Oid functionId, Datum val)
Definition: fmgr.c:1657

◆ copy_plpgsql_datums()

static void copy_plpgsql_datums ( PLpgSQL_execstate estate,
PLpgSQL_function func 
)
static

Definition at line 1267 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().

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

◆ deconstruct_composite_datum()

static TupleDesc deconstruct_composite_datum ( Datum  value,
HeapTupleData tmptup 
)
static

Definition at line 7554 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().

7555 {
7556  HeapTupleHeader td;
7557  Oid tupType;
7558  int32 tupTypmod;
7559 
7560  /* Get tuple body (note this could involve detoasting) */
7562 
7563  /* Build a temporary HeapTuple control structure */
7564  tmptup->t_len = HeapTupleHeaderGetDatumLength(td);
7565  ItemPointerSetInvalid(&(tmptup->t_self));
7566  tmptup->t_tableOid = InvalidOid;
7567  tmptup->t_data = td;
7568 
7569  /* Extract rowtype info and find a tupdesc */
7570  tupType = HeapTupleHeaderGetTypeId(td);
7571  tupTypmod = HeapTupleHeaderGetTypMod(td);
7572  return lookup_rowtype_tupdesc(tupType, tupTypmod);
7573 }
TupleDesc lookup_rowtype_tupdesc(Oid type_id, int32 typmod)
Definition: typcache.c:1710
unsigned int Oid
Definition: postgres_ext.h:31
#define DatumGetHeapTupleHeader(X)
Definition: fmgr.h:294
signed int int32
Definition: c.h:363
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
static struct @143 value
#define ItemPointerSetInvalid(pointer)
Definition: itemptr.h:172
#define HeapTupleHeaderGetDatumLength(tup)
Definition: htup_details.h:452

◆ do_cast_value()

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

Definition at line 7906 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_cast_value().

7910 {
7911  plpgsql_CastHashEntry *cast_entry;
7912 
7913  cast_entry = get_cast_hashentry(estate,
7914  valtype, valtypmod,
7915  reqtype, reqtypmod);
7916  if (cast_entry)
7917  {
7918  ExprContext *econtext = estate->eval_econtext;
7919  MemoryContext oldcontext;
7920 
7921  oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
7922 
7923  econtext->caseValue_datum = value;
7924  econtext->caseValue_isNull = *isnull;
7925 
7926  cast_entry->cast_in_use = true;
7927 
7928  value = ExecEvalExpr(cast_entry->cast_exprstate, econtext,
7929  isnull);
7930 
7931  cast_entry->cast_in_use = false;
7932 
7933  MemoryContextSwitchTo(oldcontext);
7934  }
7935 
7936  return value;
7937 }
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:7950
Datum caseValue_datum
Definition: execnodes.h:250
static Datum ExecEvalExpr(ExprState *state, ExprContext *econtext, bool *isNull)
Definition: executor.h:292
#define get_eval_mcontext(estate)
Definition: pl_exec.c:131
static struct @143 value
ExprContext * eval_econtext
Definition: plpgsql.h:1109
bool caseValue_isNull
Definition: execnodes.h:252
ExprState * cast_exprstate
Definition: pl_exec.c:167

◆ exception_matches_conditions()

static bool exception_matches_conditions ( ErrorData edata,
PLpgSQL_condition cond 
)
static

Definition at line 1553 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().

1554 {
1555  for (; cond != NULL; cond = cond->next)
1556  {
1557  int sqlerrstate = cond->sqlerrstate;
1558 
1559  /*
1560  * OTHERS matches everything *except* query-canceled and
1561  * assert-failure. If you're foolish enough, you can match those
1562  * explicitly.
1563  */
1564  if (sqlerrstate == 0)
1565  {
1566  if (edata->sqlerrcode != ERRCODE_QUERY_CANCELED &&
1567  edata->sqlerrcode != ERRCODE_ASSERT_FAILURE)
1568  return true;
1569  }
1570  /* Exact match? */
1571  else if (edata->sqlerrcode == sqlerrstate)
1572  return true;
1573  /* Category match? */
1574  else if (ERRCODE_IS_CATEGORY(sqlerrstate) &&
1575  ERRCODE_TO_CATEGORY(edata->sqlerrcode) == sqlerrstate)
1576  return true;
1577  }
1578  return false;
1579 }
#define ERRCODE_IS_CATEGORY(ec)
Definition: elog.h:68
int sqlerrcode
Definition: elog.h:364
struct PLpgSQL_condition * next
Definition: plpgsql.h:487
#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 5058 of file pl_exec.c.

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

Referenced by exec_stmt_getdiag().

5060 {
5061  text *value;
5062  MemoryContext oldcontext;
5063 
5064  /* Use eval_mcontext for short-lived text value */
5065  oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
5066  if (str != NULL)
5067  value = cstring_to_text(str);
5068  else
5069  value = cstring_to_text("");
5070  MemoryContextSwitchTo(oldcontext);
5071 
5072  exec_assign_value(estate, target, PointerGetDatum(value), false,
5073  TEXTOID, -1);
5074 }
#define PointerGetDatum(X)
Definition: postgres.h:556
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define get_eval_mcontext(estate)
Definition: pl_exec.c:131
static struct @143 value
text * cstring_to_text(const char *s)
Definition: varlena.c:188
Definition: c.h:563
static void exec_assign_value(PLpgSQL_execstate *estate, PLpgSQL_datum *target, Datum value, bool isNull, Oid valtype, int32 valtypmod)
Definition: pl_exec.c:5086

◆ exec_assign_expr()

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

Definition at line 5021 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().

5023 {
5024  Datum value;
5025  bool isnull;
5026  Oid valtype;
5027  int32 valtypmod;
5028 
5029  /*
5030  * If first time through, create a plan for this expression, and then see
5031  * if we can pass the target variable as a read-write parameter to the
5032  * expression. (This is a bit messy, but it seems cleaner than modifying
5033  * the API of exec_eval_expr for the purpose.)
5034  */
5035  if (expr->plan == NULL)
5036  {
5037  exec_prepare_plan(estate, expr, 0, true);
5038  if (target->dtype == PLPGSQL_DTYPE_VAR)
5039  exec_check_rw_parameter(expr, target->dno);
5040  }
5041 
5042  value = exec_eval_expr(estate, expr, &isnull, &valtype, &valtypmod);
5043  exec_assign_value(estate, target, value, isnull, valtype, valtypmod);
5044  exec_eval_cleanup(estate);
5045 }
static void exec_prepare_plan(PLpgSQL_execstate *estate, PLpgSQL_expr *expr, int cursorOptions, bool keepplan)
Definition: pl_exec.c:4168
static void exec_check_rw_parameter(PLpgSQL_expr *expr, int target_dno)
Definition: pl_exec.c:8316
static void exec_eval_cleanup(PLpgSQL_execstate *estate)
Definition: pl_exec.c:4147
unsigned int Oid
Definition: postgres_ext.h:31
PLpgSQL_datum_type dtype
Definition: plpgsql.h:267
SPIPlanPtr plan
Definition: plpgsql.h:222
signed int int32
Definition: c.h:363
static Datum exec_eval_expr(PLpgSQL_execstate *estate, PLpgSQL_expr *expr, bool *isNull, Oid *rettype, int32 *rettypmod)
Definition: pl_exec.c:5882
uintptr_t Datum
Definition: postgres.h:367
static struct @143 value
static void exec_assign_value(PLpgSQL_execstate *estate, PLpgSQL_datum *target, Datum value, bool isNull, Oid valtype, int32 valtypmod)
Definition: pl_exec.c:5086

◆ 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 5086 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().

5090 {
5091  switch (target->dtype)
5092  {
5093  case PLPGSQL_DTYPE_VAR:
5094  case PLPGSQL_DTYPE_PROMISE:
5095  {
5096  /*
5097  * Target is a variable
5098  */
5099  PLpgSQL_var *var = (PLpgSQL_var *) target;
5100  Datum newvalue;
5101 
5102  newvalue = exec_cast_value(estate,
5103  value,
5104  &isNull,
5105  valtype,
5106  valtypmod,
5107  var->datatype->typoid,
5108  var->datatype->atttypmod);
5109 
5110  if (isNull && var->notnull)
5111  ereport(ERROR,
5112  (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
5113  errmsg("null value cannot be assigned to variable \"%s\" declared NOT NULL",
5114  var->refname)));
5115 
5116  /*
5117  * If type is by-reference, copy the new value (which is
5118  * probably in the eval_mcontext) into the procedure's main
5119  * memory context. But if it's a read/write reference to an
5120  * expanded object, no physical copy needs to happen; at most
5121  * we need to reparent the object's memory context.
5122  *
5123  * If it's an array, we force the value to be stored in R/W
5124  * expanded form. This wins if the function later does, say,
5125  * a lot of array subscripting operations on the variable, and
5126  * otherwise might lose. We might need to use a different
5127  * heuristic, but it's too soon to tell. Also, are there
5128  * cases where it'd be useful to force non-array values into
5129  * expanded form?
5130  */
5131  if (!var->datatype->typbyval && !isNull)
5132  {
5133  if (var->datatype->typisarray &&
5135  {
5136  /* array and not already R/W, so apply expand_array */
5137  newvalue = expand_array(newvalue,
5138  estate->datum_context,
5139  NULL);
5140  }
5141  else
5142  {
5143  /* else transfer value if R/W, else just datumCopy */
5144  newvalue = datumTransfer(newvalue,
5145  false,
5146  var->datatype->typlen);
5147  }
5148  }
5149 
5150  /*
5151  * Now free the old value, if any, and assign the new one. But
5152  * skip the assignment if old and new values are the same.
5153  * Note that for expanded objects, this test is necessary and
5154  * cannot reliably be made any earlier; we have to be looking
5155  * at the object's standard R/W pointer to be sure pointer
5156  * equality is meaningful.
5157  *
5158  * Also, if it's a promise variable, we should disarm the
5159  * promise in any case --- otherwise, assigning null to an
5160  * armed promise variable would fail to disarm the promise.
5161  */
5162  if (var->value != newvalue || var->isnull || isNull)
5163  assign_simple_var(estate, var, newvalue, isNull,
5164  (!var->datatype->typbyval && !isNull));
5165  else
5167  break;
5168  }
5169 
5170  case PLPGSQL_DTYPE_ROW:
5171  {
5172  /*
5173  * Target is a row variable
5174  */
5175  PLpgSQL_row *row = (PLpgSQL_row *) target;
5176 
5177  if (isNull)
5178  {
5179  /* If source is null, just assign nulls to the row */
5180  exec_move_row(estate, (PLpgSQL_variable *) row,
5181  NULL, NULL);
5182  }
5183  else
5184  {
5185  /* Source must be of RECORD or composite type */
5186  if (!type_is_rowtype(valtype))
5187  ereport(ERROR,
5188  (errcode(ERRCODE_DATATYPE_MISMATCH),
5189  errmsg("cannot assign non-composite value to a row variable")));
5191  value);
5192  }
5193  break;
5194  }
5195 
5196  case PLPGSQL_DTYPE_REC:
5197  {
5198  /*
5199  * Target is a record variable
5200  */
5201  PLpgSQL_rec *rec = (PLpgSQL_rec *) target;
5202 
5203  if (isNull)
5204  {
5205  if (rec->notnull)
5206  ereport(ERROR,
5207  (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
5208  errmsg("null value cannot be assigned to variable \"%s\" declared NOT NULL",
5209  rec->refname)));
5210 
5211  /* Set variable to a simple NULL */
5212  exec_move_row(estate, (PLpgSQL_variable *) rec,
5213  NULL, NULL);
5214  }
5215  else
5216  {
5217  /* Source must be of RECORD or composite type */
5218  if (!type_is_rowtype(valtype))
5219  ereport(ERROR,
5220  (errcode(ERRCODE_DATATYPE_MISMATCH),
5221  errmsg("cannot assign non-composite value to a record variable")));
5223  value);
5224  }
5225  break;
5226  }
5227 
5229  {
5230  /*
5231  * Target is a field of a record
5232  */
5233  PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) target;
5234  PLpgSQL_rec *rec;
5235  ExpandedRecordHeader *erh;
5236 
5237  rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
5238  erh = rec->erh;
5239 
5240  /*
5241  * If record variable is NULL, instantiate it if it has a
5242  * named composite type, else complain. (This won't change
5243  * the logical state of the record, but if we successfully
5244  * assign below, the unassigned fields will all become NULLs.)
5245  */
5246  if (erh == NULL)
5247  {
5248  instantiate_empty_record_variable(estate, rec);
5249  erh = rec->erh;
5250  }
5251 
5252  /*
5253  * Look up the field's properties if we have not already, or
5254  * if the tuple descriptor ID changed since last time.
5255  */
5256  if (unlikely(recfield->rectupledescid != erh->er_tupdesc_id))
5257  {
5259  recfield->fieldname,
5260  &recfield->finfo))
5261  ereport(ERROR,
5262  (errcode(ERRCODE_UNDEFINED_COLUMN),
5263  errmsg("record \"%s\" has no field \"%s\"",
5264  rec->refname, recfield->fieldname)));
5265  recfield->rectupledescid = erh->er_tupdesc_id;
5266  }
5267 
5268  /* We don't support assignments to system columns. */
5269  if (recfield->finfo.fnumber <= 0)
5270  ereport(ERROR,
5271  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5272  errmsg("cannot assign to system column \"%s\"",
5273  recfield->fieldname)));
5274 
5275  /* Cast the new value to the right type, if needed. */
5276  value = exec_cast_value(estate,
5277  value,
5278  &isNull,
5279  valtype,
5280  valtypmod,
5281  recfield->finfo.ftypeid,
5282  recfield->finfo.ftypmod);
5283 
5284  /* And assign it. */
5285  expanded_record_set_field(erh, recfield->finfo.fnumber,
5286  value, isNull, !estate->atomic);
5287  break;
5288  }
5289 
5291  {
5292  /*
5293  * Target is an element of an array
5294  */
5295  PLpgSQL_arrayelem *arrayelem;
5296  int nsubscripts;
5297  int i;
5298  PLpgSQL_expr *subscripts[MAXDIM];
5299  int subscriptvals[MAXDIM];
5300  Datum oldarraydatum,
5301  newarraydatum,
5302  coerced_value;
5303  bool oldarrayisnull;
5304  Oid parenttypoid;
5305  int32 parenttypmod;
5306  SPITupleTable *save_eval_tuptable;
5307  MemoryContext oldcontext;
5308 
5309  /*
5310  * We need to do subscript evaluation, which might require
5311  * evaluating general expressions; and the caller might have
5312  * done that too in order to prepare the input Datum. We have
5313  * to save and restore the caller's SPI_execute result, if
5314  * any.
5315  */
5316  save_eval_tuptable = estate->eval_tuptable;
5317  estate->eval_tuptable = NULL;
5318 
5319  /*
5320  * To handle constructs like x[1][2] := something, we have to
5321  * be prepared to deal with a chain of arrayelem datums. Chase
5322  * back to find the base array datum, and save the subscript
5323  * expressions as we go. (We are scanning right to left here,
5324  * but want to evaluate the subscripts left-to-right to
5325  * minimize surprises.) Note that arrayelem is left pointing
5326  * to the leftmost arrayelem datum, where we will cache the
5327  * array element type data.
5328  */
5329  nsubscripts = 0;
5330  do
5331  {
5332  arrayelem = (PLpgSQL_arrayelem *) target;
5333  if (nsubscripts >= MAXDIM)
5334  ereport(ERROR,
5335  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5336  errmsg("number of array dimensions (%d) exceeds the maximum allowed (%d)",
5337  nsubscripts + 1, MAXDIM)));
5338  subscripts[nsubscripts++] = arrayelem->subscript;
5339  target = estate->datums[arrayelem->arrayparentno];
5340  } while (target->dtype == PLPGSQL_DTYPE_ARRAYELEM);
5341 
5342  /* Fetch current value of array datum */
5343  exec_eval_datum(estate, target,
5344  &parenttypoid, &parenttypmod,
5345  &oldarraydatum, &oldarrayisnull);
5346 
5347  /* Update cached type data if necessary */
5348  if (arrayelem->parenttypoid != parenttypoid ||
5349  arrayelem->parenttypmod != parenttypmod)
5350  {
5351  Oid arraytypoid;
5352  int32 arraytypmod = parenttypmod;
5353  int16 arraytyplen;
5354  Oid elemtypoid;
5355  int16 elemtyplen;
5356  bool elemtypbyval;
5357  char elemtypalign;
5358 
5359  /* If target is domain over array, reduce to base type */
5360  arraytypoid = getBaseTypeAndTypmod(parenttypoid,
5361  &arraytypmod);
5362 
5363  /* ... and identify the element type */
5364  elemtypoid = get_element_type(arraytypoid);
5365  if (!OidIsValid(elemtypoid))
5366  ereport(ERROR,
5367  (errcode(ERRCODE_DATATYPE_MISMATCH),
5368  errmsg("subscripted object is not an array")));
5369 
5370  /* Collect needed data about the types */
5371  arraytyplen = get_typlen(arraytypoid);
5372 
5373  get_typlenbyvalalign(elemtypoid,
5374  &elemtyplen,
5375  &elemtypbyval,
5376  &elemtypalign);
5377 
5378  /* Now safe to update the cached data */
5379  arrayelem->parenttypoid = parenttypoid;
5380  arrayelem->parenttypmod = parenttypmod;
5381  arrayelem->arraytypoid = arraytypoid;
5382  arrayelem->arraytypmod = arraytypmod;
5383  arrayelem->arraytyplen = arraytyplen;
5384  arrayelem->elemtypoid = elemtypoid;
5385  arrayelem->elemtyplen = elemtyplen;
5386  arrayelem->elemtypbyval = elemtypbyval;
5387  arrayelem->elemtypalign = elemtypalign;
5388  }
5389 
5390  /*
5391  * Evaluate the subscripts, switch into left-to-right order.
5392  * Like the expression built by ExecInitSubscriptingRef(),
5393  * complain if any subscript is null.
5394  */
5395  for (i = 0; i < nsubscripts; i++)
5396  {
5397  bool subisnull;
5398 
5399  subscriptvals[i] =
5400  exec_eval_integer(estate,
5401  subscripts[nsubscripts - 1 - i],
5402  &subisnull);
5403  if (subisnull)
5404  ereport(ERROR,
5405  (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
5406  errmsg("array subscript in assignment must not be null")));
5407 
5408  /*
5409  * Clean up in case the subscript expression wasn't
5410  * simple. We can't do exec_eval_cleanup, but we can do
5411  * this much (which is safe because the integer subscript
5412  * value is surely pass-by-value), and we must do it in
5413  * case the next subscript expression isn't simple either.
5414  */
5415  if (estate->eval_tuptable != NULL)
5417  estate->eval_tuptable = NULL;
5418  }
5419 
5420  /* Now we can restore caller's SPI_execute result if any. */
5421  Assert(estate->eval_tuptable == NULL);
5422  estate->eval_tuptable = save_eval_tuptable;
5423 
5424  /* Coerce source value to match array element type. */
5425  coerced_value = exec_cast_value(estate,
5426  value,
5427  &isNull,
5428  valtype,
5429  valtypmod,
5430  arrayelem->elemtypoid,
5431  arrayelem->arraytypmod);
5432 
5433  /*
5434  * If the original array is null, cons up an empty array so
5435  * that the assignment can proceed; we'll end with a
5436  * one-element array containing just the assigned-to
5437  * subscript. This only works for varlena arrays, though; for
5438  * fixed-length array types we skip the assignment. We can't
5439  * support assignment of a null entry into a fixed-length
5440  * array, either, so that's a no-op too. This is all ugly but
5441  * corresponds to the current behavior of execExpr*.c.
5442  */
5443  if (arrayelem->arraytyplen > 0 && /* fixed-length array? */
5444  (oldarrayisnull || isNull))
5445  return;
5446 
5447  /* empty array, if any, and newarraydatum are short-lived */
5448  oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
5449 
5450  if (oldarrayisnull)
5451  oldarraydatum = PointerGetDatum(construct_empty_array(arrayelem->elemtypoid));
5452 
5453  /*
5454  * Build the modified array value.
5455  */
5456  newarraydatum = array_set_element(oldarraydatum,
5457  nsubscripts,
5458  subscriptvals,
5459  coerced_value,
5460  isNull,
5461  arrayelem->arraytyplen,
5462  arrayelem->elemtyplen,
5463  arrayelem->elemtypbyval,
5464  arrayelem->elemtypalign);
5465 
5466  MemoryContextSwitchTo(oldcontext);
5467 
5468  /*
5469  * Assign the new array to the base variable. It's never NULL
5470  * at this point. Note that if the target is a domain,
5471  * coercing the base array type back up to the domain will
5472  * happen within exec_assign_value.
5473  */
5474  exec_assign_value(estate, target,
5475  newarraydatum,
5476  false,
5477  arrayelem->arraytypoid,
5478  arrayelem->arraytypmod);
5479  break;
5480  }
5481 
5482  default:
5483  elog(ERROR, "unrecognized dtype: %d", target->dtype);
5484  }
5485 }
PLpgSQL_promise_type promise
Definition: plpgsql.h:332
signed short int16
Definition: c.h:362
int16 elemtyplen
Definition: plpgsql.h:443
#define expanded_record_set_field(erh, fnumber, newValue, isnull, expand_external)
Oid getBaseTypeAndTypmod(Oid typid, int32 *typmod)
Definition: lsyscache.c:2426
SPITupleTable * eval_tuptable
Definition: plpgsql.h:1107
char * refname
Definition: plpgsql.h:303
static void exec_eval_datum(PLpgSQL_execstate *estate, PLpgSQL_datum *datum, Oid *typeid, int32 *typetypmod, Datum *value, bool *isnull)
Definition: pl_exec.c:5505
bool expanded_record_lookup_field(ExpandedRecordHeader *erh, const char *fieldname, ExpandedRecordFieldInfo *finfo)
#define MAXDIM
Definition: c.h:543
Oid get_element_type(Oid typid)
Definition: lsyscache.c:2636
void get_typlenbyvalalign(Oid typid, int16 *typlen, bool *typbyval, char *typalign)
Definition: lsyscache.c:2159
#define PointerGetDatum(X)
Definition: postgres.h:556
PLpgSQL_type * datatype
Definition: plpgsql.h:310
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:7818
ExpandedRecordHeader * erh
Definition: plpgsql.h:404
int errcode(int sqlerrcode)
Definition: elog.c:610
static void assign_simple_var(PLpgSQL_execstate *estate, PLpgSQL_var *var, Datum newvalue, bool isnull, bool freeable)
Definition: pl_exec.c:8591
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:2221
ArrayType * construct_empty_array(Oid elmtype)
Definition: arrayfuncs.c:3432
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:7585
PLpgSQL_datum_type dtype
Definition: plpgsql.h:267
#define OidIsValid(objectId)
Definition: c.h:652
char * refname
Definition: plpgsql.h:383
signed int int32
Definition: c.h:363
PLpgSQL_datum ** datums
Definition: plpgsql.h:1082
int32 arraytypmod
Definition: plpgsql.h:440
bool notnull
Definition: plpgsql.h:306
static Datum exec_cast_value(PLpgSQL_execstate *estate, Datum value, bool *isnull, Oid valtype, int32 valtypmod, Oid reqtype, int32 reqtypmod)
Definition: pl_exec.c:7882
#define ERROR
Definition: elog.h:43
bool type_is_rowtype(Oid typid)
Definition: lsyscache.c:2543
uint64 rectupledescid
Definition: plpgsql.h:419
bool typbyval
Definition: plpgsql.h:205
#define get_eval_mcontext(estate)
Definition: pl_exec.c:131
void SPI_freetuptable(SPITupleTable *tuptable)
Definition: spi.c:1235
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:5836
ExpandedRecordFieldInfo finfo
Definition: plpgsql.h:420
int32 parenttypmod
Definition: plpgsql.h:438
Datum value
Definition: plpgsql.h:323
static struct @143 value
#define ereport(elevel,...)
Definition: elog.h:144
Datum datumTransfer(Datum value, bool typByVal, int typLen)
Definition: datum.c:193
#define Assert(condition)
Definition: c.h:746
int16 arraytyplen
Definition: plpgsql.h:441
#define DatumGetPointer(X)
Definition: postgres.h:549
MemoryContext datum_context
Definition: plpgsql.h:1084
int16 get_typlen(Oid typid)
Definition: lsyscache.c:2085
int errmsg(const char *fmt,...)
Definition: elog.c:821
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:6911
#define elog(elevel,...)
Definition: elog.h:214
int i
PLpgSQL_expr * subscript
Definition: plpgsql.h:433
#define VARATT_IS_EXTERNAL_EXPANDED_RW(PTR)
Definition: postgres.h:320
#define unlikely(x)
Definition: c.h:207
int16 typlen
Definition: plpgsql.h:204
bool notnull
Definition: plpgsql.h:386
char * fieldname
Definition: plpgsql.h:416
static void exec_assign_value(PLpgSQL_execstate *estate, PLpgSQL_datum *target, Datum value, bool isNull, Oid valtype, int32 valtypmod)
Definition: pl_exec.c:5086
bool isnull
Definition: plpgsql.h:324
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 
)
inlinestatic

Definition at line 7882 of file pl_exec.c.

References do_cast_value(), 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().

7886 {
7887  /*
7888  * If the type of the given value isn't what's requested, convert it.
7889  */
7890  if (valtype != reqtype ||
7891  (valtypmod != reqtypmod && reqtypmod != -1))
7892  {
7893  /* We keep the slow path out-of-line. */
7894  value = do_cast_value(estate, value, isnull, valtype, valtypmod,
7895  reqtype, reqtypmod);
7896  }
7897 
7898  return value;
7899 }
static Datum do_cast_value(PLpgSQL_execstate *estate, Datum value, bool *isnull, Oid valtype, int32 valtypmod, Oid reqtype, int32 reqtypmod)
Definition: pl_exec.c:7906
static struct @143 value

◆ exec_check_rw_parameter()

static void exec_check_rw_parameter ( PLpgSQL_expr expr,
int  target_dno 
)
static

Definition at line 8316 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().

8317 {
8318  Oid funcid;
8319  List *fargs;
8320  ListCell *lc;
8321 
8322  /* Assume unsafe */
8323  expr->rwparam = -1;
8324 
8325  /*
8326  * If the expression isn't simple, there's no point in trying to optimize
8327  * (because the exec_run_select code path will flatten any expanded result
8328  * anyway). Even without that, this seems like a good safety restriction.
8329  */
8330  if (expr->expr_simple_expr == NULL)
8331  return;
8332 
8333  /*
8334  * If target variable isn't referenced by expression, no need to look
8335  * further.
8336  */
8337  if (!bms_is_member(target_dno, expr->paramnos))
8338  return;
8339 
8340  /*
8341  * Top level of expression must be a simple FuncExpr or OpExpr.
8342  */
8343  if (IsA(expr->expr_simple_expr, FuncExpr))
8344  {
8345  FuncExpr *fexpr = (FuncExpr *) expr->expr_simple_expr;
8346 
8347  funcid = fexpr->funcid;
8348  fargs = fexpr->args;
8349  }
8350  else if (IsA(expr->expr_simple_expr, OpExpr))
8351  {
8352  OpExpr *opexpr = (OpExpr *) expr->expr_simple_expr;
8353 
8354  funcid = opexpr->opfuncid;
8355  fargs = opexpr->args;
8356  }
8357  else
8358  return;
8359 
8360  /*
8361  * The top-level function must be one that we trust to be "safe".
8362  * Currently we hard-wire the list, but it would be very desirable to
8363  * allow extensions to mark their functions as safe ...
8364  */
8365  if (!(funcid == F_ARRAY_APPEND ||
8366  funcid == F_ARRAY_PREPEND))
8367  return;
8368 
8369  /*
8370  * The target variable (in the form of a Param) must only appear as a
8371  * direct argument of the top-level function.
8372  */
8373  foreach(lc, fargs)
8374  {
8375  Node *arg = (Node *) lfirst(lc);
8376 
8377  /* A Param is OK, whether it's the target variable or not */
8378  if (arg && IsA(arg, Param))
8379  continue;
8380  /* Otherwise, argument expression must not reference target */
8381  if (contains_target_param(arg, &target_dno))
8382  return;
8383  }
8384 
8385  /* OK, we can pass target as a read-write parameter */
8386  expr->rwparam = target_dno;
8387 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:579
List * args
Definition: primnodes.h:477
Definition: nodes.h:528
unsigned int Oid
Definition: postgres_ext.h:31
Bitmapset * paramnos
Definition: plpgsql.h:223
Oid funcid
Definition: primnodes.h:469
static bool contains_target_param(Node *node, int *target_dno)
Definition: pl_exec.c:8393
Expr * expr_simple_expr
Definition: plpgsql.h:233
int rwparam
Definition: plpgsql.h:224
Oid opfuncid
Definition: primnodes.h:517
#define lfirst(lc)
Definition: pg_list.h:169
void * arg
List * args
Definition: primnodes.h:522
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 8772 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(), PLpgSQL_execstate::readonly_func, SPI_cursor_parse_open_with_paramlist(), SPI_result, and SPI_result_code_string().

Referenced by exec_stmt_dynfors(), and exec_stmt_open().

8777 {
8778  Portal portal;
8779  Datum query;
8780  bool isnull;
8781  Oid restype;
8782  int32 restypmod;
8783  char *querystr;
8784  MemoryContext stmt_mcontext = get_stmt_mcontext(estate);
8785 
8786  /*
8787  * Evaluate the string expression after the EXECUTE keyword. Its result is
8788  * the querystring we have to execute.
8789  */
8790  query = exec_eval_expr(estate, dynquery, &isnull, &restype, &restypmod);
8791  if (isnull)
8792  ereport(ERROR,
8793  (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
8794  errmsg("query string argument of EXECUTE is null")));
8795 
8796  /* Get the C-String representation */
8797  querystr = convert_value_to_string(estate, query, restype);
8798 
8799  /* copy it into the stmt_mcontext before we clean up */
8800  querystr = MemoryContextStrdup(stmt_mcontext, querystr);
8801 
8802  exec_eval_cleanup(estate);
8803 
8804  /*
8805  * Open an implicit cursor for the query. We use
8806  * SPI_cursor_parse_open_with_paramlist even when there are no params,
8807  * because this avoids making and freeing one copy of the plan.
8808  */
8809  portal = SPI_cursor_parse_open_with_paramlist(portalname,
8810  querystr,
8811  exec_eval_using_params(estate,
8812  params),
8813  estate->readonly_func,
8814  cursorOptions);
8815 
8816  if (portal == NULL)
8817  elog(ERROR, "could not open implicit cursor for query \"%s\": %s",
8818  querystr, SPI_result_code_string(SPI_result));
8819 
8820  /* Release transient data */
8821  MemoryContextReset(stmt_mcontext);
8822 
8823  return portal;
8824 }
int errcode(int sqlerrcode)
Definition: elog.c:610
static ParamListInfo exec_eval_using_params(PLpgSQL_execstate *estate, List *params)
Definition: pl_exec.c:8690
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:137
static void exec_eval_cleanup(PLpgSQL_execstate *estate)
Definition: pl_exec.c:4147
unsigned int Oid
Definition: postgres_ext.h:31
signed int int32
Definition: c.h:363
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:5882
const char * SPI_result_code_string(int code)
Definition: spi.c:1815
static MemoryContext get_stmt_mcontext(PLpgSQL_execstate *estate)
Definition: pl_exec.c:1502
uintptr_t Datum
Definition: postgres.h:367
#define ereport(elevel,...)
Definition: elog.h:144
int errmsg(const char *fmt,...)
Definition: elog.c:821
Portal SPI_cursor_parse_open_with_paramlist(const char *name, const char *src, ParamListInfo params, bool read_only, int cursorOptions)
Definition: spi.c:1386
char * MemoryContextStrdup(MemoryContext context, const char *string)
Definition: mcxt.c:1174
#define elog(elevel,...)
Definition: elog.h:214
static char * convert_value_to_string(PLpgSQL_execstate *estate, Datum value, Oid valtype)
Definition: pl_exec.c:7853

◆ exec_eval_boolean()

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

Definition at line 5859 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().

5862 {
5863  Datum exprdatum;
5864  Oid exprtypeid;
5865  int32 exprtypmod;
5866 
5867  exprdatum = exec_eval_expr(estate, expr, isNull, &exprtypeid, &exprtypmod);
5868  exprdatum = exec_cast_value(estate, exprdatum, isNull,
5869  exprtypeid, exprtypmod,
5870  BOOLOID, -1);
5871  return DatumGetBool(exprdatum);
5872 }
unsigned int Oid
Definition: postgres_ext.h:31
signed int int32
Definition: c.h:363
static Datum exec_cast_value(PLpgSQL_execstate *estate, Datum value, bool *isnull, Oid valtype, int32 valtypmod, Oid reqtype, int32 reqtypmod)
Definition: pl_exec.c:7882
static Datum exec_eval_expr(PLpgSQL_execstate *estate, PLpgSQL_expr *expr, bool *isNull, Oid *rettype, int32 *rettypmod)
Definition: pl_exec.c:5882
#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 4147 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().

4148 {
4149  /* Clear result of a full SPI_execute */
4150  if (estate->eval_tuptable != NULL)
4152  estate->eval_tuptable = NULL;
4153 
4154  /*
4155  * Clear result of exec_eval_simple_expr (but keep the econtext). This
4156  * also clears any short-lived allocations done via get_eval_mcontext.
4157  */
4158  if (estate->eval_econtext != NULL)
4160 }
SPITupleTable * eval_tuptable
Definition: plpgsql.h:1107
void SPI_freetuptable(SPITupleTable *tuptable)
Definition: spi.c:1235
ExprContext * eval_econtext
Definition: plpgsql.h:1109
#define ResetExprContext(econtext)
Definition: executor.h:503

◆ 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 5505 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().

5511 {
5512  MemoryContext oldcontext;
5513 
5514  switch (datum->dtype)
5515  {
5516  case PLPGSQL_DTYPE_PROMISE:
5517  /* fulfill promise if needed, then handle like regular var */
5518  plpgsql_fulfill_promise(estate, (PLpgSQL_var *) datum);
5519 
5520  /* FALL THRU */
5521 
5522  case PLPGSQL_DTYPE_VAR:
5523  {
5524  PLpgSQL_var *var = (PLpgSQL_var *) datum;
5525 
5526  *typeid = var->datatype->typoid;
5527  *typetypmod = var->datatype->atttypmod;
5528  *value = var->value;
5529  *isnull = var->isnull;
5530  break;
5531  }
5532 
5533  case PLPGSQL_DTYPE_ROW:
5534  {
5535  PLpgSQL_row *row = (PLpgSQL_row *) datum;
5536  HeapTuple tup;
5537 
5538  /* We get here if there are multiple OUT parameters */
5539  if (!row->rowtupdesc) /* should not happen */
5540  elog(ERROR, "row variable has no tupdesc");
5541  /* Make sure we have a valid type/typmod setting */
5542  BlessTupleDesc(row->rowtupdesc);
5543  oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
5544  tup = make_tuple_from_row(estate, row, row->rowtupdesc);
5545  if (tup == NULL) /* should not happen */
5546  elog(ERROR, "row not compatible with its own tupdesc");
5547  *typeid = row->rowtupdesc->tdtypeid;
5548  *typetypmod = row->rowtupdesc->tdtypmod;
5549  *value = HeapTupleGetDatum(tup);
5550  *isnull = false;
5551  MemoryContextSwitchTo(oldcontext);
5552  break;
5553  }
5554 
5555  case PLPGSQL_DTYPE_REC:
5556  {
5557  PLpgSQL_rec *rec = (PLpgSQL_rec *) datum;
5558 
5559  if (rec->erh == NULL)
5560  {
5561  /* Treat uninstantiated record as a simple NULL */
5562  *value = (Datum) 0;
5563  *isnull = true;
5564  /* Report variable's declared type */
5565  *typeid = rec->rectypeid;
5566  *typetypmod = -1;
5567  }
5568  else
5569  {
5570  if (ExpandedRecordIsEmpty(rec->erh))
5571  {
5572  /* Empty record is also a NULL */
5573  *value = (Datum) 0;
5574  *isnull = true;
5575  }
5576  else
5577  {
5578  *value = ExpandedRecordGetDatum(rec->erh);
5579  *isnull = false;
5580  }
5581  if (rec->rectypeid != RECORDOID)
5582  {
5583  /* Report variable's declared type, if not RECORD */
5584  *typeid = rec->rectypeid;
5585  *typetypmod = -1;
5586  }
5587  else
5588  {
5589  /* Report record's actual type if declared RECORD */
5590  *typeid = rec->erh->er_typeid;
5591  *typetypmod = rec->erh->er_typmod;
5592  }
5593  }
5594  break;
5595  }
5596 
5598  {
5599  PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) datum;
5600  PLpgSQL_rec *rec;
5601  ExpandedRecordHeader *erh;
5602 
5603  rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
5604  erh = rec->erh;
5605 
5606  /*
5607  * If record variable is NULL, instantiate it if it has a
5608  * named composite type, else complain. (This won't change
5609  * the logical state of the record: it's still NULL.)
5610  */
5611  if (erh == NULL)
5612  {
5613  instantiate_empty_record_variable(estate, rec);
5614  erh = rec->erh;
5615  }
5616 
5617  /*
5618  * Look up the field's properties if we have not already, or
5619  * if the tuple descriptor ID changed since last time.
5620  */
5621  if (unlikely(recfield->rectupledescid != erh->er_tupdesc_id))
5622  {
5624  recfield->fieldname,
5625  &recfield->finfo))
5626  ereport(ERROR,
5627  (errcode(ERRCODE_UNDEFINED_COLUMN),
5628  errmsg("record \"%s\" has no field \"%s\"",
5629  rec->refname, recfield->fieldname)));
5630  recfield->rectupledescid = erh->er_tupdesc_id;
5631  }
5632 
5633  /* Report type data. */
5634  *typeid = recfield->finfo.ftypeid;
5635  *typetypmod = recfield->finfo.ftypmod;
5636 
5637  /* And fetch the field value. */
5639  recfield->finfo.fnumber,
5640  isnull);
5641  break;
5642  }
5643 
5644  default:
5645  elog(ERROR, "unrecognized dtype: %d", datum->dtype);
5646  }
5647 }
static HeapTuple make_tuple_from_row(PLpgSQL_execstate *estate, PLpgSQL_row *row, TupleDesc tupdesc)
Definition: pl_exec.c:7499
#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:310
static void plpgsql_fulfill_promise(PLpgSQL_execstate *estate, PLpgSQL_var *var)
Definition: pl_exec.c:1342
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:7818
ExpandedRecordHeader * erh
Definition: plpgsql.h:404
int errcode(int sqlerrcode)
Definition: elog.c:610
PLpgSQL_datum_type dtype
Definition: plpgsql.h:267
char * refname
Definition: plpgsql.h:383
PLpgSQL_datum ** datums
Definition: plpgsql.h:1082
#define ERROR
Definition: elog.h:43
int32 tdtypmod
Definition: tupdesc.h:83
TupleDesc BlessTupleDesc(TupleDesc tupdesc)
Definition: execTuples.c:2052
uint64 rectupledescid
Definition: plpgsql.h:419
#define get_eval_mcontext(estate)
Definition: pl_exec.c:131
uintptr_t Datum
Definition: postgres.h:367
ExpandedRecordFieldInfo finfo
Definition: plpgsql.h:420
Datum value
Definition: plpgsql.h:323
static struct @143 value
#define ereport(elevel,...)
Definition: elog.h:144
#define HeapTupleGetDatum(tuple)
Definition: funcapi.h:221
Oid tdtypeid
Definition: tupdesc.h:82
int errmsg(const char *fmt,...)
Definition: elog.c:821
int32 atttypmod
Definition: plpgsql.h:209
#define elog(elevel,...)
Definition: elog.h:214
TupleDesc rowtupdesc
Definition: plpgsql.h:369
#define unlikely(x)
Definition: c.h:207
Oid rectypeid
Definition: plpgsql.h:397
#define ExpandedRecordGetDatum(erh)
char * fieldname
Definition: plpgsql.h:416
bool isnull
Definition: plpgsql.h:324
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 5882 of file pl_exec.c.

References CURSOR_OPT_PARALLEL_OK, ereport, errcode(), ERRCODE_WRONG_OBJECT_TYPE, 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(), exec_stmt_return_next(), and exec_stmt_return_query().

5887 {
5888  Datum result = 0;
5889  int rc;
5890  Form_pg_attribute attr;
5891 
5892  /*
5893  * If first time through, create a plan for this expression.
5894  */
5895  if (expr->plan == NULL)
5896  exec_prepare_plan(estate, expr, CURSOR_OPT_PARALLEL_OK, true);
5897 
5898  /*
5899  * If this is a simple expression, bypass SPI and use the executor
5900  * directly
5901  */
5902  if (exec_eval_simple_expr(estate, expr,
5903  &result, isNull, rettype, rettypmod))
5904  return result;
5905 
5906  /*
5907  * Else do it the hard way via exec_run_select
5908  */
5909  rc = exec_run_select(estate, expr, 2, NULL);
5910  if (rc != SPI_OK_SELECT)
5911  ereport(ERROR,
5913  errmsg("query \"%s\" did not return data", expr->query)));
5914 
5915  /*
5916  * Check that the expression returns exactly one column...
5917  */
5918  if (estate->eval_tuptable->tupdesc->natts != 1)
5919  ereport(ERROR,
5920  (errcode(ERRCODE_SYNTAX_ERROR),
5921  errmsg_plural("query \"%s\" returned %d column",
5922  "query \"%s\" returned %d columns",
5923  estate->eval_tuptable->tupdesc->natts,
5924  expr->query,
5925  estate->eval_tuptable->tupdesc->natts)));
5926 
5927  /*
5928  * ... and get the column's datatype.
5929  */
5930  attr = TupleDescAttr(estate->eval_tuptable->tupdesc, 0);
5931  *rettype = attr->atttypid;
5932  *rettypmod = attr->atttypmod;
5933 
5934  /*
5935  * If there are no rows selected, the result is a NULL of that type.
5936  */
5937  if (estate->eval_processed == 0)
5938  {
5939  *isNull = true;
5940  return (Datum) 0;
5941  }
5942 
5943  /*
5944  * Check that the expression returned no more than one row.
5945  */
5946  if (estate->eval_processed != 1)
5947  ereport(ERROR,
5948  (errcode(ERRCODE_CARDINALITY_VIOLATION),
5949  errmsg("query \"%s\" returned more than one row",
5950  expr->query)));
5951 
5952  /*
5953  * Return the single result Datum.
5954  */
5955  return SPI_getbinval(estate->eval_tuptable->vals[0],
5956  estate->eval_tuptable->tupdesc, 1, isNull);
5957 }
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:4168
SPITupleTable * eval_tuptable
Definition: plpgsql.h:1107
uint64 eval_processed
Definition: plpgsql.h:1108
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:931
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
int errcode(int sqlerrcode)
Definition: elog.c:610
HeapTuple * vals
Definition: spi.h:26
SPIPlanPtr plan
Definition: plpgsql.h:222
#define ERRCODE_WRONG_OBJECT_TYPE
#define ERROR
Definition: elog.h:43
Datum SPI_getbinval(HeapTuple tuple, TupleDesc tupdesc, int fnumber, bool *isnull)
Definition: spi.c:1101
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:193
uintptr_t Datum
Definition: postgres.h:367
TupleDesc tupdesc
Definition: spi.h:25
#define SPI_OK_SELECT
Definition: spi.h:57
#define ereport(elevel,...)
Definition: elog.h:144
static int exec_run_select(PLpgSQL_execstate *estate, PLpgSQL_expr *expr, long maxtuples, Portal *portalP)
Definition: pl_exec.c:5965
static bool exec_eval_simple_expr(PLpgSQL_execstate *estate, PLpgSQL_expr *expr, Datum *result, bool *isNull, Oid *rettype, int32 *rettypmod)
Definition: pl_exec.c:6200
#define CURSOR_OPT_PARALLEL_OK
Definition: parsenodes.h:2721
int errmsg(const char *fmt,...)
Definition: elog.c:821

◆ exec_eval_integer()

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

Definition at line 5836 of file pl_exec.c.

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

Referenced by exec_assign_value(), and exec_stmt_fetch().

5839 {
5840  Datum exprdatum;
5841  Oid exprtypeid;
5842  int32 exprtypmod;
5843 
5844  exprdatum = exec_eval_expr(estate, expr, isNull, &exprtypeid, &exprtypmod);
5845  exprdatum = exec_cast_value(estate, exprdatum, isNull,
5846  exprtypeid, exprtypmod,
5847  INT4OID, -1);
5848  return DatumGetInt32(exprdatum);
5849 }
#define DatumGetInt32(X)
Definition: postgres.h:472
unsigned int Oid
Definition: postgres_ext.h:31
signed int int32
Definition: c.h:363
static Datum exec_cast_value(PLpgSQL_execstate *estate, Datum value, bool *isnull, Oid valtype, int32 valtypmod, Oid reqtype, int32 reqtypmod)
Definition: pl_exec.c:7882
static Datum exec_eval_expr(PLpgSQL_execstate *estate, PLpgSQL_expr *expr, bool *isNull, Oid *rettype, int32 *rettypmod)
Definition: pl_exec.c:5882
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 6200 of file pl_exec.c.

References Assert, CachedPlanAllowsSimpleValidityCheck(), CachedPlanIsSimplyValid(), CommandCounterIncrement(), CurrentResourceOwner, 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_in_use, PLpgSQL_expr::expr_simple_lxid, PLpgSQL_expr::expr_simple_mutable, PLpgSQL_expr::expr_simple_plan, PLpgSQL_expr::expr_simple_plan_lxid, PLpgSQL_expr::expr_simple_plansource, PLpgSQL_expr::expr_simple_state, PLpgSQL_expr::expr_simple_type, PLpgSQL_expr::expr_simple_typmod, get_eval_mcontext, GetTransactionSnapshot(), InvalidLocalTransactionId, likely, PGPROC::lxid, MemoryContextSwitchTo(), MyProc, PLpgSQL_execstate::paramLI, ParamListInfoData::parserSetupArg, PLpgSQL_expr::plan, PopActiveSnapshot(), PushActiveSnapshot(), PLpgSQL_execstate::readonly_func, ReleaseCachedPlan(), PLpgSQL_expr::rwparam, PLpgSQL_execstate::simple_eval_estate, PLpgSQL_execstate::simple_eval_resowner, SPI_plan_get_cached_plan(), and unlikely.

Referenced by exec_eval_expr().

6206 {
6207  ExprContext *econtext = estate->eval_econtext;
6208  LocalTransactionId curlxid = MyProc->lxid;
6209  ParamListInfo paramLI;
6210  void *save_setup_arg;
6211  bool need_snapshot;
6212  MemoryContext oldcontext;
6213 
6214  /*
6215  * Forget it if expression wasn't simple before.
6216  */
6217  if (expr->expr_simple_expr == NULL)
6218  return false;
6219 
6220  /*
6221  * If expression is in use in current xact, don't touch it.
6222  */
6223  if (unlikely(expr->expr_simple_in_use) &&
6224  expr->expr_simple_lxid == curlxid)
6225  return false;
6226 
6227  /*
6228  * Check to see if the cached plan has been invalidated. If not, and this
6229  * is the first use in the current transaction, save a plan refcount in
6230  * the simple-expression resowner.
6231  */
6233  expr->expr_simple_plan,
6234  (expr->expr_simple_plan_lxid != curlxid ?
6235  estate->simple_eval_resowner : NULL))))
6236  {
6237  /*
6238  * It's still good, so just remember that we have a refcount on the
6239  * plan in the current transaction. (If we already had one, this
6240  * assignment is a no-op.)
6241  */
6242  expr->expr_simple_plan_lxid = curlxid;
6243  }
6244  else
6245  {
6246  /* Need to replan */
6247  CachedPlan *cplan;
6248 
6249  /*
6250  * If we have a valid refcount on some previous version of the plan,
6251  * release it, so we don't leak plans intra-transaction.
6252  */
6253  if (expr->expr_simple_plan_lxid == curlxid)
6254  {
6255  ResourceOwner saveResourceOwner = CurrentResourceOwner;
6256 
6258  ReleaseCachedPlan(expr->expr_simple_plan, true);
6259  CurrentResourceOwner = saveResourceOwner;
6260  expr->expr_simple_plan = NULL;
6262  }
6263 
6264  /* Do the replanning work in the eval_mcontext */
6265  oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
6266  cplan = SPI_plan_get_cached_plan(expr->plan);
6267  MemoryContextSwitchTo(oldcontext);
6268 
6269  /*
6270  * We can't get a failure here, because the number of
6271  * CachedPlanSources in the SPI plan can't change from what
6272  * exec_simple_check_plan saw; it's a property of the raw parsetree
6273  * generated from the query text.
6274  */
6275  Assert(cplan != NULL);
6276 
6277  /*
6278  * This test probably can't fail either, but if it does, cope by
6279  * declaring the plan to be non-simple. On success, we'll acquire a
6280  * refcount on the new plan, stored in simple_eval_resowner.
6281  */
6283  cplan,
6284  estate->simple_eval_resowner))
6285  {
6286  /* Remember that we have the refcount */
6287  expr->expr_simple_plan = cplan;
6288  expr->expr_simple_plan_lxid = curlxid;
6289  }
6290  else
6291  {
6292  /* Release SPI_plan_get_cached_plan's refcount */
6293  ReleaseCachedPlan(cplan, true);
6294  /* Mark expression as non-simple, and fail */
6295  expr->expr_simple_expr = NULL;
6296  return false;
6297  }
6298 
6299  /*
6300  * SPI_plan_get_cached_plan acquired a plan refcount stored in the
6301  * active resowner. We don't need that anymore, so release it.
6302  */
6303  ReleaseCachedPlan(cplan, true);
6304 
6305  /* Extract desired scalar expression from cached plan */
6306  exec_save_simple_expr(expr, cplan);
6307 
6308  /* better recheck r/w safety, as it could change due to inlining */
6309  if (expr->rwparam >= 0)
6310  exec_check_rw_parameter(expr, expr->rwparam);
6311  }
6312 
6313  /*
6314  * Pass back previously-determined result type.
6315  */
6316  *rettype = expr->expr_simple_type;
6317  *rettypmod = expr->expr_simple_typmod;
6318 
6319  /*
6320  * Set up ParamListInfo to pass to executor. For safety, save and restore
6321  * estate->paramLI->parserSetupArg around our use of the param list.
6322  */
6323  paramLI = estate->paramLI;
6324  save_setup_arg = paramLI->parserSetupArg;
6325 
6326  /*
6327  * We can skip using setup_param_list() in favor of just doing this
6328  * unconditionally, because there's no need for the optimization of
6329  * possibly setting ecxt_param_list_info to NULL; we've already forced use
6330  * of a generic plan.
6331  */
6332  paramLI->parserSetupArg = (void *) expr;
6333  econtext->ecxt_param_list_info = paramLI;
6334 
6335  /*
6336  * Prepare the expression for execution, if it's not been done already in
6337  * the current transaction. (This will be forced to happen if we called
6338  * exec_save_simple_expr above.)
6339  */
6340  if (unlikely(expr->expr_simple_lxid != curlxid))
6341  {
6342  oldcontext = MemoryContextSwitchTo(estate->simple_eval_estate->es_query_cxt);
6343  expr->expr_simple_state =
6345  econtext->ecxt_param_list_info);
6346  expr->expr_simple_in_use = false;
6347  expr->expr_simple_lxid = curlxid;
6348  MemoryContextSwitchTo(oldcontext);
6349  }
6350 
6351  /*
6352  * We have to do some of the things SPI_execute_plan would do, in
6353  * particular push a new snapshot so that stable functions within the
6354  * expression can see updates made so far by our own function. However,
6355  * we can skip doing that (and just invoke the expression with the same
6356  * snapshot passed to our function) in some cases, which is useful because
6357  * it's quite expensive relative to the cost of a simple expression. We
6358  * can skip it if the expression contains no stable or volatile functions;
6359  * immutable functions shouldn't need to see our updates. Also, if this
6360  * is a read-only function, we haven't made any updates so again it's okay
6361  * to skip.
6362  */
6363  oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
6364  need_snapshot = (expr->expr_simple_mutable && !estate->readonly_func);
6365  if (need_snapshot)
6366  {
6369  }
6370 
6371  /*
6372  * Mark expression as busy for the duration of the ExecEvalExpr call.
6373  */
6374  expr->expr_simple_in_use = true;
6375 
6376  /*
6377  * Finally we can call the executor to evaluate the expression
6378  */
6379  *result = ExecEvalExpr(expr->expr_simple_state,
6380  econtext,
6381  isNull);
6382 
6383  /* Assorted cleanup */
6384  expr->expr_simple_in_use = false;
6385 
6386  econtext->ecxt_param_list_info = NULL;
6387 
6388  paramLI->parserSetupArg = save_setup_arg;
6389 
6390  if (need_snapshot)
6392 
6393  MemoryContextSwitchTo(oldcontext);
6394 
6395  /*
6396  * That's it.
6397  */
6398  return true;
6399 }
#define likely(x)
Definition: c.h:206
void * parserSetupArg
Definition: params.h:117
static void exec_check_rw_parameter(PLpgSQL_expr *expr, int target_dno)
Definition: pl_exec.c:8316
ResourceOwner simple_eval_resowner
Definition: plpgsql.h:1096
PGPROC * MyProc
Definition: proc.c:67
ResourceOwner CurrentResourceOwner
Definition: resowner.c:142
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void PopActiveSnapshot(void)
Definition: snapmgr.c:759
bool CachedPlanIsSimplyValid(CachedPlanSource *plansource, CachedPlan *plan, ResourceOwner owner)
Definition: plancache.c:1424
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:250
static void exec_save_simple_expr(PLpgSQL_expr *expr, CachedPlan *cplan)
Definition: pl_exec.c:8228
SPIPlanPtr plan
Definition: plpgsql.h:222
CachedPlan * SPI_plan_get_cached_plan(SPIPlanPtr plan)
Definition: spi.c:1908
MemoryContext es_query_cxt
Definition: execnodes.h:559
ParamListInfo paramLI
Definition: plpgsql.h:1092
CachedPlanSource * expr_simple_plansource
Definition: plpgsql.h:244
EState * simple_eval_estate
Definition: plpgsql.h:1095
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:680
static Datum ExecEvalExpr(ExprState *state, ExprContext *econtext, bool *isNull)
Definition: executor.h:292
ExprState * ExecInitExprWithParams(Expr *node, ParamListInfo ext_params)
Definition: execExpr.c:160
void ReleaseCachedPlan(CachedPlan *plan, bool useResOwner)
Definition: plancache.c:1264
Expr * expr_simple_expr
Definition: plpgsql.h:233
uint32 LocalTransactionId
Definition: c.h:523
bool CachedPlanAllowsSimpleValidityCheck(CachedPlanSource *plansource, CachedPlan *plan, ResourceOwner owner)
Definition: plancache.c:1309
int rwparam
Definition: plpgsql.h:224
#define get_eval_mcontext(estate)
Definition: pl_exec.c:131
ExprState * expr_simple_state
Definition: plpgsql.h:254
bool expr_simple_mutable
Definition: plpgsql.h:236
CachedPlan * expr_simple_plan
Definition: plpgsql.h:245
void CommandCounterIncrement(void)
Definition: xact.c:1021
LocalTransactionId expr_simple_lxid
Definition: plpgsql.h:256
#define Assert(condition)
Definition: c.h:746
ExprContext * eval_econtext
Definition: plpgsql.h:1109
int32 expr_simple_typmod
Definition: plpgsql.h:235
#define InvalidLocalTransactionId
Definition: lock.h:68
#define unlikely(x)
Definition: c.h:207
LocalTransactionId expr_simple_plan_lxid
Definition: plpgsql.h:246
bool expr_simple_in_use
Definition: plpgsql.h:255
ParamListInfo ecxt_param_list_info
Definition: execnodes.h:237
Oid expr_simple_type
Definition: plpgsql.h:234
LocalTransactionId lxid
Definition: proc.h:134

◆ exec_eval_using_params()

static ParamListInfo exec_eval_using_params ( PLpgSQL_execstate estate,
List params 
)
static

Definition at line 8690 of file pl_exec.c.

References CStringGetTextDatum, datumCopy(), DatumGetCString, exec_eval_cleanup(), exec_eval_expr(), get_stmt_mcontext(), get_typlenbyval(), i, ParamExternData::isnull, lfirst, list_length(), makeParamList(), MemoryContextSwitchTo(), NIL, PARAM_FLAG_CONST, ParamListInfoData::params, ParamExternData::pflags, ParamExternData::ptype, and ParamExternData::value.

Referenced by exec_dynquery_with_params(), exec_stmt_dynexecute(), and exec_stmt_return_query().

8691 {
8692  ParamListInfo paramLI;
8693  int nargs;
8694  MemoryContext stmt_mcontext;
8695  MemoryContext oldcontext;
8696  int i;
8697  ListCell *lc;
8698 
8699  /* Fast path for no parameters: we can just return NULL */
8700  if (params == NIL)
8701  return NULL;
8702 
8703  nargs = list_length(params);
8704  stmt_mcontext = get_stmt_mcontext(estate);
8705  oldcontext = MemoryContextSwitchTo(stmt_mcontext);
8706  paramLI = makeParamList(nargs);
8707  MemoryContextSwitchTo(oldcontext);
8708 
8709  i = 0;
8710  foreach(lc, params)
8711  {
8712  PLpgSQL_expr *param = (PLpgSQL_expr *) lfirst(lc);
8713  ParamExternData *prm = &paramLI->params[i];
8714  int32 ppdtypmod;
8715 
8716  /*
8717  * Always mark params as const, since we only use the result with
8718  * one-shot plans.
8719  */
8720  prm->pflags = PARAM_FLAG_CONST;
8721 
8722  prm->value = exec_eval_expr(estate, param,
8723  &prm->isnull,
8724  &prm->ptype,
8725  &ppdtypmod);
8726 
8727  oldcontext = MemoryContextSwitchTo(stmt_mcontext);
8728 
8729  if (prm->ptype == UNKNOWNOID)
8730  {
8731  /*
8732  * Treat 'unknown' parameters as text, since that's what most
8733  * people would expect. The SPI functions can coerce unknown
8734  * constants in a more intelligent way, but not unknown Params.
8735  * This code also takes care of copying into the right context.
8736  * Note we assume 'unknown' has the representation of C-string.
8737  */
8738  prm->ptype = TEXTOID;
8739  if (!prm->isnull)
8741  }
8742  /* pass-by-ref non null values must be copied into stmt_mcontext */
8743  else if (!prm->isnull)
8744  {
8745  int16 typLen;
8746  bool typByVal;
8747 
8748  get_typlenbyval(prm->ptype, &typLen, &typByVal);
8749  if (!typByVal)
8750  prm->value = datumCopy(prm->value, typByVal, typLen);
8751  }
8752 
8753  MemoryContextSwitchTo(oldcontext);
8754 
8755  exec_eval_cleanup(estate);
8756 
8757  i++;
8758  }
8759 
8760  return paramLI;
8761 }
signed short int16
Definition: c.h:362
ParamExternData params[FLEXIBLE_ARRAY_MEMBER]
Definition: params.h:125
#define NIL
Definition: pg_list.h:65
Datum value
Definition: params.h:92
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
static void exec_eval_cleanup(PLpgSQL_execstate *estate)
Definition: pl_exec.c:4147
ParamListInfo makeParamList(int numParams)
Definition: params.c:44
signed int int32
Definition: c.h:363
#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:5882
static MemoryContext get_stmt_mcontext(PLpgSQL_execstate *estate)
Definition: pl_exec.c:1502
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition: datum.c:131
#define lfirst(lc)
Definition: pg_list.h:169
uint16 pflags
Definition: params.h:94
static int list_length(const List *l)
Definition: pg_list.h:149
void get_typlenbyval(Oid typid, int16 *typlen, bool *typbyval)
Definition: lsyscache.c:2139
int i
#define CStringGetTextDatum(s)
Definition: builtins.h:86
bool isnull
Definition: params.h:93
#define PARAM_FLAG_CONST
Definition: params.h:88

◆ exec_for_query()

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

Definition at line 6029 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().

6031 {
6032  PLpgSQL_variable *var;
6033  SPITupleTable *tuptab;
6034  bool found = false;
6035  int rc = PLPGSQL_RC_OK;
6036  uint64 previous_id = INVALID_TUPLEDESC_IDENTIFIER;
6037  bool tupdescs_match = true;
6038  uint64 n;
6039 
6040  /* Fetch loop variable's datum entry */
6041  var = (PLpgSQL_variable *) estate->datums[stmt->var->dno];
6042 
6043  /*
6044  * Make sure the portal doesn't get closed by the user statements we
6045  * execute.
6046  */
6047  PinPortal(portal);
6048 
6049  /*
6050  * Fetch the initial tuple(s). If prefetching is allowed then we grab a
6051  * few more rows to avoid multiple trips through executor startup
6052  * overhead.
6053  */
6054  SPI_cursor_fetch(portal, true, prefetch_ok ? 10 : 1);
6055  tuptab = SPI_tuptable;
6056  n = SPI_processed;
6057 
6058  /*
6059  * If the query didn't return any rows, set the target to NULL and fall
6060  * through with found = false.
6061  */
6062  if (n == 0)
6063  {
6064  exec_move_row(estate, var, NULL, tuptab->tupdesc);
6065  exec_eval_cleanup(estate);
6066  }
6067  else
6068  found = true; /* processed at least one tuple */
6069 
6070  /*
6071  * Now do the loop
6072  */
6073  while (n > 0)
6074  {
6075  uint64 i;
6076 
6077  for (i = 0; i < n; i++)
6078  {
6079  /*
6080  * Assign the tuple to the target. Here, because we know that all
6081  * loop iterations should be assigning the same tupdesc, we can
6082  * optimize away repeated creations of expanded records with
6083  * identical tupdescs. Testing for changes of er_tupdesc_id is
6084  * reliable even if the loop body contains assignments that
6085  * replace the target's value entirely, because it's assigned from
6086  * a process-global counter. The case where the tupdescs don't
6087  * match could possibly be handled more efficiently than this
6088  * coding does, but it's not clear extra effort is worthwhile.
6089  */
6090  if (var->dtype == PLPGSQL_DTYPE_REC)
6091  {
6092  PLpgSQL_rec *rec = (PLpgSQL_rec *) var;
6093 
6094  if (rec->erh &&
6095  rec->erh->er_tupdesc_id == previous_id &&
6096  tupdescs_match)
6097  {
6098  /* Only need to assign a new tuple value */
6099  expanded_record_set_tuple(rec->erh, tuptab->vals[i],
6100  true, !estate->atomic);
6101  }
6102  else
6103  {
6104  /*
6105  * First time through, or var's tupdesc changed in loop,
6106  * or we have to do it the hard way because type coercion
6107  * is needed.
6108  */
6109  exec_move_row(estate, var,
6110  tuptab->vals[i], tuptab->tupdesc);
6111 
6112  /*
6113  * Check to see if physical assignment is OK next time.
6114  * Once the tupdesc comparison has failed once, we don't
6115  * bother rechecking in subsequent loop iterations.
6116  */
6117  if (tupdescs_match)
6118  {
6119  tupdescs_match =
6120  (rec->rectypeid == RECORDOID ||
6121  rec->rectypeid == tuptab->tupdesc->tdtypeid ||
6122  compatible_tupdescs(tuptab->tupdesc,
6124  }
6125  previous_id = rec->erh->er_tupdesc_id;
6126  }
6127  }
6128  else
6129  exec_move_row(estate, var, tuptab->vals[i], tuptab->tupdesc);
6130 
6131  exec_eval_cleanup(estate);
6132 
6133  /*
6134  * Execute the statements
6135  */
6136  rc = exec_stmts(estate, stmt->body);
6137 
6138  LOOP_RC_PROCESSING(stmt->label, goto loop_exit);
6139  }
6140 
6141  SPI_freetuptable(tuptab);
6142 
6143  /*
6144  * Fetch more tuples. If prefetching is allowed, grab 50 at a time.
6145  */
6146  SPI_cursor_fetch(portal, true, prefetch_ok ? 50 : 1);
6147  tuptab = SPI_tuptable;
6148  n = SPI_processed;
6149  }
6150 
6151 loop_exit:
6152 
6153  /*
6154  * Release last group of tuples (if any)
6155  */
6156  SPI_freetuptable(tuptab);
6157 
6158  UnpinPortal(portal);
6159 
6160  /*
6161  * Set the FOUND variable to indicate the result of executing the loop
6162  * (namely, whether we looped one or more times). This must be set last so
6163  * that it does not interfere with the value of the FOUND variable inside
6164  * the loop processing itself.
6165  */
6166  exec_set_found(estate, found);
6167 
6168  return rc;
6169 }
void UnpinPortal(Portal portal)
Definition: portalmem.c:379
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:404
static void exec_eval_cleanup(PLpgSQL_execstate *estate)
Definition: pl_exec.c:4147
HeapTuple * vals
Definition: spi.h:26
#define INVALID_TUPLEDESC_IDENTIFIER
Definition: typcache.h:148
uint64 SPI_processed
Definition: spi.c:45
PLpgSQL_datum ** datums
Definition: plpgsql.h:1082
void PinPortal(Portal portal)
Definition: portalmem.c:370
#define LOOP_RC_PROCESSING(looplabel, exit_action)
Definition: pl_exec.c:198
static TupleDesc expanded_record_get_tupdesc(ExpandedRecordHeader *erh)
void SPI_freetuptable(SPITupleTable *tuptable)
Definition: spi.c:1235
static bool compatible_tupdescs(TupleDesc src_tupdesc, TupleDesc dst_tupdesc)
Definition: pl_exec.c:7455
TupleDesc tupdesc
Definition: spi.h:25
PLpgSQL_datum_type dtype
Definition: plpgsql.h:279
PLpgSQL_variable * var
Definition: plpgsql.h:717
static void exec_set_found(PLpgSQL_execstate *estate, bool state)
Definition: pl_exec.c:8415
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:6911
int i
void SPI_cursor_fetch(Portal portal, bool forward, long count)
Definition: spi.c:1649
Oid rectypeid
Definition: plpgsql.h:397
static int exec_stmts(PLpgSQL_execstate *estate, List *stmts)
Definition: pl_exec.c:1947

◆ exec_init_tuple_store()

static void exec_init_tuple_store ( PLpgSQL_execstate estate)
static

Definition at line 3691 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().

3692 {
3693  ReturnSetInfo *rsi = estate->rsi;
3694  MemoryContext oldcxt;
3695  ResourceOwner oldowner;
3696 
3697  /*
3698  * Check caller can handle a set result in the way we want
3699  */
3700  if (!rsi || !IsA(rsi, ReturnSetInfo) ||
3701  (rsi->allowedModes & SFRM_Materialize) == 0 ||
3702  rsi->expectedDesc == NULL)
3703  ereport(ERROR,
3704  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3705  errmsg("set-valued function called in context that cannot accept a set")));
3706 
3707  /*
3708  * Switch to the right memory context and resource owner for storing the
3709  * tuplestore for return set. If we're within a subtransaction opened for
3710  * an exception-block, for example, we must still create the tuplestore in
3711  * the resource owner that was active when this function was entered, and
3712  * not in the subtransaction resource owner.
3713  */
3714  oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
3715  oldowner = CurrentResourceOwner;
3717 
3718  estate->tuple_store =
3720  false, work_mem);
3721 
3722  CurrentResourceOwner = oldowner;
3723  MemoryContextSwitchTo(oldcxt);
3724 
3725  estate->tuple_store_desc = rsi->expectedDesc;
3726 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:579
ResourceOwner tuple_store_owner
Definition: plpgsql.h:1070
ResourceOwner CurrentResourceOwner
Definition: resowner.c:142
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
int errcode(int sqlerrcode)
Definition: elog.c:610
TupleDesc expectedDesc
Definition: execnodes.h:303
TupleDesc tuple_store_desc
Definition: plpgsql.h:1068
#define ERROR
Definition: elog.h:43
MemoryContext tuple_store_cxt
Definition: plpgsql.h:1069
ReturnSetInfo * rsi
Definition: plpgsql.h:1071
Tuplestorestate * tuple_store
Definition: plpgsql.h:1067
Tuplestorestate * tuplestore_begin_heap(bool randomAccess, bool interXact, int maxKBytes)
Definition: tuplestore.c:318
int work_mem
Definition: globals.c:121
#define ereport(elevel,...)
Definition: elog.h:144
int allowedModes
Definition: execnodes.h:304
int errmsg(const char *fmt,...)
Definition: elog.c:821

◆ exec_move_row()

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

Definition at line 6911 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().

6914 {
6915  ExpandedRecordHeader *newerh = NULL;
6916 
6917  /*
6918  * If target is RECORD, we may be able to avoid field-by-field processing.
6919  */
6920  if (target->dtype == PLPGSQL_DTYPE_REC)
6921  {
6922  PLpgSQL_rec *rec = (PLpgSQL_rec *) target;
6923 
6924  /*
6925  * If we have no source tupdesc, just set the record variable to NULL.
6926  * (If we have a source tupdesc but not a tuple, we'll set the
6927  * variable to a row of nulls, instead. This is odd perhaps, but
6928  * backwards compatible.)
6929  */
6930  if (tupdesc == NULL)
6931  {
6932  if (rec->datatype &&
6933  rec->datatype->typtype == TYPTYPE_DOMAIN)
6934  {
6935  /*
6936  * If it's a composite domain, NULL might not be a legal
6937  * value, so we instead need to make an empty expanded record
6938  * and ensure that domain type checking gets done. If there
6939  * is already an expanded record, piggyback on its lookups.
6940  */
6941  newerh = make_expanded_record_for_rec(estate, rec,
6942  NULL, rec->erh);
6943  expanded_record_set_tuple(newerh, NULL, false, false);
6944  assign_record_var(estate, rec, newerh);
6945  }
6946  else
6947  {
6948  /* Just clear it to NULL */
6949  if (rec->erh)
6951  rec->erh = NULL;
6952  }
6953  return;
6954  }
6955 
6956  /*
6957  * Build a new expanded record with appropriate tupdesc.
6958  */
6959  newerh = make_expanded_record_for_rec(estate, rec, tupdesc, NULL);
6960 
6961  /*
6962  * If the rowtypes match, or if we have no tuple anyway, we can
6963  * complete the assignment without field-by-field processing.
6964  *
6965  * The tests here are ordered more or less in order of cheapness. We
6966  * can easily detect it will work if the target is declared RECORD or
6967  * has the same typeid as the source. But when assigning from a query
6968  * result, it's common to have a source tupdesc that's labeled RECORD
6969  * but is actually physically compatible with a named-composite-type
6970  * target, so it's worth spending extra cycles to check for that.
6971  */
6972  if (rec->rectypeid == RECORDOID ||
6973  rec->rectypeid == tupdesc->tdtypeid ||
6974  !HeapTupleIsValid(tup) ||
6976  {
6977  if (!HeapTupleIsValid(tup))
6978  {
6979  /* No data, so force the record into all-nulls state */
6981  }
6982  else
6983  {
6984  /* No coercion is needed, so just assign the row value */
6985  expanded_record_set_tuple(newerh, tup, true, !estate->atomic);
6986  }
6987 
6988  /* Complete the assignment */
6989  assign_record_var(estate, rec, newerh);
6990 
6991  return;
6992  }
6993  }
6994 
6995  /*
6996  * Otherwise, deconstruct the tuple and do field-by-field assignment,
6997  * using exec_move_row_from_fields.
6998  */
6999  if (tupdesc && HeapTupleIsValid(tup))
7000  {
7001  int td_natts = tupdesc->natts;
7002  Datum *values;
7003  bool *nulls;
7004  Datum values_local[64];
7005  bool nulls_local[64];
7006 
7007  /*
7008  * Need workspace arrays. If td_natts is small enough, use local
7009  * arrays to save doing a palloc. Even if it's not small, we can
7010  * allocate both the Datum and isnull arrays in one palloc chunk.
7011  */
7012  if (td_natts <= lengthof(values_local))
7013  {
7014  values = values_local;
7015  nulls = nulls_local;
7016  }
7017  else
7018  {
7019  char *chunk;
7020 
7021  chunk = eval_mcontext_alloc(estate,
7022  td_natts * (sizeof(Datum) + sizeof(bool)));
7023  values = (Datum *) chunk;
7024  nulls = (bool *) (chunk + td_natts * sizeof(Datum));
7025  }
7026 
7027  heap_deform_tuple(tup, tupdesc, values, nulls);
7028 
7029  exec_move_row_from_fields(estate, target, newerh,
7030  values, nulls, tupdesc);
7031  }
7032  else
7033  {
7034  /*
7035  * Assign all-nulls.
7036  */
7037  exec_move_row_from_fields(estate, target, newerh,
7038  NULL, NULL, NULL);
7039  }
7040 }
PLpgSQL_type * datatype
Definition: plpgsql.h:396
static void assign_record_var(PLpgSQL_execstate *estate, PLpgSQL_rec *rec, ExpandedRecordHeader *erh)
Definition: pl_exec.c:8667
void expanded_record_set_tuple(ExpandedRecordHeader *erh, HeapTuple tuple, bool copy, bool expand_external)
ExpandedRecordHeader * erh
Definition: plpgsql.h:404
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:7189
#define lengthof(array)
Definition: c.h:676
static ExpandedRecordHeader * make_expanded_record_for_rec(PLpgSQL_execstate *estate, PLpgSQL_rec *rec, TupleDesc srctupdesc, ExpandedRecordHeader *srcerh)
Definition: pl_exec.c:7126
#define eval_mcontext_alloc(estate, sz)
Definition: pl_exec.c:133
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:7455
void DeleteExpandedObject(Datum d)
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
PLpgSQL_datum_type dtype
Definition: plpgsql.h:279
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:165
Oid tdtypeid
Definition: tupdesc.h:82
Oid rectypeid
Definition: plpgsql.h:397
#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 7585 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().

7588 {
7589  /* Check to see if source is an expanded record */
7591  {
7593  ExpandedRecordHeader *newerh = NULL;
7594 
7595  Assert(erh->er_magic == ER_MAGIC);
7596 
7597  /* These cases apply if the target is record not row... */
7598  if (target->dtype == PLPGSQL_DTYPE_REC)
7599  {
7600  PLpgSQL_rec *rec = (PLpgSQL_rec *) target;
7601 
7602  /*
7603  * If it's the same record already stored in the variable, do
7604  * nothing. This would happen only in silly cases like "r := r",
7605  * but we need some check to avoid possibly freeing the variable's
7606  * live value below. Note that this applies even if what we have
7607  * is a R/O pointer.
7608  */
7609  if (erh == rec->erh)
7610  return;
7611 
7612  /*
7613  * Make sure rec->rectypeid is up-to-date before using it.
7614  */
7615  revalidate_rectypeid(rec);
7616 
7617  /*
7618  * If we have a R/W pointer, we're allowed to just commandeer
7619  * ownership of the expanded record. If it's of the right type to
7620  * put into the record variable, do that. (Note we don't accept
7621  * an expanded record of a composite-domain type as a RECORD
7622  * value. We'll treat it as the base composite type instead;
7623  * compare logic in make_expanded_record_for_rec.)
7624  */
7626  (rec->rectypeid == erh->er_decltypeid ||
7627  (rec->rectypeid == RECORDOID &&
7628  !ExpandedRecordIsDomain(erh))))
7629  {
7630  assign_record_var(estate, rec, erh);
7631  return;
7632  }
7633 
7634  /*
7635  * If we already have an expanded record object in the target
7636  * variable, and the source record contains a valid tuple
7637  * representation with the right rowtype, then we can skip making
7638  * a new expanded record and just assign the tuple with
7639  * expanded_record_set_tuple. (We can't do the equivalent if we
7640  * have to do field-by-field assignment, since that wouldn't be
7641  * atomic if there's an error.) We consider that there's a
7642  * rowtype match only if it's the same named composite type or
7643  * same registered rowtype; checking for matches of anonymous
7644  * rowtypes would be more expensive than this is worth.
7645  */
7646  if (rec->erh &&
7647  (erh->flags & ER_FLAG_FVALUE_VALID) &&
7648  erh->er_typeid == rec->erh->er_typeid &&
7649  (erh->er_typeid != RECORDOID ||
7650  (erh->er_typmod == rec->erh->er_typmod &&
7651  erh->er_typmod >= 0)))
7652  {
7654  true, !estate->atomic);
7655  return;
7656  }
7657 
7658  /*
7659  * Otherwise we're gonna need a new expanded record object. Make
7660  * it here in hopes of piggybacking on the source object's
7661  * previous typcache lookup.
7662  */
7663  newerh = make_expanded_record_for_rec(estate, rec, NULL, erh);
7664 
7665  /*
7666  * If the expanded record contains a valid tuple representation,
7667  * and we don't need rowtype conversion, then just copying the
7668  * tuple is probably faster than field-by-field processing. (This
7669  * isn't duplicative of the previous check, since here we will
7670  * catch the case where the record variable was previously empty.)
7671  */
7672  if ((erh->flags & ER_FLAG_FVALUE_VALID) &&
7673  (rec->rectypeid == RECORDOID ||
7674  rec->rectypeid == erh->er_typeid))
7675  {
7676  expanded_record_set_tuple(newerh, erh->fvalue,
7677  true, !estate->atomic);
7678  assign_record_var(estate, rec, newerh);
7679  return;
7680  }
7681 
7682  /*
7683  * Need to special-case empty source record, else code below would
7684  * leak newerh.
7685  */
7686  if (ExpandedRecordIsEmpty(erh))
7687  {
7688  /* Set newerh to a row of NULLs */
7690  assign_record_var(estate, rec, newerh);
7691  return;
7692  }
7693  } /* end of record-target-only cases */
7694 
7695  /*
7696  * If the source expanded record is empty, we should treat that like a
7697  * NULL tuple value. (We're unlikely to see such a case, but we must
7698  * check this; deconstruct_expanded_record would cause a change of
7699  * logical state, which is not OK.)
7700  */
7701  if (ExpandedRecordIsEmpty(erh))
7702  {
7703  exec_move_row(estate, target, NULL,
7705  return;
7706  }
7707 
7708  /*
7709  * Otherwise, ensure that the source record is deconstructed, and
7710  * assign from its field values.
7711  */
7713  exec_move_row_from_fields(estate, target, newerh,
7714  erh->dvalues, erh->dnulls,
7716  }
7717  else
7718  {
7719  /*
7720  * Nope, we've got a plain composite Datum. Deconstruct it; but we
7721  * don't use deconstruct_composite_datum(), because we may be able to
7722  * skip calling lookup_rowtype_tupdesc().
7723  */
7724  HeapTupleHeader td;
7725  HeapTupleData tmptup;
7726  Oid tupType;
7727  int32 tupTypmod;
7728  TupleDesc tupdesc;
7729  MemoryContext oldcontext;
7730 
7731  /* Ensure that any detoasted data winds up in the eval_mcontext */
7732  oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
7733  /* Get tuple body (note this could involve detoasting) */
7735  MemoryContextSwitchTo(oldcontext);
7736 
7737  /* Build a temporary HeapTuple control structure */
7738  tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
7739  ItemPointerSetInvalid(&(tmptup.t_self));
7740  tmptup.t_tableOid = InvalidOid;
7741  tmptup.t_data = td;
7742 
7743  /* Extract rowtype info */
7744  tupType = HeapTupleHeaderGetTypeId(td);
7745  tupTypmod = HeapTupleHeaderGetTypMod(td);
7746 
7747  /* Now, if the target is record not row, maybe we can optimize ... */
7748  if (target->dtype == PLPGSQL_DTYPE_REC)
7749  {
7750  PLpgSQL_rec *rec = (PLpgSQL_rec *) target;
7751 
7752  /*
7753  * If we already have an expanded record object in the target
7754  * variable, and the source datum has a matching rowtype, then we
7755  * can skip making a new expanded record and just assign the tuple
7756  * with expanded_record_set_tuple. We consider that there's a
7757  * rowtype match only if it's the same named composite type or
7758  * same registered rowtype. (Checking to reject an anonymous
7759  * rowtype here should be redundant, but let's be safe.)
7760  */
7761  if (rec->erh &&
7762  tupType == rec->erh->er_typeid &&
7763  (tupType != RECORDOID ||
7764  (tupTypmod == rec->erh->er_typmod &&
7765  tupTypmod >= 0)))
7766  {
7767  expanded_record_set_tuple(rec->erh, &tmptup,
7768  true, !estate->atomic);
7769  return;
7770  }
7771 
7772  /*
7773  * If the source datum has a rowtype compatible with the target
7774  * variable, just build a new expanded record and assign the tuple
7775  * into it. Using make_expanded_record_from_typeid() here saves
7776  * one typcache lookup compared to the code below.
7777  */
7778  if (rec->rectypeid == RECORDOID || rec->rectypeid == tupType)
7779  {
7780  ExpandedRecordHeader *newerh;
7781  MemoryContext mcontext = get_eval_mcontext(estate);
7782 
7783  newerh = make_expanded_record_from_typeid(tupType, tupTypmod,
7784  mcontext);
7785  expanded_record_set_tuple(newerh, &tmptup,
7786  true, !estate->atomic);
7787  assign_record_var(estate, rec, newerh);
7788  return;
7789  }
7790 
7791  /*
7792  * Otherwise, we're going to need conversion, so fall through to
7793  * do it the hard way.
7794  */
7795  }
7796 
7797  /*
7798  * ROW target, or unoptimizable RECORD target, so we have to expend a
7799  * lookup to obtain the source datum's tupdesc.
7800  */
7801  tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
7802 
7803  /* Do the move */
7804  exec_move_row(estate, target, &tmptup, tupdesc);
7805 
7806  /* Release tupdesc usage count */
7807  ReleaseTupleDesc(tupdesc);
7808  }
7809 }
#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:1710
static void assign_record_var(PLpgSQL_execstate *estate, PLpgSQL_rec *rec, ExpandedRecordHeader *erh)
Definition: pl_exec.c:8667
void expanded_record_set_tuple(ExpandedRecordHeader *erh, HeapTuple tuple, bool copy, bool expand_external)
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
ExpandedRecordHeader * erh
Definition: plpgsql.h:404
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:7189
unsigned int Oid
Definition: postgres_ext.h:31
#define DatumGetHeapTupleHeader(X)
Definition: fmgr.h:294
signed int int32
Definition: c.h:363
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:7126
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:131
#define ER_MAGIC
#define HeapTupleHeaderGetTypeId(tup)
Definition: htup_details.h:458
#define InvalidOid
Definition: postgres_ext.h:36
static struct @143 value
#define Assert(condition)
Definition: c.h:746
PLpgSQL_datum_type dtype
Definition: plpgsql.h:279
#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:6911
static void revalidate_rectypeid(PLpgSQL_rec *rec)
Definition: pl_exec.c:7046
#define VARATT_IS_EXTERNAL_EXPANDED_RW(PTR)
Definition: postgres.h:320
Oid rectypeid
Definition: plpgsql.h:397
#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 7189 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().

7194 {
7195  int td_natts = tupdesc ? tupdesc->natts : 0;
7196  int fnum;
7197  int anum;
7198  int strict_multiassignment_level = 0;
7199 
7200  /*
7201  * The extra check strict strict_multi_assignment can be active, only when
7202  * input tupdesc is specified.
7203  */
7204  if (tupdesc != NULL)
7205  {
7207  strict_multiassignment_level = ERROR;
7208  else if (plpgsql_extra_warnings & PLPGSQL_XCHECK_STRICTMULTIASSIGNMENT)
7209  strict_multiassignment_level = WARNING;
7210  }
7211 
7212  /* Handle RECORD-target case */
7213  if (target->dtype == PLPGSQL_DTYPE_REC)
7214  {
7215  PLpgSQL_rec *rec = (PLpgSQL_rec *) target;
7216  TupleDesc var_tupdesc;
7217  Datum newvalues_local[64];
7218  bool newnulls_local[64];
7219 
7220  Assert(newerh != NULL); /* caller must have built new object */
7221 
7222  var_tupdesc = expanded_record_get_tupdesc(newerh);
7223 
7224  /*
7225  * Coerce field values if needed. This might involve dealing with
7226  * different sets of dropped columns and/or coercing individual column
7227  * types. That's sort of a pain, but historically plpgsql has allowed
7228  * it, so we preserve the behavior. However, it's worth a quick check
7229  * to see if the tupdescs are identical. (Since expandedrecord.c
7230  * prefers to use refcounted tupdescs from the typcache, expanded
7231  * records with the same rowtype will have pointer-equal tupdescs.)
7232  */
7233  if (var_tupdesc != tupdesc)
7234  {
7235  int vtd_natts = var_tupdesc->natts;
7236  Datum *newvalues;
7237  bool *newnulls;
7238 
7239  /*
7240  * Need workspace arrays. If vtd_natts is small enough, use local
7241  * arrays to save doing a palloc. Even if it's not small, we can
7242  * allocate both the Datum and isnull arrays in one palloc chunk.
7243  */
7244  if (vtd_natts <= lengthof(newvalues_local))
7245  {
7246  newvalues = newvalues_local;
7247  newnulls = newnulls_local;
7248  }
7249  else
7250  {
7251  char *chunk;
7252 
7253  chunk = eval_mcontext_alloc(estate,
7254  vtd_natts * (sizeof(Datum) + sizeof(bool)));
7255  newvalues = (Datum *) chunk;
7256  newnulls = (bool *) (chunk + vtd_natts * sizeof(Datum));
7257  }
7258 
7259  /* Walk over destination columns */
7260  anum = 0;
7261  for (fnum = 0; fnum < vtd_natts; fnum++)
7262  {
7263  Form_pg_attribute attr = TupleDescAttr(var_tupdesc, fnum);
7264  Datum value;
7265  bool isnull;
7266  Oid valtype;
7267  int32 valtypmod;
7268 
7269  if (attr->attisdropped)
7270  {
7271  /* expanded_record_set_fields should ignore this column */
7272  continue; /* skip dropped column in record */
7273  }
7274 
7275  while (anum < td_natts &&
7276  TupleDescAttr(tupdesc, anum)->attisdropped)
7277  anum++; /* skip dropped column in tuple */
7278 
7279  if (anum < td_natts)
7280  {
7281  value = values[anum];
7282  isnull = nulls[anum];
7283  valtype = TupleDescAttr(tupdesc, anum)->atttypid;
7284  valtypmod = TupleDescAttr(tupdesc, anum)->atttypmod;
7285  anum++;
7286  }
7287  else
7288  {
7289  /* no source for destination column */
7290  value = (Datum) 0;
7291  isnull = true;
7292  valtype = UNKNOWNOID;
7293  valtypmod = -1;
7294 
7295  /* When source value is missing */
7296  if (strict_multiassignment_level)
7297  ereport(strict_multiassignment_level,
7298  (errcode(ERRCODE_DATATYPE_MISMATCH),
7299  errmsg("number of source and target fields in assignment does not match"),
7300  /* translator: %s represents a name of an extra check */
7301  errdetail("%s check of %s is active.",
7302  "strict_multi_assignment",
7303  strict_multiassignment_level == ERROR ? "extra_errors" :
7304  "extra_warnings"),
7305  errhint("Make sure the query returns the exact list of columns.")));
7306  }
7307 
7308  /* Cast the new value to the right type, if needed. */
7309  newvalues[fnum] = exec_cast_value(estate,
7310  value,
7311  &isnull,
7312  valtype,
7313  valtypmod,
7314  attr->atttypid,
7315  attr->atttypmod);
7316  newnulls[fnum] = isnull;
7317  }
7318 
7319  /*
7320  * When strict_multiassignment extra check is active, then ensure
7321  * there are no unassigned source attributes.
7322  */
7323  if (strict_multiassignment_level && anum < td_natts)
7324  {
7325  /* skip dropped columns in the source descriptor */
7326  while (anum < td_natts &&
7327  TupleDescAttr(tupdesc, anum)->attisdropped)
7328  anum++;
7329 
7330  if (anum < td_natts)
7331  ereport(strict_multiassignment_level,
7332  (errcode(ERRCODE_DATATYPE_MISMATCH),
7333  errmsg("number of source and target fields in assignment does not match"),
7334  /* translator: %s represents a name of an extra check */
7335  errdetail("%s check of %s is active.",
7336  "strict_multi_assignment",
7337  strict_multiassignment_level == ERROR ? "extra_errors" :
7338  "extra_warnings"),
7339  errhint("Make sure the query returns the exact list of columns.")));
7340  }
7341 
7342  values = newvalues;
7343  nulls = newnulls;
7344  }
7345 
7346  /* Insert the coerced field values into the new expanded record */
7347  expanded_record_set_fields(newerh, values, nulls, !estate->atomic);
7348 
7349  /* Complete the assignment */
7350  assign_record_var(estate, rec, newerh);
7351 
7352  return;
7353  }
7354 
7355  /* newerh should not have been passed in non-RECORD cases */
7356  Assert(newerh == NULL);
7357 
7358  /*
7359  * For a row, we assign the individual field values to the variables the
7360  * row points to.
7361  *
7362  * NOTE: both this code and the record code above silently ignore extra
7363  * columns in the source and assume NULL for missing columns. This is
7364  * pretty dubious but it's the historical behavior.
7365  *
7366  * If we have no input data at all, we'll assign NULL to all columns of
7367  * the row variable.
7368  */
7369  if (target->dtype == PLPGSQL_DTYPE_ROW)
7370  {
7371  PLpgSQL_row *row = (PLpgSQL_row *) target;
7372 
7373  anum = 0;
7374  for (fnum = 0; fnum < row->nfields; fnum++)
7375  {
7376  PLpgSQL_var *var;
7377  Datum value;
7378  bool isnull;
7379  Oid valtype;
7380  int32 valtypmod;
7381 
7382  var = (PLpgSQL_var *) (estate->datums[row->varnos[fnum]]);
7383 
7384  while (anum < td_natts &&
7385  TupleDescAttr(tupdesc, anum)->attisdropped)
7386  anum++; /* skip dropped column in tuple */
7387 
7388  if (anum < td_natts)
7389  {
7390  value = values[anum];
7391  isnull = nulls[anum];
7392  valtype = TupleDescAttr(tupdesc, anum)->atttypid;
7393  valtypmod = TupleDescAttr(tupdesc, anum)->atttypmod;
7394  anum++;
7395  }
7396  else
7397  {
7398  /* no source for destination column */
7399  value = (Datum) 0;
7400  isnull = true;
7401  valtype = UNKNOWNOID;
7402  valtypmod = -1;
7403 
7404  if (strict_multiassignment_level)
7405  ereport(strict_multiassignment_level,
7406  (errcode(ERRCODE_DATATYPE_MISMATCH),
7407  errmsg("number of source and target fields in assignment does not match"),
7408  /* translator: %s represents a name of an extra check */
7409  errdetail("%s check of %s is active.",
7410  "strict_multi_assignment",
7411  strict_multiassignment_level == ERROR ? "extra_errors" :
7412  "extra_warnings"),
7413  errhint("Make sure the query returns the exact list of columns.")));
7414  }
7415 
7416  exec_assign_value(estate, (PLpgSQL_datum *) var,
7417  value, isnull, valtype, valtypmod);
7418  }
7419 
7420  /*
7421  * When strict_multiassignment extra check is active, ensure there are
7422  * no unassigned source attributes.
7423  */
7424  if (strict_multiassignment_level && anum < td_natts)
7425  {
7426  while (anum < td_natts &&
7427  TupleDescAttr(tupdesc, anum)->attisdropped)
7428  anum++; /* skip dropped column in tuple */
7429 
7430  if (anum < td_natts)
7431  ereport(strict_multiassignment_level,
7432  (errcode(ERRCODE_DATATYPE_MISMATCH),
7433  errmsg("number of source and target fields in assignment does not match"),
7434  /* translator: %s represents a name of an extra check */
7435  errdetail("%s check of %s is active.",
7436  "strict_multi_assignment",
7437  strict_multiassignment_level == ERROR ? "extra_errors" :
7438  "extra_warnings"),
7439  errhint("Make sure the query returns the exact list of columns.")));
7440  }
7441 
7442  return;
7443  }
7444 
7445  elog(ERROR, "unsupported target type: %d", target->dtype);
7446 }
int errhint(const char *fmt,...)
Definition: elog.c:1068
static void assign_record_var(PLpgSQL_execstate *estate, PLpgSQL_rec *rec, ExpandedRecordHeader *erh)
Definition: pl_exec.c:8667
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
#define PLPGSQL_XCHECK_STRICTMULTIASSIGNMENT
Definition: plpgsql.h:1209
int plpgsql_extra_errors
Definition: pl_handler.c:53
int errcode(int sqlerrcode)
Definition: elog.c:610
void expanded_record_set_fields(ExpandedRecordHeader *erh, const Datum *newValues, const bool *isnulls, bool expand_external)
#define lengthof(array)
Definition: c.h:676
unsigned int Oid
Definition: postgres_ext.h:31
signed int int32
Definition: c.h:363
PLpgSQL_datum ** datums
Definition: plpgsql.h:1082
static Datum exec_cast_value(PLpgSQL_execstate *estate, Datum value, bool *isnull, Oid valtype, int32 valtypmod, Oid reqtype, int32 reqtypmod)
Definition: pl_exec.c:7882
#define ERROR
Definition: elog.h:43
#define eval_mcontext_alloc(estate, sz)
Definition: pl_exec.c:133
int plpgsql_extra_warnings
Definition: pl_handler.c:52
int errdetail(const char *fmt,...)
Definition: elog.c:954
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:193
static TupleDesc expanded_record_get_tupdesc(ExpandedRecordHeader *erh)
int * varnos
Definition: plpgsql.h:373
#define WARNING
Definition: elog.h:40
uintptr_t Datum
Definition: postgres.h:367
static struct @143 value
#define ereport(elevel,...)
Definition: elog.h:144
#define Assert(condition)
Definition: c.h:746
int nfields
Definition: plpgsql.h:371
PLpgSQL_datum_type dtype
Definition: plpgsql.h:279
static Datum values[MAXATTR]
Definition: bootstrap.c:165
int errmsg(const char *fmt,...)
Definition: elog.c:821
#define elog(elevel,...)
Definition: elog.h:214
static void exec_assign_value(PLpgSQL_execstate *estate, PLpgSQL_datum *target, Datum value, bool isNull, Oid valtype, int32 valtypmod)
Definition: pl_exec.c:5086

◆ exec_prepare_plan()

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

Definition at line 4168 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(), exec_stmt_return_query(), and exec_stmt_set().

4171 {
4172  SPIPlanPtr plan;
4173 
4174  /*
4175  * The grammar can't conveniently set expr->func while building the parse
4176  * tree, so make sure it's set before parser hooks need it.
4177  */
4178  expr->func = estate->func;
4179 
4180  /*
4181  * Generate and save the plan
4182  */
4183  plan = SPI_prepare_params(expr->query,
4185  (void *) expr,
4186  cursorOptions);
4187  if (plan == NULL)
4188  elog(ERROR, "SPI_prepare_params failed for \"%s\": %s",
4190  if (keepplan)
4191  SPI_keepplan(plan);
4192  expr->plan = plan;
4193 
4194  /* Check to see if it's a simple expression */
4195  exec_simple_check_plan(estate, expr);
4196 
4197  /*
4198  * Mark expression as not using a read-write param. exec_assign_value has
4199  * to take steps to override this if appropriate; that seems cleaner than
4200  * adding parameters to all other callers.
4201  */
4202  expr->rwparam = -1;
4203 }
char * query
Definition: plpgsql.h:221
PLpgSQL_function * func
Definition: plpgsql.h:1047
static void exec_simple_check_plan(PLpgSQL_execstate *estate, PLpgSQL_expr *expr)
Definition: pl_exec.c:8111
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:1815
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:1075
int SPI_keepplan(SPIPlanPtr plan)
Definition: spi.c:825
int rwparam
Definition: plpgsql.h:224
struct PLpgSQL_function * func
Definition: plpgsql.h:227
#define elog(elevel,...)
Definition: elog.h:214
SPIPlanPtr SPI_prepare_params(const char *src, ParserSetupHook parserSetup, void *parserSetupArg, int cursorOptions)
Definition: spi.c:788

◆ exec_run_select()

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

Definition at line 5965 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(), and exec_stmt_perform().

5967 {
5968  ParamListInfo paramLI;
5969  int rc;
5970 
5971  /*
5972  * On the first call for this expression generate the plan.
5973  *
5974  * If we don't need to return a portal, then we're just going to execute
5975  * the query once, which means it's OK to use a parallel plan, even if the
5976  * number of rows being fetched is limited. If we do need to return a
5977  * portal, the caller might do cursor operations, which parallel query
5978  * can't support.
5979  */
5980  if (expr->plan == NULL)
5981  exec_prepare_plan(estate, expr,
5982  portalP == NULL ? CURSOR_OPT_PARALLEL_OK : 0, true);
5983 
5984  /*
5985  * Set up ParamListInfo to pass to executor
5986  */
5987  paramLI = setup_param_list(estate, expr);
5988 
5989  /*
5990  * If a portal was requested, put the query and paramlist into the portal
5991  */
5992  if (portalP != NULL)
5993  {
5994  *portalP = SPI_cursor_open_with_paramlist(NULL, expr->plan,
5995  paramLI,
5996  estate->readonly_func);
5997  if (*portalP == NULL)
5998  elog(ERROR, "could not open implicit cursor for query \"%s\": %s",
6000  exec_eval_cleanup(estate);
6001  return SPI_OK_CURSOR;
6002  }
6003 
6004  /*
6005  * Execute the query
6006  */
6007  rc = SPI_execute_plan_with_paramlist(expr->plan, paramLI,
6008  estate->readonly_func, maxtuples);
6009  if (rc != SPI_OK_SELECT)
6010  ereport(ERROR,
6011  (errcode(ERRCODE_SYNTAX_ERROR),
6012  errmsg("query \"%s\" is not a SELECT", expr->query)));
6013 
6014  /* Save query results for eventual cleanup */
6015  Assert(estate->eval_tuptable == NULL);
6016  estate->eval_tuptable = SPI_tuptable;
6017  estate->eval_processed = SPI_processed;
6018 
6019  return rc;
6020 }
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:4168
SPITupleTable * eval_tuptable
Definition: plpgsql.h:1107
uint64 eval_processed
Definition: plpgsql.h:1108
Portal SPI_cursor_open_with_paramlist(const char *name, SPIPlanPtr plan, ParamListInfo params, bool read_only)
Definition: spi.c:1373
SPITupleTable * SPI_tuptable
Definition: spi.c:46
int errcode(int sqlerrcode)
Definition: elog.c:610
static void exec_eval_cleanup(PLpgSQL_execstate *estate)
Definition: pl_exec.c:4147
#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:566
const char * SPI_result_code_string(int code)
Definition: spi.c:1815
static ParamListInfo setup_param_list(PLpgSQL_execstate *estate, PLpgSQL_expr *expr)
Definition: pl_exec.c:6418
#define SPI_OK_SELECT
Definition: spi.h:57
#define ereport(elevel,...)
Definition: elog.h:144
#define Assert(condition)
Definition: c.h:746
#define CURSOR_OPT_PARALLEL_OK
Definition: parsenodes.h:2721
int errmsg(const char *fmt,...)
Definition: elog.c:821
#define elog(elevel,...)
Definition: elog.h:214

◆ exec_save_simple_expr()

static void exec_save_simple_expr ( PLpgSQL_expr expr,
CachedPlan cplan 
)
static

Definition at line 8228 of file pl_exec.c.

References Assert, castNode, CMD_SELECT, PlannedStmt::commandType, contain_mutable_functions(), elog, ERROR, PLpgSQL_expr::expr_simple_expr, PLpgSQL_expr::expr_simple_in_use, PLpgSQL_expr::expr_simple_lxid, PLpgSQL_expr::expr_simple_mutable, PLpgSQL_expr::expr_simple_state, PLpgSQL_expr::expr_simple_type, PLpgSQL_expr::expr_simple_typmod, exprType(), exprTypmod(), 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().

8229 {
8230  PlannedStmt *stmt;
8231  Plan *plan;
8232  Expr *tle_expr;
8233 
8234  /*
8235  * Given the checks that exec_simple_check_plan did, none of the Asserts
8236  * here should ever fail.
8237  */
8238 
8239  /* Extract the single PlannedStmt */
8240  Assert(list_length(cplan->stmt_list) == 1);
8241  stmt = linitial_node(PlannedStmt, cplan->stmt_list);
8242  Assert(stmt->commandType == CMD_SELECT);
8243 
8244  /*
8245  * Ordinarily, the plan node should be a simple Result. However, if
8246  * force_parallel_mode is on, the planner might've stuck a Gather node
8247  * atop that. The simplest way to deal with this is to look through the
8248  * Gather node. The Gather node's tlist would normally contain a Var
8249  * referencing the child node's output, but it could also be a Param, or
8250  * it could be a Const that setrefs.c copied as-is.
8251  */
8252  plan = stmt->planTree;
8253  for (;;)
8254  {
8255  /* Extract the single tlist expression */
8256  Assert(list_length(plan->targetlist) == 1);
8257  tle_expr = castNode(TargetEntry, linitial(plan->targetlist))->expr;
8258 
8259  if (IsA(plan, Result))
8260  {
8261  Assert(plan->lefttree == NULL &&
8262  plan->righttree == NULL &&
8263  plan->initPlan == NULL &&
8264  plan->qual == NULL &&
8265  ((Result *) plan)->resconstantqual == NULL);
8266  break;
8267  }
8268  else if (IsA(plan, Gather))
8269  {
8270  Assert(plan->lefttree != NULL &&
8271  plan->righttree == NULL &&
8272  plan->initPlan == NULL &&
8273  plan->qual == NULL);
8274  /* If setrefs.c copied up a Const, no need to look further */
8275  if (IsA(tle_expr, Const))
8276  break;
8277  /* Otherwise, it had better be a Param or an outer Var */
8278  Assert(IsA(tle_expr, Param) || (IsA(tle_expr, Var) &&
8279  ((Var *) tle_expr)->varno == OUTER_VAR));
8280  /* Descend to the child node */
8281  plan = plan->lefttree;
8282  }
8283  else
8284  elog(ERROR, "unexpected plan node type: %d",
8285  (int) nodeTag(plan));
8286  }
8287 
8288  /*
8289  * Save the simple expression, and initialize state to "not valid in
8290  * current transaction".
8291  */
8292  expr->expr_simple_expr = tle_expr;
8293  expr->expr_simple_state = NULL;
8294  expr->expr_simple_in_use = false;
8296  /* Also stash away the expression result type */
8297  expr->expr_simple_type = exprType((Node *) tle_expr);
8298  expr->expr_simple_typmod = exprTypmod((Node *) tle_expr);
8299  /* We also want to remember if it is immutable or not */
8300  expr->expr_simple_mutable = contain_mutable_functions((Node *) tle_expr);
8301 }
List * qual
Definition: plannodes.h:137
#define IsA(nodeptr, _type_)
Definition: nodes.h:579
#define castNode(_type_, nodeptr)
Definition: nodes.h:597
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:275
Definition: nodes.h:528
Definition: primnodes.h:181
#define linitial_node(type, l)
Definition: pg_list.h:177
struct Plan * planTree
Definition: plannodes.h:64
struct Plan * righttree
Definition: plannodes.h:139
#define linitial(l)
Definition: pg_list.h:174
#define ERROR
Definition: elog.h:43
Expr * expr_simple_expr
Definition: plpgsql.h:233
ExprState * expr_simple_state
Definition: plpgsql.h:254
bool expr_simple_mutable
Definition: plpgsql.h:236
CmdType commandType
Definition: plannodes.h:46
LocalTransactionId expr_simple_lxid
Definition: plpgsql.h:256
#define Assert(condition)
Definition: c.h:746
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:41
static int list_length(const List *l)
Definition: pg_list.h:149
struct Plan * lefttree
Definition: plannodes.h:138
#define nodeTag(nodeptr)
Definition: nodes.h:533
List * targetlist
Definition: plannodes.h:136
int32 expr_simple_typmod
Definition: plpgsql.h:235
List * initPlan
Definition: plannodes.h:140
#define elog(elevel,...)
Definition: elog.h:214
#define InvalidLocalTransactionId
Definition: lock.h:68
bool contain_mutable_functions(Node *clause)
Definition: clauses.c:645
List * stmt_list
Definition: plancache.h:150
bool expr_simple_in_use
Definition: plpgsql.h:255
#define OUTER_VAR
Definition: primnodes.h:172
Oid expr_simple_type
Definition: plpgsql.h:234

◆ exec_set_found()

static void exec_set_found ( PLpgSQL_execstate estate,
bool  state 
)
static

Definition at line 8415 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().

8416 {
8417  PLpgSQL_var *var;
8418 
8419  var = (PLpgSQL_var *) (estate->datums[estate->found_varno]);
8420  assign_simple_var(estate, var, BoolGetDatum(state), false, false);
8421 }
static void assign_simple_var(PLpgSQL_execstate *estate, PLpgSQL_var *var, Datum newvalue, bool isnull, bool freeable)
Definition: pl_exec.c:8591
PLpgSQL_datum ** datums
Definition: plpgsql.h:1082
#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 8111 of file pl_exec.c.

References Assert, CachedPlanAllowsSimpleValidityCheck(), CMD_SELECT, Query::commandType, Query::cteList, Query::distinctClause, exec_save_simple_expr(), PLpgSQL_expr::expr_simple_expr, PLpgSQL_expr::expr_simple_plan, PLpgSQL_expr::expr_simple_plan_lxid, PLpgSQL_expr::expr_simple_plansource, 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(), PGPROC::lxid, MemoryContextSwitchTo(), MyProc, NIL, PLpgSQL_expr::plan, FromExpr::quals, CachedPlanSource::query_list, ReleaseCachedPlan(), Query::rtable, Query::setOperations, PLpgSQL_execstate::simple_eval_resowner, Query::sortClause, SPI_plan_get_cached_plan(), SPI_plan_get_plan_sources(), Query::targetList, and Query::windowClause.

Referenced by exec_prepare_plan().

8112 {
8113  List *plansources;
8114  CachedPlanSource *plansource;
8115  Query *query;
8116  CachedPlan *cplan;
8117  MemoryContext oldcontext;
8118 
8119  /*
8120  * Initialize to "not simple".
8121  */
8122  expr->expr_simple_expr = NULL;
8123 
8124  /*
8125  * Check the analyzed-and-rewritten form of the query to see if we will be
8126  * able to treat it as a simple expression. Since this function is only
8127  * called immediately after creating the CachedPlanSource, we need not
8128  * worry about the query being stale.
8129  */
8130 
8131  /*
8132  * We can only test queries that resulted in exactly one CachedPlanSource
8133  */
8134  plansources = SPI_plan_get_plan_sources(expr->plan);
8135  if (list_length(plansources) != 1)
8136  return;
8137  plansource = (CachedPlanSource *) linitial(plansources);
8138 
8139  /*
8140  * 1. There must be one single querytree.
8141  */
8142  if (list_length(plansource->query_list) != 1)
8143  return;
8144  query = (Query *) linitial(plansource->query_list);
8145 
8146  /*
8147  * 2. It must be a plain SELECT query without any input tables
8148  */
8149  if (!IsA(query, Query))
8150  return;
8151  if (query->commandType != CMD_SELECT)
8152  return;
8153  if (query->rtable != NIL)
8154  return;
8155 
8156  /*
8157  * 3. Can't have any subplans, aggregates, qual clauses either. (These
8158  * tests should generally match what inline_function() checks before
8159  * inlining a SQL function; otherwise, inlining could change our
8160  * conclusion about whether an expression is simple, which we don't want.)
8161  */
8162  if (query->hasAggs ||
8163  query->hasWindowFuncs ||
8164  query->hasTargetSRFs ||
8165  query->hasSubLinks ||
8166  query->cteList ||
8167  query->jointree->fromlist ||
8168  query->jointree->quals ||
8169  query->groupClause ||
8170  query->groupingSets ||
8171  query->havingQual ||
8172  query->windowClause ||
8173  query->distinctClause ||
8174  query->sortClause ||
8175  query->limitOffset ||
8176  query->limitCount ||
8177  query->setOperations)
8178  return;
8179 
8180  /*
8181  * 4. The query must have a single attribute as result
8182  */
8183  if (list_length(query->targetList) != 1)
8184  return;
8185 
8186  /*
8187  * OK, we can treat it as a simple plan.
8188  *
8189  * Get the generic plan for the query. If replanning is needed, do that
8190  * work in the eval_mcontext.
8191  */
8192  oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
8193  cplan = SPI_plan_get_cached_plan(expr->plan);
8194  MemoryContextSwitchTo(oldcontext);
8195 
8196  /* Can't fail, because we checked for a single CachedPlanSource above */
8197  Assert(cplan != NULL);
8198 
8199  /*
8200  * Verify that plancache.c thinks the plan is simple enough to use
8201  * CachedPlanIsSimplyValid. Given the restrictions above, it's unlikely
8202  * that this could fail, but if it does, just treat plan as not simple. On
8203  * success, save a refcount on the plan in the simple-expression resowner.
8204  */
8205  if (CachedPlanAllowsSimpleValidityCheck(plansource, cplan,
8206  estate->simple_eval_resowner))
8207  {
8208  /* Remember that we have the refcount */
8209  expr->expr_simple_plansource = plansource;
8210  expr->expr_simple_plan = cplan;
8212 
8213  /* Share the remaining work with the replan code path */
8214  exec_save_simple_expr(expr, cplan);
8215  }
8216 
8217  /*
8218  * Release the plan refcount obtained by SPI_plan_get_cached_plan. (This
8219  * refcount is held by the wrong resowner, so we can't just repurpose it.)
8220  */
8221  ReleaseCachedPlan(cplan, true);
8222 }
Node * limitOffset
Definition: parsenodes.h:160
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:579
List * sortClause
Definition: parsenodes.h:158
ResourceOwner simple_eval_resowner
Definition: plpgsql.h:1096
FromExpr * jointree
Definition: parsenodes.h:138
PGPROC * MyProc
Definition: proc.c:67
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:1513
Node * quals
Definition: primnodes.h:1514
static void exec_save_simple_expr(PLpgSQL_expr *expr, CachedPlan *cplan)
Definition: pl_exec.c:8228
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:1908
#define linitial(l)
Definition: pg_list.h:174
List * rtable
Definition: parsenodes.h:137
List * distinctClause
Definition: parsenodes.h:156
CachedPlanSource * expr_simple_plansource
Definition: plpgsql.h:244
Node * limitCount
Definition: parsenodes.h:161
void ReleaseCachedPlan(CachedPlan *plan, bool useResOwner)
Definition: plancache.c:1264
Expr * expr_simple_expr
Definition: plpgsql.h:233
bool CachedPlanAllowsSimpleValidityCheck(CachedPlanSource *plansource, CachedPlan *plan, ResourceOwner owner)
Definition: plancache.c:1309
#define get_eval_mcontext(estate)
Definition: pl_exec.c:131
CachedPlan * expr_simple_plan
Definition: plpgsql.h:245
CmdType commandType
Definition: parsenodes.h:112
bool hasTargetSRFs
Definition: parsenodes.h:127
#define Assert(condition)
Definition: c.h:746
bool hasWindowFuncs
Definition: parsenodes.h:126
static int list_length(const List *l)
Definition: pg_list.h:149
List * cteList
Definition: parsenodes.h:135
Node * setOperations
Definition: parsenodes.h:166
List * groupClause
Definition: parsenodes.h:148
bool hasSubLinks
Definition: parsenodes.h:128
List * SPI_plan_get_plan_sources(SPIPlanPtr plan)
Definition: spi.c:1892
List * query_list
Definition: plancache.h:111
LocalTransactionId expr_simple_plan_lxid
Definition: plpgsql.h:246
Node * havingQual
Definition: parsenodes.h:152
Definition: pg_list.h:50
LocalTransactionId lxid
Definition: proc.h:134

◆ exec_stmt_assert()

static int exec_stmt_assert ( PLpgSQL_execstate estate,
PLpgSQL_stmt_assert stmt 
)
static

Definition at line 3954 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_stmts().

3955 {
3956  bool value;
3957  bool isnull;
3958 
3959  /* do nothing when asserts are not enabled */
3960  if (!plpgsql_check_asserts)
3961  return PLPGSQL_RC_OK;
3962 
3963  value = exec_eval_boolean(estate, stmt->cond, &isnull);
3964  exec_eval_cleanup(estate);
3965 
3966  if (isnull || !value)
3967  {
3968  char *message = NULL;
3969 
3970  if (stmt->message != NULL)
3971  {
3972  Datum val;
3973  Oid typeid;
3974  int32 typmod;
3975 
3976  val = exec_eval_expr(estate, stmt->message,
3977  &isnull, &typeid, &typmod);
3978  if (!isnull)
3979  message = convert_value_to_string(estate, val, typeid);
3980  /* we mustn't do exec_eval_cleanup here */
3981  }
3982 
3983  ereport(ERROR,
3984  (errcode(ERRCODE_ASSERT_FAILURE),
3985  message ? errmsg_internal("%s", message) :
3986  errmsg("assertion failed")));
3987  }
3988 
3989  return PLPGSQL_RC_OK;
3990 }
int errcode(int sqlerrcode)
Definition: elog.c:610
static void exec_eval_cleanup(PLpgSQL_execstate *estate)
Definition: pl_exec.c:4147
unsigned int Oid
Definition: postgres_ext.h:31
signed int int32
Definition: c.h:363
#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:5882
PLpgSQL_expr * message
Definition: plpgsql.h:910
static bool exec_eval_boolean(PLpgSQL_execstate *estate, PLpgSQL_expr *expr, bool *isNull)
Definition: pl_exec.c:5859
uintptr_t Datum
Definition: postgres.h:367
static struct @143 value
#define ereport(elevel,...)
Definition: elog.h:144
int errmsg_internal(const char *fmt,...)
Definition: elog.c:908
int errmsg(const char *fmt,...)
Definition: elog.c:821
static char * convert_value_to_string(PLpgSQL_execstate *estate, Datum value, Oid valtype)
Definition: pl_exec.c:7853
PLpgSQL_expr * cond
Definition: plpgsql.h:909
bool plpgsql_check_asserts
Definition: pl_handler.c:48
long val
Definition: informix.c:664

◆ exec_stmt_assign()

static int exec_stmt_assign ( PLpgSQL_execstate estate,
PLpgSQL_stmt_assign stmt 
)
static

Definition at line 2119 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_stmts().

2120 {
2121  Assert(stmt->varno >= 0);
2122 
2123  exec_assign_expr(estate, estate->datums[stmt->varno], stmt->expr);
2124 
2125  return PLPGSQL_RC_OK;
2126 }
PLpgSQL_datum ** datums
Definition: plpgsql.h:1082
static void exec_assign_expr(PLpgSQL_execstate *estate, PLpgSQL_datum *target, PLpgSQL_expr *expr)
Definition: pl_exec.c:5021
#define Assert(condition)
Definition: c.h:746
PLpgSQL_expr * expr
Definition: plpgsql.h:534

◆ exec_stmt_block()

static int exec_stmt_block ( PLpgSQL_execstate estate,
PLpgSQL_stmt_block block 
)
static

Definition at line 1621 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_stmts(), and exec_toplevel_block().

1622 {
1623  volatile int rc = -1;
1624  int i;
1625 
1626  /*
1627  * First initialize all variables declared in this block
1628  */
1629  estate->err_text = gettext_noop("during statement block local variable initialization");
1630 
1631  for (i = 0; i < block->n_initvars; i++)
1632  {
1633  int n = block->initvarnos[i];
1634  PLpgSQL_datum *datum = estate->datums[n];
1635 
1636  /*
1637  * The set of dtypes handled here must match plpgsql_add_initdatums().
1638  *
1639  * Note that we currently don't support promise datums within blocks,
1640  * only at a function's outermost scope, so we needn't handle those
1641  * here.
1642  */
1643  switch (datum->dtype)
1644  {
1645  case PLPGSQL_DTYPE_VAR:
1646  {
1647  PLpgSQL_var *var = (PLpgSQL_var *) datum;
1648 
1649  /*
1650  * Free any old value, in case re-entering block, and
1651  * initialize to NULL
1652  */
1653  assign_simple_var(estate, var, (Datum) 0, true, false);
1654 
1655  if (var->default_val == NULL)
1656  {
1657  /*
1658  * If needed, give the datatype a chance to reject
1659  * NULLs, by assigning a NULL to the variable. We
1660  * claim the value is of type UNKNOWN, not the var's
1661  * datatype, else coercion will be skipped.
1662  */
1663  if (var->datatype->typtype == TYPTYPE_DOMAIN)
1664  exec_assign_value(estate,
1665  (PLpgSQL_datum *) var,
1666  (Datum) 0,
1667  true,
1668  UNKNOWNOID,
1669  -1);
1670 
1671  /* parser should have rejected NOT NULL */
1672  Assert(!var->notnull);
1673  }
1674  else
1675  {
1676  exec_assign_expr(estate, (PLpgSQL_datum *) var,
1677  var->default_val);
1678  }
1679  }
1680  break;
1681 
1682  case PLPGSQL_DTYPE_REC:
1683  {
1684  PLpgSQL_rec *rec = (PLpgSQL_rec *) datum;
1685 
1686  /*
1687  * Deletion of any existing object will be handled during
1688  * the assignments below, and in some cases it's more
1689  * efficient for us not to get rid of it beforehand.
1690  */
1691  if (rec->default_val == NULL)
1692  {
1693  /*
1694  * If needed, give the datatype a chance to reject
1695  * NULLs, by assigning a NULL to the variable.
1696  */
1697  exec_move_row(estate, (PLpgSQL_variable *) rec,
1698  NULL, NULL);
1699 
1700  /* parser should have rejected NOT NULL */
1701  Assert(!rec->notnull);
1702  }
1703  else
1704  {
1705  exec_assign_expr(estate, (PLpgSQL_datum *) rec,
1706  rec->default_val);
1707  }
1708  }
1709  break;
1710 
1711  default:
1712  elog(ERROR, "unrecognized dtype: %d", datum->dtype);
1713  }
1714  }
1715 
1716  if (block->exceptions)
1717  {
1718  /*
1719  * Execute the statements in the block's body inside a sub-transaction
1720  */
1721  MemoryContext oldcontext = CurrentMemoryContext;
1723  ExprContext *old_eval_econtext = estate->eval_econtext;
1724  ErrorData *save_cur_error = estate->cur_error;
1725  MemoryContext stmt_mcontext;
1726 
1727  estate->err_text = gettext_noop("during statement block entry");
1728 
1729  /*
1730  * We will need a stmt_mcontext to hold the error data if an error
1731  * occurs. It seems best to force it to exist before entering the
1732  * subtransaction, so that we reduce the risk of out-of-memory during
1733  * error recovery, and because this greatly simplifies restoring the
1734  * stmt_mcontext stack to the correct state after an error. We can
1735  * ameliorate the cost of this by allowing the called statements to
1736  * use this mcontext too; so we don't push it down here.
1737  */
1738  stmt_mcontext = get_stmt_mcontext(estate);
1739 
1741  /* Want to run statements inside function's memory context */
1742  MemoryContextSwitchTo(oldcontext);
1743 
1744  PG_TRY();
1745  {
1746  /*
1747  * We need to run the block's statements with a new eval_econtext
1748  * that belongs to the current subtransaction; if we try to use
1749  * the outer econtext then ExprContext shutdown callbacks will be
1750  * called at the wrong times.
1751  */
1752  plpgsql_create_econtext(estate);
1753 
1754  estate->err_text = NULL;
1755 
1756  /* Run the block's statements */
1757  rc = exec_stmts(estate, block->body);
1758 
1759  estate->err_text = gettext_noop("during statement block exit");
1760 
1761  /*
1762  * If the block ended with RETURN, we may need to copy the return
1763  * value out of the subtransaction eval_context. We can avoid a
1764  * physical copy if the value happens to be a R/W expanded object.
1765  */
1766  if (rc == PLPGSQL_RC_RETURN &&
1767  !estate->retisset &&
1768  !estate->retisnull)
1769  {
1770  int16 resTypLen;
1771  bool resTypByVal;
1772 
1773  get_typlenbyval(estate->rettype, &resTypLen, &resTypByVal);
1774  estate->retval = datumTransfer(estate->retval,
1775  resTypByVal, resTypLen);
1776  }
1777 
1778  /* Commit the inner transaction, return to outer xact context */
1780  MemoryContextSwitchTo(oldcontext);
1781  CurrentResourceOwner = oldowner;
1782 
1783  /* Assert that the stmt_mcontext stack is unchanged */
1784  Assert(stmt_mcontext == estate->stmt_mcontext);
1785 
1786  /*
1787  * Revert to outer eval_econtext. (The inner one was
1788  * automatically cleaned up during subxact exit.)
1789  */
1790  estate->eval_econtext = old_eval_econtext;
1791  }
1792  PG_CATCH();
1793  {
1794  ErrorData *edata;
1795  ListCell *e;
1796 
1797  estate->err_text = gettext_noop("during exception cleanup");
1798 
1799  /* Save error info in our stmt_mcontext */
1800  MemoryContextSwitchTo(stmt_mcontext);
1801  edata = CopyErrorData();
1802  FlushErrorState();
1803 
1804  /* Abort the inner transaction */
1806  MemoryContextSwitchTo(oldcontext);
1807  CurrentResourceOwner = oldowner;
1808 
1809  /*
1810  * Set up the stmt_mcontext stack as though we had restored our
1811  * previous state and then done push_stmt_mcontext(). The push is
1812  * needed so that statements in the exception handler won't
1813  * clobber the error data that's in our stmt_mcontext.
1814  */
1815  estate->stmt_mcontext_parent = stmt_mcontext;
1816  estate->stmt_mcontext = NULL;
1817 
1818  /*
1819  * Now we can delete any nested stmt_mcontexts that might have
1820  * been created as children of ours. (Note: we do not immediately
1821  * release any statement-lifespan data that might have been left
1822  * behind in stmt_mcontext itself. We could attempt that by doing
1823  * a MemoryContextReset on it before collecting the error data
1824  * above, but it seems too risky to do any significant amount of
1825  * work before collecting the error.)
1826  */
1827  MemoryContextDeleteChildren(stmt_mcontext);
1828 
1829  /* Revert to outer eval_econtext */
1830  estate->eval_econtext = old_eval_econtext;
1831 
1832  /*
1833  * Must clean up the econtext too. However, any tuple table made
1834  * in the subxact will have been thrown away by SPI during subxact
1835  * abort, so we don't need to (and mustn't try to) free the
1836  * eval_tuptable.
1837  */
1838  estate->eval_tuptable = NULL;
1839  exec_eval_cleanup(estate);
1840 
1841  /* Look for a matching exception handler */
1842  foreach(e, block->exceptions->exc_list)
1843  {
1844  PLpgSQL_exception *exception = (PLpgSQL_exception *) lfirst(e);
1845 
1846  if (exception_matches_conditions(edata, exception->conditions))
1847  {
1848  /*
1849  * Initialize the magic SQLSTATE and SQLERRM variables for
1850  * the exception block; this also frees values from any
1851  * prior use of the same exception. We needn't do this
1852  * until we have found a matching exception.
1853  */
1854  PLpgSQL_var *state_var;
1855  PLpgSQL_var *errm_var;
1856 
1857  state_var = (PLpgSQL_var *)
1858  estate->datums[block->exceptions->sqlstate_varno];
1859  errm_var = (PLpgSQL_var *)
1860  estate->datums[block->exceptions->sqlerrm_varno];
1861 
1862  assign_text_var(estate, state_var,
1863  unpack_sql_state(edata->sqlerrcode));
1864  assign_text_var(estate, errm_var, edata->message);
1865 
1866  /*
1867  * Also set up cur_error so the error data is accessible
1868  * inside the handler.
1869  */
1870  estate->cur_error = edata;
1871 
1872  estate->err_text = NULL;
1873 
1874  rc = exec_stmts(estate, exception->action);
1875 
1876  break;
1877  }
1878  }
1879 
1880  /*
1881  * Restore previous state of cur_error, whether or not we executed
1882  * a handler. This is needed in case an error got thrown from
1883  * some inner block's exception handler.
1884  */
1885  estate->cur_error = save_cur_error;
1886 
1887  /* If no match found, re-throw the error */
1888  if (e == NULL)
1889  ReThrowError(edata);
1890 
1891  /* Restore stmt_mcontext stack and release the error data */
1892  pop_stmt_mcontext(estate);
1893  MemoryContextReset(stmt_mcontext);
1894  }
1895  PG_END_TRY();
1896 
1897  Assert(save_cur_error == estate->cur_error);
1898  }
1899  else
1900  {
1901  /*
1902  * Just execute the statements in the block's body
1903  */
1904  estate->err_text = NULL;
1905 
1906  rc = exec_stmts(estate, block->body);
1907  }
1908 
1909  estate->err_text = NULL;
1910 
1911  /*
1912  * Handle the return code. This is intentionally different from
1913  * LOOP_RC_PROCESSING(): CONTINUE never matches a block, and EXIT matches
1914  * a block only if there is a label match.
1915  */
1916  switch (rc)
1917  {
1918  case PLPGSQL_RC_OK:
1919  case PLPGSQL_RC_RETURN:
1920  case PLPGSQL_RC_CONTINUE:
1921  return rc;
1922 
1923  case PLPGSQL_RC_EXIT:
1924  if (estate->exitlabel == NULL)
1925  return PLPGSQL_RC_EXIT;
1926  if (block->label == NULL)
1927  return PLPGSQL_RC_EXIT;
1928  if (strcmp(block->label, estate->exitlabel) != 0)
1929  return PLPGSQL_RC_EXIT;
1930  estate->exitlabel = NULL;
1931  return PLPGSQL_RC_OK;
1932 
1933  default:
1934  elog(ERROR, "unrecognized rc: %d", rc);
1935  }
1936 
1937  return PLPGSQL_RC_OK;
1938 }
signed short int16
Definition: c.h:362
SPITupleTable * eval_tuptable
Definition: plpgsql.h:1107
int sqlerrcode
Definition: elog.h:364
ErrorData * CopyErrorData(void)
Definition: elog.c:1471
ResourceOwner CurrentResourceOwner
Definition: resowner.c:142
void ReleaseCurrentSubTransaction(void)
Definition: xact.c:4479
char * unpack_sql_state(int sql_state)
Definition: elog.c:2890
PLpgSQL_type * datatype
Definition: plpgsql.h:310
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define gettext_noop(x)
Definition: c.h:1139
static void assign_simple_var(PLpgSQL_execstate *estate, PLpgSQL_var *var, Datum newvalue, bool isnull, bool freeable)
Definition: pl_exec.c:8591
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:137
static void exec_eval_cleanup(PLpgSQL_execstate *estate)
Definition: pl_exec.c:4147
PLpgSQL_datum_type dtype
Definition: plpgsql.h:267
void FlushErrorState(void)
Definition: elog.c:1565
PLpgSQL_datum ** datums
Definition: plpgsql.h:1082
static void exec_assign_expr(PLpgSQL_execstate *estate, PLpgSQL_datum *target, PLpgSQL_expr *expr)
Definition: pl_exec.c:5021
#define ERROR
Definition: elog.h:43
PLpgSQL_expr * default_val
Definition: plpgsql.h:307
void RollbackAndReleaseCurrentSubTransaction(void)
Definition: xact.c:4513
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
static MemoryContext get_stmt_mcontext(PLpgSQL_execstate *estate)
Definition: pl_exec.c:1502
static bool exception_matches_conditions(ErrorData *edata, PLpgSQL_condition *cond)
Definition: pl_exec.c:1553
void MemoryContextDeleteChildren(MemoryContext context)
Definition: mcxt.c:257
ErrorData * cur_error
Definition: plpgsql.h:1065
MemoryContext stmt_mcontext_parent
Definition: plpgsql.h:1104
uintptr_t Datum
Definition: postgres.h:367
const char * err_text
Definition: plpgsql.h:1113
PLpgSQL_condition * conditions
Definition: plpgsql.h:506
Datum datumTransfer(Datum value, bool typByVal, int typLen)
Definition: datum.c:193
#define PG_CATCH()
Definition: elog.h:305
static void assign_text_var(PLpgSQL_execstate *estate, PLpgSQL_var *var, const char *str)
Definition: pl_exec.c:8658
#define Assert(condition)
Definition: c.h:746
#define lfirst(lc)
Definition: pg_list.h:169
PLpgSQL_exception_block * exceptions
Definition: plpgsql.h:522
void BeginInternalSubTransaction(const char *name)
Definition: xact.c:4408
ExprContext * eval_econtext
Definition: plpgsql.h:1109
void get_typlenbyval(Oid typid, int16 *typlen, bool *typbyval)
Definition: lsyscache.c:2139
char typtype
Definition: plpgsql.h:206
e
Definition: preproc-init.c:82
static void exec_move_row(PLpgSQL_execstate *estate, PLpgSQL_variable *target, HeapTuple tup, TupleDesc tupdesc)
Definition: pl_exec.c:6911
#define elog(elevel,...)
Definition: elog.h:214
int i
static void plpgsql_create_econtext(PLpgSQL_execstate *estate)
Definition: pl_exec.c:8431
MemoryContext stmt_mcontext
Definition: plpgsql.h:1103
static void pop_stmt_mcontext(PLpgSQL_execstate *estate)
Definition: pl_exec.c:1540
char * exitlabel
Definition: plpgsql.h:1063
#define PG_TRY()
Definition: elog.h:295
PLpgSQL_expr * default_val
Definition: plpgsql.h:387
bool notnull
Definition: plpgsql.h:386
#define PG_END_TRY()
Definition: elog.h:320
void ReThrowError(ErrorData *edata)
Definition: elog.c:1649
char * message
Definition: elog.h:365
static int exec_stmts(PLpgSQL_execstate *estate, List *stmts)
Definition: pl_exec.c:1947
static void exec_assign_value(PLpgSQL_execstate *estate, PLpgSQL_datum *target, Datum value, bool isNull, Oid valtype, int32 valtypmod)
Definition: pl_exec.c:5086

◆ exec_stmt_call()

static int exec_stmt_call ( PLpgSQL_execstate estate,
PLpgSQL_stmt_call stmt 
)
static

Definition at line 2152 of file pl_exec.c.

References FuncExpr::args, Assert, PLpgSQL_execstate::atomic, PLpgSQL_row::dtype, elog, ereport, errcode(), errmsg(), ERROR, exec_eval_cleanup(), exec_move_row(), exec_prepare_plan(), expand_function_arguments(), PLpgSQL_stmt_call::expr, PLpgSQL_expr::expr_simple_expr, PLpgSQL_function::fn_cxt, PLpgSQL_execstate::func, FuncExpr::funcid, FuncExpr::funcresulttype, get_eval_mcontext, get_func_arg_info(), GetTransactionSnapshot(), HeapTupleIsValid, i, PLpgSQL_stmt_call::is_call, IsA, lfirst, PLpgSQL_row::lineno, linitial, linitial_node, list_length(), PGPROC::lxid, MemoryContextSwitchTo(), MyProc, PLpgSQL_row::nfields, _SPI_plan::no_snapshots, ObjectIdGetDatum, palloc(), palloc0(), Param::paramid, PG_CATCH, PG_END_TRY, PG_RE_THROW, PG_TRY, PLpgSQL_expr::plan, _SPI_plan::plancache_list, plpgsql_create_econtext(), PLPGSQL_DTYPE_ROW, PLPGSQL_RC_OK, PopActiveSnapshot(), PROCOID, PushActiveSnapshot(), PLpgSQL_expr::query, PLpgSQL_execstate::readonly_func, PLpgSQL_row::refname, ReleaseSysCache(), SearchSysCache1(), setup_param_list(), PLpgSQL_execstate::simple_eval_estate, PLpgSQL_execstate::simple_eval_resowner, SPI_execute_plan_with_paramlist(), SPI_freeplan(), SPI_freetuptable(), SPI_processed, SPI_result_code_string(), SPI_tuptable, PLpgSQL_stmt_call::target, SPITupleTable::tupdesc, SPITupleTable::vals, and PLpgSQL_row::varnos.

Referenced by exec_stmts().

2153 {
2154  PLpgSQL_expr *expr = stmt->expr;
2155  SPIPlanPtr orig_plan = expr->plan;
2156  bool local_plan;
2157  PLpgSQL_variable *volatile cur_target = stmt->target;
2158  volatile LocalTransactionId before_lxid;
2159  LocalTransactionId after_lxid;
2160  volatile bool pushed_active_snap = false;
2161  volatile int rc;
2162 
2163  /*
2164  * If not in atomic context, we make a local plan that we'll just use for
2165  * this invocation, and