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

Go to the source code of this file.

Data Structures

struct  PreparedParamsData
 
struct  SimpleEcontextStackEntry
 
struct  plpgsql_CastHashKey
 
struct  plpgsql_CastHashEntry
 

Macros

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

Typedefs

typedef struct SimpleEcontextStackEntry SimpleEcontextStackEntry
 

Functions

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

Variables

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

Macro Definition Documentation

◆ eval_mcontext_alloc

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

◆ eval_mcontext_alloc0

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

Definition at line 124 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:575
#define ERROR
Definition: elog.h:43
const char * name
Definition: encode.c:521
int errmsg(const char *fmt,...)
Definition: elog.c:797
char * MemoryContextStrdup(MemoryContext context, const char *string)
Definition: mcxt.c:1148

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

8147 {
8148  Assert(rec->dtype == PLPGSQL_DTYPE_REC);
8149 
8150  /* Transfer new record object into datum_context */
8151  TransferExpandedRecord(erh, estate->datum_context);
8152 
8153  /* Free the old value ... */
8154  if (rec->erh)
8156 
8157  /* ... and install the new */
8158  rec->erh = erh;
8159 }
PLpgSQL_datum_type dtype
Definition: plpgsql.h:362
ExpandedRecordHeader * erh
Definition: plpgsql.h:379
void DeleteExpandedObject(Datum d)
#define Assert(condition)
Definition: c.h:699
#define TransferExpandedRecord(erh, cxt)
MemoryContext datum_context
Definition: plpgsql.h:1017
#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 8069 of file pl_exec.c.

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

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

8071 {
8072  Assert(var->dtype == PLPGSQL_DTYPE_VAR ||
8073  var->dtype == PLPGSQL_DTYPE_PROMISE);
8074 
8075  /*
8076  * In non-atomic contexts, we do not want to store TOAST pointers in
8077  * variables, because such pointers might become stale after a commit.
8078  * Forcibly detoast in such cases. We don't want to detoast (flatten)
8079  * expanded objects, however; those should be OK across a transaction
8080  * boundary since they're just memory-resident objects. (Elsewhere in
8081  * this module, operations on expanded records likewise need to request
8082  * detoasting of record fields when !estate->atomic. Expanded arrays are
8083  * not a problem since all array entries are always detoasted.)
8084  */
8085  if (!estate->atomic && !isnull && var->datatype->typlen == -1 &&
8087  {
8088  MemoryContext oldcxt;
8089  Datum detoasted;
8090 
8091  /*
8092  * Do the detoasting in the eval_mcontext to avoid long-term leakage
8093  * of whatever memory toast fetching might leak. Then we have to copy
8094  * the detoasted datum to the function's main context, which is a
8095  * pain, but there's little choice.
8096  */
8097  oldcxt = MemoryContextSwitchTo(get_eval_mcontext(estate));
8098  detoasted = PointerGetDatum(heap_tuple_fetch_attr((struct varlena *) DatumGetPointer(newvalue)));
8099  MemoryContextSwitchTo(oldcxt);
8100  /* Now's a good time to not leak the input value if it's freeable */
8101  if (freeable)
8102  pfree(DatumGetPointer(newvalue));
8103  /* Once we copy the value, it's definitely freeable */
8104  newvalue = datumCopy(detoasted, false, -1);
8105  freeable = true;
8106  /* Can't clean up eval_mcontext here, but it'll happen before long */
8107  }
8108 
8109  /* Free the old value if needed */
8110  if (var->freeval)
8111  {
8113  var->isnull,
8114  var->datatype->typlen))
8116  else
8117  pfree(DatumGetPointer(var->value));
8118  }
8119  /* Assign new value to datum */
8120  var->value = newvalue;
8121  var->isnull = isnull;
8122  var->freeval = freeable;
8123 
8124  /*
8125  * If it's a promise variable, then either we just assigned the promised
8126  * value, or the user explicitly assigned an overriding value. Either
8127  * way, cancel the promise.
8128  */
8130 }
PLpgSQL_promise_type promise
Definition: plpgsql.h:318
#define VARATT_IS_EXTERNAL_NON_EXPANDED(PTR)
Definition: postgres.h:324
PLpgSQL_datum_type dtype
Definition: plpgsql.h:287
#define PointerGetDatum(X)
Definition: postgres.h:541
struct varlena * heap_tuple_fetch_attr(struct varlena *attr)
Definition: tuptoaster.c:101
PLpgSQL_type * datatype
Definition: plpgsql.h:296
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void pfree(void *pointer)
Definition: mcxt.c:1031
bool freeval
Definition: plpgsql.h:311
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition: datum.c:128
#define get_eval_mcontext(estate)
Definition: pl_exec.c:120
uintptr_t Datum
Definition: postgres.h:367
Datum value
Definition: plpgsql.h:309
void DeleteExpandedObject(Datum d)
#define Assert(condition)
Definition: c.h:699
#define DatumIsReadWriteExpandedObject(d, isnull, typlen)
#define DatumGetPointer(X)
Definition: postgres.h:534
Definition: c.h:516
int16 typlen
Definition: plpgsql.h:204
bool isnull
Definition: plpgsql.h:310

◆ assign_text_var()

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

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

8137 {
8138  assign_simple_var(estate, var, CStringGetTextDatum(str), false, true);
8139 }
static void assign_simple_var(PLpgSQL_execstate *estate, PLpgSQL_var *var, Datum newvalue, bool isnull, bool freeable)
Definition: pl_exec.c:8069
#define CStringGetTextDatum(s)
Definition: builtins.h:95

◆ coerce_function_result_tuple()

static void coerce_function_result_tuple ( PLpgSQL_execstate estate,
TupleDesc  tupdesc 
)
static

Definition at line 772 of file pl_exec.c.

References Assert, convert_tuples_by_position(), DatumGetEOHP(), DatumGetPointer, deconstruct_composite_datum(), do_convert_tuple(), ER_MAGIC, ExpandedRecordHeader::er_magic, expanded_record_get_tupdesc(), expanded_record_get_tuple(), gettext_noop, PointerGetDatum, ReleaseTupleDesc, PLpgSQL_execstate::rettype, PLpgSQL_execstate::retval, SPI_datumTransfer(), SPI_returntuple(), type_is_rowtype(), and VARATT_IS_EXTERNAL_EXPANDED.

Referenced by plpgsql_exec_function().

773 {
774  HeapTuple rettup;
775  TupleDesc retdesc;
776  TupleConversionMap *tupmap;
777 
778  /* We assume exec_stmt_return verified that result is composite */
779  Assert(type_is_rowtype(estate->rettype));
780 
781  /* We can special-case expanded records for speed */
783  {
785 
786  Assert(erh->er_magic == ER_MAGIC);
787 
788  /* Extract record's TupleDesc */
789  retdesc = expanded_record_get_tupdesc(erh);
790 
791  /* check rowtype compatibility */
792  tupmap = convert_tuples_by_position(retdesc,
793  tupdesc,
794  gettext_noop("returned record type does not match expected record type"));
795 
796  /* it might need conversion */
797  if (tupmap)
798  {
799  rettup = expanded_record_get_tuple(erh);
800  Assert(rettup);
801  rettup = do_convert_tuple(rettup, tupmap);
802 
803  /*
804  * Copy tuple to upper executor memory, as a tuple Datum. Make
805  * sure it is labeled with the caller-supplied tuple type.
806  */
807  estate->retval = PointerGetDatum(SPI_returntuple(rettup, tupdesc));
808  /* no need to free map, we're about to return anyway */
809  }
810  else
811  {
812  /*
813  * We need only copy result into upper executor memory context.
814  * However, if we have a R/W expanded datum, we can just transfer
815  * its ownership out to the upper executor context.
816  */
817  estate->retval = SPI_datumTransfer(estate->retval,
818  false,
819  -1);
820  }
821  }
822  else
823  {
824  /* Convert composite datum to a HeapTuple and TupleDesc */
825  HeapTupleData tmptup;
826 
827  retdesc = deconstruct_composite_datum(estate->retval, &tmptup);
828  rettup = &tmptup;
829 
830  /* check rowtype compatibility */
831  tupmap = convert_tuples_by_position(retdesc,
832  tupdesc,
833  gettext_noop("returned record type does not match expected record type"));
834 
835  /* it might need conversion */
836  if (tupmap)
837  rettup = do_convert_tuple(rettup, tupmap);
838 
839  /*
840  * Copy tuple to upper executor memory, as a tuple Datum. Make sure
841  * it is labeled with the caller-supplied tuple type.
842  */
843  estate->retval = PointerGetDatum(SPI_returntuple(rettup, tupdesc));
844 
845  /* no need to free map, we're about to return anyway */
846 
847  ReleaseTupleDesc(retdesc);
848  }
849 }
HeapTuple expanded_record_get_tuple(ExpandedRecordHeader *erh)
HeapTupleHeader SPI_returntuple(HeapTuple tuple, TupleDesc tupdesc)
Definition: spi.c:754
#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:66
#define PointerGetDatum(X)
Definition: postgres.h:541
#define gettext_noop(x)
Definition: c.h:1036
static TupleDesc deconstruct_composite_datum(Datum value, HeapTupleData *tmptup)
Definition: pl_exec.c:7110
Datum SPI_datumTransfer(Datum value, bool typByVal, int typLen)
Definition: spi.c:1043
bool type_is_rowtype(Oid typid)
Definition: lsyscache.c:2409
static TupleDesc expanded_record_get_tupdesc(ExpandedRecordHeader *erh)
ExpandedObjectHeader * DatumGetEOHP(Datum d)
Definition: expandeddatum.c:29
#define ER_MAGIC
#define Assert(condition)
Definition: c.h:699
HeapTuple do_convert_tuple(HeapTuple tuple, TupleConversionMap *map)
Definition: tupconvert.c:354
#define DatumGetPointer(X)
Definition: postgres.h:534
#define ReleaseTupleDesc(tupdesc)
Definition: tupdesc.h:124

◆ compatible_tupdescs()

static bool compatible_tupdescs ( TupleDesc  src_tupdesc,
TupleDesc  dst_tupdesc 
)
static

Definition at line 7011 of file pl_exec.c.

References i, tupleDesc::natts, and TupleDescAttr.

Referenced by exec_for_query(), and exec_move_row().

7012 {
7013  int i;
7014 
7015  /* Possibly we could allow src_tupdesc to have extra columns? */
7016  if (dst_tupdesc->natts != src_tupdesc->natts)
7017  return false;
7018 
7019  for (i = 0; i < dst_tupdesc->natts; i++)
7020  {
7021  Form_pg_attribute dattr = TupleDescAttr(dst_tupdesc, i);
7022  Form_pg_attribute sattr = TupleDescAttr(src_tupdesc, i);
7023 
7024  if (dattr->attisdropped != sattr->attisdropped)
7025  return false;
7026  if (!dattr->attisdropped)
7027  {
7028  /* Normal columns must match by type and typmod */
7029  if (dattr->atttypid != sattr->atttypid ||
7030  (dattr->atttypmod >= 0 &&
7031  dattr->atttypmod != sattr->atttypmod))
7032  return false;
7033  }
7034  else
7035  {
7036  /* Dropped columns are OK as long as length/alignment match */
7037  if (dattr->attlen != sattr->attlen ||
7038  dattr->attalign != sattr->attalign)
7039  return false;
7040  }
7041  }
7042  return true;
7043 }
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:93
int natts
Definition: tupdesc.h:82
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:197
int i

◆ contains_target_param()

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

Definition at line 7899 of file pl_exec.c.

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

Referenced by exec_check_rw_parameter().

7900 {
7901  if (node == NULL)
7902  return false;
7903  if (IsA(node, Param))
7904  {
7905  Param *param = (Param *) node;
7906 
7907  if (param->paramkind == PARAM_EXTERN &&
7908  param->paramid == *target_dno + 1)
7909  return true;
7910  return false;
7911  }
7913  (void *) target_dno);
7914 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:567
ParamKind paramkind
Definition: primnodes.h:244
static bool contains_target_param(Node *node, int *target_dno)
Definition: pl_exec.c:7899
int paramid
Definition: primnodes.h:245
bool expression_tree_walker(Node *node, bool(*walker)(), void *context)
Definition: nodeFuncs.c:1834

◆ convert_value_to_string()

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

Definition at line 7401 of file pl_exec.c.

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

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

7402 {
7403  char *result;
7404  MemoryContext oldcontext;
7405  Oid typoutput;
7406  bool typIsVarlena;
7407 
7408  oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
7409  getTypeOutputInfo(valtype, &typoutput, &typIsVarlena);
7410  result = OidOutputFunctionCall(typoutput, value);
7411  MemoryContextSwitchTo(oldcontext);
7412 
7413  return result;
7414 }
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:2650
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:120
static struct @131 value
char * OidOutputFunctionCall(Oid functionId, Datum val)
Definition: fmgr.c:1833

◆ copy_plpgsql_datums()

static void copy_plpgsql_datums ( PLpgSQL_execstate estate,
PLpgSQL_function func 
)
static

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

1213 {
1214  int ndatums = estate->ndatums;
1215  PLpgSQL_datum **indatums;
1216  PLpgSQL_datum **outdatums;
1217  char *workspace;
1218  char *ws_next;
1219  int i;
1220 
1221  /* Allocate local datum-pointer array */
1222  estate->datums = (PLpgSQL_datum **)
1223  palloc(sizeof(PLpgSQL_datum *) * ndatums);
1224 
1225  /*
1226  * To reduce palloc overhead, we make a single palloc request for all the
1227  * space needed for locally-instantiated datums.
1228  */
1229  workspace = palloc(func->copiable_size);
1230  ws_next = workspace;
1231 
1232  /* Fill datum-pointer array, copying datums into workspace as needed */
1233  indatums = func->datums;
1234  outdatums = estate->datums;
1235  for (i = 0; i < ndatums; i++)
1236  {
1237  PLpgSQL_datum *indatum = indatums[i];
1238  PLpgSQL_datum *outdatum;
1239 
1240  /* This must agree with plpgsql_finish_datums on what is copiable */
1241  switch (indatum->dtype)
1242  {
1243  case PLPGSQL_DTYPE_VAR:
1244  case PLPGSQL_DTYPE_PROMISE:
1245  outdatum = (PLpgSQL_datum *) ws_next;
1246  memcpy(outdatum, indatum, sizeof(PLpgSQL_var));
1247  ws_next += MAXALIGN(sizeof(PLpgSQL_var));
1248  break;
1249 
1250  case PLPGSQL_DTYPE_REC:
1251  outdatum = (PLpgSQL_datum *) ws_next;
1252  memcpy(outdatum, indatum, sizeof(PLpgSQL_rec));
1253  ws_next += MAXALIGN(sizeof(PLpgSQL_rec));
1254  break;
1255 
1256  case PLPGSQL_DTYPE_ROW:
1259 
1260  /*
1261  * These datum records are read-only at runtime, so no need to
1262  * copy them (well, RECFIELD and ARRAYELEM contain cached
1263  * data, but we'd just as soon centralize the caching anyway).
1264  */
1265  outdatum = indatum;
1266  break;
1267 
1268  default:
1269  elog(ERROR, "unrecognized dtype: %d", indatum->dtype);
1270  outdatum = NULL; /* keep compiler quiet */
1271  break;
1272  }
1273 
1274  outdatums[i] = outdatum;
1275  }
1276 
1277  Assert(ws_next == workspace + func->copiable_size);
1278 }
PLpgSQL_datum ** datums
Definition: plpgsql.h:964
PLpgSQL_datum_type dtype
Definition: plpgsql.h:253
PLpgSQL_datum ** datums
Definition: plpgsql.h:1015
#define ERROR
Definition: elog.h:43
#define Assert(condition)
Definition: c.h:699
#define MAXALIGN(LEN)
Definition: c.h:652
void * palloc(Size size)
Definition: mcxt.c:924
int i
Size copiable_size
Definition: plpgsql.h:965
#define elog
Definition: elog.h:219

◆ deconstruct_composite_datum()

static TupleDesc deconstruct_composite_datum ( Datum  value,
HeapTupleData tmptup 
)
static

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

7111 {
7112  HeapTupleHeader td;
7113  Oid tupType;
7114  int32 tupTypmod;
7115 
7116  /* Get tuple body (note this could involve detoasting) */
7118 
7119  /* Build a temporary HeapTuple control structure */
7120  tmptup->t_len = HeapTupleHeaderGetDatumLength(td);
7121  ItemPointerSetInvalid(&(tmptup->t_self));
7122  tmptup->t_tableOid = InvalidOid;
7123  tmptup->t_data = td;
7124 
7125  /* Extract rowtype info and find a tupdesc */
7126  tupType = HeapTupleHeaderGetTypeId(td);
7127  tupTypmod = HeapTupleHeaderGetTypMod(td);
7128  return lookup_rowtype_tupdesc(tupType, tupTypmod);
7129 }
TupleDesc lookup_rowtype_tupdesc(Oid type_id, int32 typmod)
Definition: typcache.c:1641
unsigned int Oid
Definition: postgres_ext.h:31
#define DatumGetHeapTupleHeader(X)
Definition: fmgr.h:264
signed int int32
Definition: c.h:313
HeapTupleHeader t_data
Definition: htup.h:68
#define HeapTupleHeaderGetTypMod(tup)
Definition: htup_details.h:467
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:457
static struct @131 value
#define InvalidOid
Definition: postgres_ext.h:36
#define ItemPointerSetInvalid(pointer)
Definition: itemptr.h:172
#define HeapTupleHeaderGetDatumLength(tup)
Definition: htup_details.h:451

◆ exception_matches_conditions()

static bool exception_matches_conditions ( ErrorData edata,
PLpgSQL_condition cond 
)
static

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

1498 {
1499  for (; cond != NULL; cond = cond->next)
1500  {
1501  int sqlerrstate = cond->sqlerrstate;
1502 
1503  /*
1504  * OTHERS matches everything *except* query-canceled and
1505  * assert-failure. If you're foolish enough, you can match those
1506  * explicitly.
1507  */
1508  if (sqlerrstate == 0)
1509  {
1510  if (edata->sqlerrcode != ERRCODE_QUERY_CANCELED &&
1511  edata->sqlerrcode != ERRCODE_ASSERT_FAILURE)
1512  return true;
1513  }
1514  /* Exact match? */
1515  else if (edata->sqlerrcode == sqlerrstate)
1516  return true;
1517  /* Category match? */
1518  else if (ERRCODE_IS_CATEGORY(sqlerrstate) &&
1519  ERRCODE_TO_CATEGORY(edata->sqlerrcode) == sqlerrstate)
1520  return true;
1521  }
1522  return false;
1523 }
#define ERRCODE_IS_CATEGORY(ec)
Definition: elog.h:68
int sqlerrcode
Definition: elog.h:342
struct PLpgSQL_condition * next
Definition: plpgsql.h:455
#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 4842 of file pl_exec.c.

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

Referenced by exec_stmt_getdiag().

4844 {
4845  text *value;
4846  MemoryContext oldcontext;
4847 
4848  /* Use eval_mcontext for short-lived text value */
4849  oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
4850  if (str != NULL)
4851  value = cstring_to_text(str);
4852  else
4853  value = cstring_to_text("");
4854  MemoryContextSwitchTo(oldcontext);
4855 
4856  exec_assign_value(estate, target, PointerGetDatum(value), false,
4857  TEXTOID, -1);
4858 }
#define PointerGetDatum(X)
Definition: postgres.h:541
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define get_eval_mcontext(estate)
Definition: pl_exec.c:120
static struct @131 value
text * cstring_to_text(const char *s)
Definition: varlena.c:149
Definition: c.h:516
static void exec_assign_value(PLpgSQL_execstate *estate, PLpgSQL_datum *target, Datum value, bool isNull, Oid valtype, int32 valtypmod)
Definition: pl_exec.c:4870

◆ exec_assign_expr()

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

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

4807 {
4808  Datum value;
4809  bool isnull;
4810  Oid valtype;
4811  int32 valtypmod;
4812 
4813  /*
4814  * If first time through, create a plan for this expression, and then see
4815  * if we can pass the target variable as a read-write parameter to the
4816  * expression. (This is a bit messy, but it seems cleaner than modifying
4817  * the API of exec_eval_expr for the purpose.)
4818  */
4819  if (expr->plan == NULL)
4820  {
4821  exec_prepare_plan(estate, expr, 0, true);
4822  if (target->dtype == PLPGSQL_DTYPE_VAR)
4823  exec_check_rw_parameter(expr, target->dno);
4824  }
4825 
4826  value = exec_eval_expr(estate, expr, &isnull, &valtype, &valtypmod);
4827  exec_assign_value(estate, target, value, isnull, valtype, valtypmod);
4828  exec_eval_cleanup(estate);
4829 }
static void exec_prepare_plan(PLpgSQL_execstate *estate, PLpgSQL_expr *expr, int cursorOptions, bool keepplan)
Definition: pl_exec.c:3948
static void exec_check_rw_parameter(PLpgSQL_expr *expr, int target_dno)
Definition: pl_exec.c:7822
static void exec_eval_cleanup(PLpgSQL_execstate *estate)
Definition: pl_exec.c:3927
unsigned int Oid
Definition: postgres_ext.h:31
PLpgSQL_datum_type dtype
Definition: plpgsql.h:253
SPIPlanPtr plan
Definition: plpgsql.h:218
signed int int32
Definition: c.h:313
static Datum exec_eval_expr(PLpgSQL_execstate *estate, PLpgSQL_expr *expr, bool *isNull, Oid *rettype, int32 *rettypmod)
Definition: pl_exec.c:5666
uintptr_t Datum
Definition: postgres.h:367
static struct @131 value
static void exec_assign_value(PLpgSQL_execstate *estate, PLpgSQL_datum *target, Datum value, bool isNull, Oid valtype, int32 valtypmod)
Definition: pl_exec.c:4870

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

4874 {
4875  switch (target->dtype)
4876  {
4877  case PLPGSQL_DTYPE_VAR:
4878  case PLPGSQL_DTYPE_PROMISE:
4879  {
4880  /*
4881  * Target is a variable
4882  */
4883  PLpgSQL_var *var = (PLpgSQL_var *) target;
4884  Datum newvalue;
4885 
4886  newvalue = exec_cast_value(estate,
4887  value,
4888  &isNull,
4889  valtype,
4890  valtypmod,
4891  var->datatype->typoid,
4892  var->datatype->atttypmod);
4893 
4894  if (isNull && var->notnull)
4895  ereport(ERROR,
4896  (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
4897  errmsg("null value cannot be assigned to variable \"%s\" declared NOT NULL",
4898  var->refname)));
4899 
4900  /*
4901  * If type is by-reference, copy the new value (which is
4902  * probably in the eval_mcontext) into the procedure's main
4903  * memory context. But if it's a read/write reference to an
4904  * expanded object, no physical copy needs to happen; at most
4905  * we need to reparent the object's memory context.
4906  *
4907  * If it's an array, we force the value to be stored in R/W
4908  * expanded form. This wins if the function later does, say,
4909  * a lot of array subscripting operations on the variable, and
4910  * otherwise might lose. We might need to use a different
4911  * heuristic, but it's too soon to tell. Also, are there
4912  * cases where it'd be useful to force non-array values into
4913  * expanded form?
4914  */
4915  if (!var->datatype->typbyval && !isNull)
4916  {
4917  if (var->datatype->typisarray &&
4919  {
4920  /* array and not already R/W, so apply expand_array */
4921  newvalue = expand_array(newvalue,
4922  estate->datum_context,
4923  NULL);
4924  }
4925  else
4926  {
4927  /* else transfer value if R/W, else just datumCopy */
4928  newvalue = datumTransfer(newvalue,
4929  false,
4930  var->datatype->typlen);
4931  }
4932  }
4933 
4934  /*
4935  * Now free the old value, if any, and assign the new one. But
4936  * skip the assignment if old and new values are the same.
4937  * Note that for expanded objects, this test is necessary and
4938  * cannot reliably be made any earlier; we have to be looking
4939  * at the object's standard R/W pointer to be sure pointer
4940  * equality is meaningful.
4941  *
4942  * Also, if it's a promise variable, we should disarm the
4943  * promise in any case --- otherwise, assigning null to an
4944  * armed promise variable would fail to disarm the promise.
4945  */
4946  if (var->value != newvalue || var->isnull || isNull)
4947  assign_simple_var(estate, var, newvalue, isNull,
4948  (!var->datatype->typbyval && !isNull));
4949  else
4951  break;
4952  }
4953 
4954  case PLPGSQL_DTYPE_ROW:
4955  {
4956  /*
4957  * Target is a row variable
4958  */
4959  PLpgSQL_row *row = (PLpgSQL_row *) target;
4960 
4961  if (isNull)
4962  {
4963  /* If source is null, just assign nulls to the row */
4964  exec_move_row(estate, (PLpgSQL_variable *) row,
4965  NULL, NULL);
4966  }
4967  else
4968  {
4969  /* Source must be of RECORD or composite type */
4970  if (!type_is_rowtype(valtype))
4971  ereport(ERROR,
4972  (errcode(ERRCODE_DATATYPE_MISMATCH),
4973  errmsg("cannot assign non-composite value to a row variable")));
4975  value);
4976  }
4977  break;
4978  }
4979 
4980  case PLPGSQL_DTYPE_REC:
4981  {
4982  /*
4983  * Target is a record variable
4984  */
4985  PLpgSQL_rec *rec = (PLpgSQL_rec *) target;
4986 
4987  if (isNull)
4988  {
4989  if (rec->notnull)
4990  ereport(ERROR,
4991  (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
4992  errmsg("null value cannot be assigned to variable \"%s\" declared NOT NULL",
4993  rec->refname)));
4994 
4995  /* Set variable to a simple NULL */
4996  exec_move_row(estate, (PLpgSQL_variable *) rec,
4997  NULL, NULL);
4998  }
4999  else
5000  {
5001  /* Source must be of RECORD or composite type */
5002  if (!type_is_rowtype(valtype))
5003  ereport(ERROR,
5004  (errcode(ERRCODE_DATATYPE_MISMATCH),
5005  errmsg("cannot assign non-composite value to a record variable")));
5007  value);
5008  }
5009  break;
5010  }
5011 
5013  {
5014  /*
5015  * Target is a field of a record
5016  */
5017  PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) target;
5018  PLpgSQL_rec *rec;
5019  ExpandedRecordHeader *erh;
5020 
5021  rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
5022  erh = rec->erh;
5023 
5024  /*
5025  * If record variable is NULL, instantiate it if it has a
5026  * named composite type, else complain. (This won't change
5027  * the logical state of the record, but if we successfully
5028  * assign below, the unassigned fields will all become NULLs.)
5029  */
5030  if (erh == NULL)
5031  {
5032  instantiate_empty_record_variable(estate, rec);
5033  erh = rec->erh;
5034  }
5035 
5036  /*
5037  * Look up the field's properties if we have not already, or
5038  * if the tuple descriptor ID changed since last time.
5039  */
5040  if (unlikely(recfield->rectupledescid != erh->er_tupdesc_id))
5041  {
5043  recfield->fieldname,
5044  &recfield->finfo))
5045  ereport(ERROR,
5046  (errcode(ERRCODE_UNDEFINED_COLUMN),
5047  errmsg("record \"%s\" has no field \"%s\"",
5048  rec->refname, recfield->fieldname)));
5049  recfield->rectupledescid = erh->er_tupdesc_id;
5050  }
5051 
5052  /* We don't support assignments to system columns. */
5053  if (recfield->finfo.fnumber <= 0)
5054  ereport(ERROR,
5055  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
5056  errmsg("cannot assign to system column \"%s\"",
5057  recfield->fieldname)));
5058 
5059  /* Cast the new value to the right type, if needed. */
5060  value = exec_cast_value(estate,
5061  value,
5062  &isNull,
5063  valtype,
5064  valtypmod,
5065  recfield->finfo.ftypeid,
5066  recfield->finfo.ftypmod);
5067 
5068  /* And assign it. */
5069  expanded_record_set_field(erh, recfield->finfo.fnumber,
5070  value, isNull, !estate->atomic);
5071  break;
5072  }
5073 
5075  {
5076  /*
5077  * Target is an element of an array
5078  */
5079  PLpgSQL_arrayelem *arrayelem;
5080  int nsubscripts;
5081  int i;
5082  PLpgSQL_expr *subscripts[MAXDIM];
5083  int subscriptvals[MAXDIM];
5084  Datum oldarraydatum,
5085  newarraydatum,
5086  coerced_value;
5087  bool oldarrayisnull;
5088  Oid parenttypoid;
5089  int32 parenttypmod;
5090  SPITupleTable *save_eval_tuptable;
5091  MemoryContext oldcontext;
5092 
5093  /*
5094  * We need to do subscript evaluation, which might require
5095  * evaluating general expressions; and the caller might have
5096  * done that too in order to prepare the input Datum. We have
5097  * to save and restore the caller's SPI_execute result, if
5098  * any.
5099  */
5100  save_eval_tuptable = estate->eval_tuptable;
5101  estate->eval_tuptable = NULL;
5102 
5103  /*
5104  * To handle constructs like x[1][2] := something, we have to
5105  * be prepared to deal with a chain of arrayelem datums. Chase
5106  * back to find the base array datum, and save the subscript
5107  * expressions as we go. (We are scanning right to left here,
5108  * but want to evaluate the subscripts left-to-right to
5109  * minimize surprises.) Note that arrayelem is left pointing
5110  * to the leftmost arrayelem datum, where we will cache the
5111  * array element type data.
5112  */
5113  nsubscripts = 0;
5114  do
5115  {
5116  arrayelem = (PLpgSQL_arrayelem *) target;
5117  if (nsubscripts >= MAXDIM)
5118  ereport(ERROR,
5119  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5120  errmsg("number of array dimensions (%d) exceeds the maximum allowed (%d)",
5121  nsubscripts + 1, MAXDIM)));
5122  subscripts[nsubscripts++] = arrayelem->subscript;
5123  target = estate->datums[arrayelem->arrayparentno];
5124  } while (target->dtype == PLPGSQL_DTYPE_ARRAYELEM);
5125 
5126  /* Fetch current value of array datum */
5127  exec_eval_datum(estate, target,
5128  &parenttypoid, &parenttypmod,
5129  &oldarraydatum, &oldarrayisnull);
5130 
5131  /* Update cached type data if necessary */
5132  if (arrayelem->parenttypoid != parenttypoid ||
5133  arrayelem->parenttypmod != parenttypmod)
5134  {
5135  Oid arraytypoid;
5136  int32 arraytypmod = parenttypmod;
5137  int16 arraytyplen;
5138  Oid elemtypoid;
5139  int16 elemtyplen;
5140  bool elemtypbyval;
5141  char elemtypalign;
5142 
5143  /* If target is domain over array, reduce to base type */
5144  arraytypoid = getBaseTypeAndTypmod(parenttypoid,
5145  &arraytypmod);
5146 
5147  /* ... and identify the element type */
5148  elemtypoid = get_element_type(arraytypoid);
5149  if (!OidIsValid(elemtypoid))
5150  ereport(ERROR,
5151  (errcode(ERRCODE_DATATYPE_MISMATCH),
5152  errmsg("subscripted object is not an array")));
5153 
5154  /* Collect needed data about the types */
5155  arraytyplen = get_typlen(arraytypoid);
5156 
5157  get_typlenbyvalalign(elemtypoid,
5158  &elemtyplen,
5159  &elemtypbyval,
5160  &elemtypalign);
5161 
5162  /* Now safe to update the cached data */
5163  arrayelem->parenttypoid = parenttypoid;
5164  arrayelem->parenttypmod = parenttypmod;
5165  arrayelem->arraytypoid = arraytypoid;
5166  arrayelem->arraytypmod = arraytypmod;
5167  arrayelem->arraytyplen = arraytyplen;
5168  arrayelem->elemtypoid = elemtypoid;
5169  arrayelem->elemtyplen = elemtyplen;
5170  arrayelem->elemtypbyval = elemtypbyval;
5171  arrayelem->elemtypalign = elemtypalign;
5172  }
5173 
5174  /*
5175  * Evaluate the subscripts, switch into left-to-right order.
5176  * Like the expression built by ExecInitArrayRef(), complain
5177  * if any subscript is null.
5178  */
5179  for (i = 0; i < nsubscripts; i++)
5180  {
5181  bool subisnull;
5182 
5183  subscriptvals[i] =
5184  exec_eval_integer(estate,
5185  subscripts[nsubscripts - 1 - i],
5186  &subisnull);
5187  if (subisnull)
5188  ereport(ERROR,
5189  (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
5190  errmsg("array subscript in assignment must not be null")));
5191 
5192  /*
5193  * Clean up in case the subscript expression wasn't
5194  * simple. We can't do exec_eval_cleanup, but we can do
5195  * this much (which is safe because the integer subscript
5196  * value is surely pass-by-value), and we must do it in
5197  * case the next subscript expression isn't simple either.
5198  */
5199  if (estate->eval_tuptable != NULL)
5201  estate->eval_tuptable = NULL;
5202  }
5203 
5204  /* Now we can restore caller's SPI_execute result if any. */
5205  Assert(estate->eval_tuptable == NULL);
5206  estate->eval_tuptable = save_eval_tuptable;
5207 
5208  /* Coerce source value to match array element type. */
5209  coerced_value = exec_cast_value(estate,
5210  value,
5211  &isNull,
5212  valtype,
5213  valtypmod,
5214  arrayelem->elemtypoid,
5215  arrayelem->arraytypmod);
5216 
5217  /*
5218  * If the original array is null, cons up an empty array so
5219  * that the assignment can proceed; we'll end with a
5220  * one-element array containing just the assigned-to
5221  * subscript. This only works for varlena arrays, though; for
5222  * fixed-length array types we skip the assignment. We can't
5223  * support assignment of a null entry into a fixed-length
5224  * array, either, so that's a no-op too. This is all ugly but
5225  * corresponds to the current behavior of execExpr*.c.
5226  */
5227  if (arrayelem->arraytyplen > 0 && /* fixed-length array? */
5228  (oldarrayisnull || isNull))
5229  return;
5230 
5231  /* empty array, if any, and newarraydatum are short-lived */
5232  oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
5233 
5234  if (oldarrayisnull)
5235  oldarraydatum = PointerGetDatum(construct_empty_array(arrayelem->elemtypoid));
5236 
5237  /*
5238  * Build the modified array value.
5239  */
5240  newarraydatum = array_set_element(oldarraydatum,
5241  nsubscripts,
5242  subscriptvals,
5243  coerced_value,
5244  isNull,
5245  arrayelem->arraytyplen,
5246  arrayelem->elemtyplen,
5247  arrayelem->elemtypbyval,
5248  arrayelem->elemtypalign);
5249 
5250  MemoryContextSwitchTo(oldcontext);
5251 
5252  /*
5253  * Assign the new array to the base variable. It's never NULL
5254  * at this point. Note that if the target is a domain,
5255  * coercing the base array type back up to the domain will
5256  * happen within exec_assign_value.
5257  */
5258  exec_assign_value(estate, target,
5259  newarraydatum,
5260  false,
5261  arrayelem->arraytypoid,
5262  arrayelem->arraytypmod);
5263  break;
5264  }
5265 
5266  default:
5267  elog(ERROR, "unrecognized dtype: %d", target->dtype);
5268  }
5269 }
PLpgSQL_promise_type promise
Definition: plpgsql.h:318
signed short int16
Definition: c.h:312
int16 elemtyplen
Definition: plpgsql.h:418
#define expanded_record_set_field(erh, fnumber, newValue, isnull, expand_external)
Oid getBaseTypeAndTypmod(Oid typid, int32 *typmod)
Definition: lsyscache.c:2292
SPITupleTable * eval_tuptable
Definition: plpgsql.h:1039
char * refname
Definition: plpgsql.h:289
static void exec_eval_datum(PLpgSQL_execstate *estate, PLpgSQL_datum *datum, Oid *typeid, int32 *typetypmod, Datum *value, bool *isnull)
Definition: pl_exec.c:5289
bool expanded_record_lookup_field(ExpandedRecordHeader *erh, const char *fieldname, ExpandedRecordFieldInfo *finfo)
#define MAXDIM
Definition: c.h:496
Oid get_element_type(Oid typid)
Definition: lsyscache.c:2502
void get_typlenbyvalalign(Oid typid, int16 *typlen, bool *typbyval, char *typalign)
Definition: lsyscache.c:2025
#define PointerGetDatum(X)
Definition: postgres.h:541
PLpgSQL_type * datatype
Definition: plpgsql.h:296
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:7369
ExpandedRecordHeader * erh
Definition: plpgsql.h:379
int errcode(int sqlerrcode)
Definition: elog.c:575
static void assign_simple_var(PLpgSQL_execstate *estate, PLpgSQL_var *var, Datum newvalue, bool isnull, bool freeable)
Definition: pl_exec.c:8069
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:2187
ArrayType * construct_empty_array(Oid elmtype)
Definition: arrayfuncs.c:3398
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:7141
PLpgSQL_datum_type dtype
Definition: plpgsql.h:253
#define OidIsValid(objectId)
Definition: c.h:605
char * refname
Definition: plpgsql.h:364
signed int int32
Definition: c.h:313
PLpgSQL_datum ** datums
Definition: plpgsql.h:1015
int32 arraytypmod
Definition: plpgsql.h:415
bool notnull
Definition: plpgsql.h:292
static Datum exec_cast_value(PLpgSQL_execstate *estate, Datum value, bool *isnull, Oid valtype, int32 valtypmod, Oid reqtype, int32 reqtypmod)
Definition: pl_exec.c:7430
#define ERROR
Definition: elog.h:43
bool type_is_rowtype(Oid typid)
Definition: lsyscache.c:2409
#define ereport(elevel, rest)
Definition: elog.h:122
uint64 rectupledescid
Definition: plpgsql.h:394
bool typbyval
Definition: plpgsql.h:205
#define get_eval_mcontext(estate)
Definition: pl_exec.c:120
void SPI_freetuptable(SPITupleTable *tuptable)
Definition: spi.c:1068
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:5620
ExpandedRecordFieldInfo finfo
Definition: plpgsql.h:395
int32 parenttypmod
Definition: plpgsql.h:413
static struct @131 value
Datum value
Definition: plpgsql.h:309
Datum datumTransfer(Datum value, bool typByVal, int typLen)
Definition: datum.c:190
#define Assert(condition)
Definition: c.h:699
int16 arraytyplen
Definition: plpgsql.h:416
#define DatumGetPointer(X)
Definition: postgres.h:534
MemoryContext datum_context
Definition: plpgsql.h:1017
int16 get_typlen(Oid typid)
Definition: lsyscache.c:1951
int errmsg(const char *fmt,...)
Definition: elog.c:797
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:6625
int i
PLpgSQL_expr * subscript
Definition: plpgsql.h:408
#define VARATT_IS_EXTERNAL_EXPANDED_RW(PTR)
Definition: postgres.h:320
#define unlikely(x)
Definition: c.h:208
#define elog
Definition: elog.h:219
int16 typlen
Definition: plpgsql.h:204
bool notnull
Definition: plpgsql.h:367
char * fieldname
Definition: plpgsql.h:391
static void exec_assign_value(PLpgSQL_execstate *estate, PLpgSQL_datum *target, Datum value, bool isNull, Oid valtype, int32 valtypmod)
Definition: pl_exec.c:4870
bool isnull
Definition: plpgsql.h:310
Oid typoid
Definition: plpgsql.h:202

◆ exec_cast_value()

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

Definition at line 7430 of file pl_exec.c.

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

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

7434 {
7435  /*
7436  * If the type of the given value isn't what's requested, convert it.
7437  */
7438  if (valtype != reqtype ||
7439  (valtypmod != reqtypmod && reqtypmod != -1))
7440  {
7441  plpgsql_CastHashEntry *cast_entry;
7442 
7443  cast_entry = get_cast_hashentry(estate,
7444  valtype, valtypmod,
7445  reqtype, reqtypmod);
7446  if (cast_entry)
7447  {
7448  ExprContext *econtext = estate->eval_econtext;
7449  MemoryContext oldcontext;
7450 
7451  oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
7452 
7453  econtext->caseValue_datum = value;
7454  econtext->caseValue_isNull = *isnull;
7455 
7456  cast_entry->cast_in_use = true;
7457 
7458  value = ExecEvalExpr(cast_entry->cast_exprstate, econtext,
7459  isnull);
7460 
7461  cast_entry->cast_in_use = false;
7462 
7463  MemoryContextSwitchTo(oldcontext);
7464  }
7465  }
7466 
7467  return value;
7468 }
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:7481
Datum caseValue_datum
Definition: execnodes.h:243
static Datum ExecEvalExpr(ExprState *state, ExprContext *econtext, bool *isNull)
Definition: executor.h:280
#define get_eval_mcontext(estate)
Definition: pl_exec.c:120
static struct @131 value
ExprContext * eval_econtext
Definition: plpgsql.h:1042
bool caseValue_isNull
Definition: execnodes.h:245
ExprState * cast_exprstate
Definition: pl_exec.c:155

◆ exec_check_rw_parameter()

static void exec_check_rw_parameter ( PLpgSQL_expr expr,
int  target_dno 
)
static

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

7823 {
7824  Oid funcid;
7825  List *fargs;
7826  ListCell *lc;
7827 
7828  /* Assume unsafe */
7829  expr->rwparam = -1;
7830 
7831  /*
7832  * If the expression isn't simple, there's no point in trying to optimize
7833  * (because the exec_run_select code path will flatten any expanded result
7834  * anyway). Even without that, this seems like a good safety restriction.
7835  */
7836  if (expr->expr_simple_expr == NULL)
7837  return;
7838 
7839  /*
7840  * If target variable isn't referenced by expression, no need to look
7841  * further.
7842  */
7843  if (!bms_is_member(target_dno, expr->paramnos))
7844  return;
7845 
7846  /*
7847  * Top level of expression must be a simple FuncExpr or OpExpr.
7848  */
7849  if (IsA(expr->expr_simple_expr, FuncExpr))
7850  {
7851  FuncExpr *fexpr = (FuncExpr *) expr->expr_simple_expr;
7852 
7853  funcid = fexpr->funcid;
7854  fargs = fexpr->args;
7855  }
7856  else if (IsA(expr->expr_simple_expr, OpExpr))
7857  {
7858  OpExpr *opexpr = (OpExpr *) expr->expr_simple_expr;
7859 
7860  funcid = opexpr->opfuncid;
7861  fargs = opexpr->args;
7862  }
7863  else
7864  return;
7865 
7866  /*
7867  * The top-level function must be one that we trust to be "safe".
7868  * Currently we hard-wire the list, but it would be very desirable to
7869  * allow extensions to mark their functions as safe ...
7870  */
7871  if (!(funcid == F_ARRAY_APPEND ||
7872  funcid == F_ARRAY_PREPEND))
7873  return;
7874 
7875  /*
7876  * The target variable (in the form of a Param) must only appear as a
7877  * direct argument of the top-level function.
7878  */
7879  foreach(lc, fargs)
7880  {
7881  Node *arg = (Node *) lfirst(lc);
7882 
7883  /* A Param is OK, whether it's the target variable or not */
7884  if (arg && IsA(arg, Param))
7885  continue;
7886  /* Otherwise, argument expression must not reference target */
7887  if (contains_target_param(arg, &target_dno))
7888  return;
7889  }
7890 
7891  /* OK, we can pass target as a read-write parameter */
7892  expr->rwparam = target_dno;
7893 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:567
List * args
Definition: primnodes.h:457
Definition: nodes.h:516
unsigned int Oid
Definition: postgres_ext.h:31
Bitmapset * paramnos
Definition: plpgsql.h:219
Oid funcid
Definition: primnodes.h:449
static bool contains_target_param(Node *node, int *target_dno)
Definition: pl_exec.c:7899
Expr * expr_simple_expr
Definition: plpgsql.h:229
int rwparam
Definition: plpgsql.h:220
Oid opfuncid
Definition: primnodes.h:497
#define lfirst(lc)
Definition: pg_list.h:106
void * arg
List * args
Definition: primnodes.h:502
Definition: pg_list.h:45
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:486

◆ 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 8247 of file pl_exec.c.

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

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

8252 {
8253  Portal portal;
8254  Datum query;
8255  bool isnull;
8256  Oid restype;
8257  int32 restypmod;
8258  char *querystr;
8259  MemoryContext stmt_mcontext = get_stmt_mcontext(estate);
8260 
8261  /*
8262  * Evaluate the string expression after the EXECUTE keyword. Its result is
8263  * the querystring we have to execute.
8264  */
8265  query = exec_eval_expr(estate, dynquery, &isnull, &restype, &restypmod);
8266  if (isnull)
8267  ereport(ERROR,
8268  (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
8269  errmsg("query string argument of EXECUTE is null")));
8270 
8271  /* Get the C-String representation */
8272  querystr = convert_value_to_string(estate, query, restype);
8273 
8274  /* copy it into the stmt_mcontext before we clean up */
8275  querystr = MemoryContextStrdup(stmt_mcontext, querystr);
8276 
8277  exec_eval_cleanup(estate);
8278 
8279  /*
8280  * Open an implicit cursor for the query. We use
8281  * SPI_cursor_open_with_args even when there are no params, because this
8282  * avoids making and freeing one copy of the plan.
8283  */
8284  if (params)
8285  {
8286  PreparedParamsData *ppd;
8287 
8288  ppd = exec_eval_using_params(estate, params);
8289  portal = SPI_cursor_open_with_args(portalname,
8290  querystr,
8291  ppd->nargs, ppd->types,
8292  ppd->values, ppd->nulls,
8293  estate->readonly_func,
8294  cursorOptions);
8295  }
8296  else
8297  {
8298  portal = SPI_cursor_open_with_args(portalname,
8299  querystr,
8300  0, NULL,
8301  NULL, NULL,
8302  estate->readonly_func,
8303  cursorOptions);
8304  }
8305 
8306  if (portal == NULL)
8307  elog(ERROR, "could not open implicit cursor for query \"%s\": %s",
8308  querystr, SPI_result_code_string(SPI_result));
8309 
8310  /* Release transient data */
8311  MemoryContextReset(stmt_mcontext);
8312 
8313  return portal;
8314 }
int errcode(int sqlerrcode)
Definition: elog.c:575
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:136
static void exec_eval_cleanup(PLpgSQL_execstate *estate)
Definition: pl_exec.c:3927
Datum * values
Definition: pl_exec.c:57
unsigned int Oid
Definition: postgres_ext.h:31
signed int int32
Definition: c.h:313
int SPI_result
Definition: spi.c:42
#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:5666
static PreparedParamsData * exec_eval_using_params(PLpgSQL_execstate *estate, List *params)
Definition: pl_exec.c:8168
const char * SPI_result_code_string(int code)
Definition: spi.c:1611
static MemoryContext get_stmt_mcontext(PLpgSQL_execstate *estate)
Definition: pl_exec.c:1446
#define ereport(elevel, rest)
Definition: elog.h:122
uintptr_t Datum
Definition: postgres.h:367
Portal SPI_cursor_open_with_args(const char *name, const char *src, int nargs, Oid *argtypes, Datum *Values, const char *Nulls, bool read_only, int cursorOptions)
Definition: spi.c:1154
bool readonly_func
Definition: plpgsql.h:993
int errmsg(const char *fmt,...)
Definition: elog.c:797
char * MemoryContextStrdup(MemoryContext context, const char *string)
Definition: mcxt.c:1148
static char * convert_value_to_string(PLpgSQL_execstate *estate, Datum value, Oid valtype)
Definition: pl_exec.c:7401
#define elog
Definition: elog.h:219

◆ exec_eval_boolean()

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

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

5646 {
5647  Datum exprdatum;
5648  Oid exprtypeid;
5649  int32 exprtypmod;
5650 
5651  exprdatum = exec_eval_expr(estate, expr, isNull, &exprtypeid, &exprtypmod);
5652  exprdatum = exec_cast_value(estate, exprdatum, isNull,
5653  exprtypeid, exprtypmod,
5654  BOOLOID, -1);
5655  return DatumGetBool(exprdatum);
5656 }
unsigned int Oid
Definition: postgres_ext.h:31
signed int int32
Definition: c.h:313
static Datum exec_cast_value(PLpgSQL_execstate *estate, Datum value, bool *isnull, Oid valtype, int32 valtypmod, Oid reqtype, int32 reqtypmod)
Definition: pl_exec.c:7430
static Datum exec_eval_expr(PLpgSQL_execstate *estate, PLpgSQL_expr *expr, bool *isNull, Oid *rettype, int32 *rettypmod)
Definition: pl_exec.c:5666
#define DatumGetBool(X)
Definition: postgres.h:378
uintptr_t Datum
Definition: postgres.h:367

◆ exec_eval_cleanup()

static void exec_eval_cleanup ( PLpgSQL_execstate estate)
static

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

3928 {
3929  /* Clear result of a full SPI_execute */
3930  if (estate->eval_tuptable != NULL)
3932  estate->eval_tuptable = NULL;
3933 
3934  /*
3935  * Clear result of exec_eval_simple_expr (but keep the econtext). This
3936  * also clears any short-lived allocations done via get_eval_mcontext.
3937  */
3938  if (estate->eval_econtext != NULL)
3940 }
SPITupleTable * eval_tuptable
Definition: plpgsql.h:1039
void SPI_freetuptable(SPITupleTable *tuptable)
Definition: spi.c:1068
ExprContext * eval_econtext
Definition: plpgsql.h:1042
#define ResetExprContext(econtext)
Definition: executor.h:482

◆ 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 5289 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, tupleDesc::tdtypeid, tupleDesc::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().

5295 {
5296  MemoryContext oldcontext;
5297 
5298  switch (datum->dtype)
5299  {
5300  case PLPGSQL_DTYPE_PROMISE:
5301  /* fulfill promise if needed, then handle like regular var */
5302  plpgsql_fulfill_promise(estate, (PLpgSQL_var *) datum);
5303 
5304  /* FALL THRU */
5305 
5306  case PLPGSQL_DTYPE_VAR:
5307  {
5308  PLpgSQL_var *var = (PLpgSQL_var *) datum;
5309 
5310  *typeid = var->datatype->typoid;
5311  *typetypmod = var->datatype->atttypmod;
5312  *value = var->value;
5313  *isnull = var->isnull;
5314  break;
5315  }
5316 
5317  case PLPGSQL_DTYPE_ROW:
5318  {
5319  PLpgSQL_row *row = (PLpgSQL_row *) datum;
5320  HeapTuple tup;
5321 
5322  /* We get here if there are multiple OUT parameters */
5323  if (!row->rowtupdesc) /* should not happen */
5324  elog(ERROR, "row variable has no tupdesc");
5325  /* Make sure we have a valid type/typmod setting */
5326  BlessTupleDesc(row->rowtupdesc);
5327  oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
5328  tup = make_tuple_from_row(estate, row, row->rowtupdesc);
5329  if (tup == NULL) /* should not happen */
5330  elog(ERROR, "row not compatible with its own tupdesc");
5331  *typeid = row->rowtupdesc->tdtypeid;
5332  *typetypmod = row->rowtupdesc->tdtypmod;
5333  *value = HeapTupleGetDatum(tup);
5334  *isnull = false;
5335  MemoryContextSwitchTo(oldcontext);
5336  break;
5337  }
5338 
5339  case PLPGSQL_DTYPE_REC:
5340  {
5341  PLpgSQL_rec *rec = (PLpgSQL_rec *) datum;
5342 
5343  if (rec->erh == NULL)
5344  {
5345  /* Treat uninstantiated record as a simple NULL */
5346  *value = (Datum) 0;
5347  *isnull = true;
5348  /* Report variable's declared type */
5349  *typeid = rec->rectypeid;
5350  *typetypmod = -1;
5351  }
5352  else
5353  {
5354  if (ExpandedRecordIsEmpty(rec->erh))
5355  {
5356  /* Empty record is also a NULL */
5357  *value = (Datum) 0;
5358  *isnull = true;
5359  }
5360  else
5361  {
5362  *value = ExpandedRecordGetDatum(rec->erh);
5363  *isnull = false;
5364  }
5365  if (rec->rectypeid != RECORDOID)
5366  {
5367  /* Report variable's declared type, if not RECORD */
5368  *typeid = rec->rectypeid;
5369  *typetypmod = -1;
5370  }
5371  else
5372  {
5373  /* Report record's actual type if declared RECORD */
5374  *typeid = rec->erh->er_typeid;
5375  *typetypmod = rec->erh->er_typmod;
5376  }
5377  }
5378  break;
5379  }
5380 
5382  {
5383  PLpgSQL_recfield *recfield = (PLpgSQL_recfield *) datum;
5384  PLpgSQL_rec *rec;
5385  ExpandedRecordHeader *erh;
5386 
5387  rec = (PLpgSQL_rec *) (estate->datums[recfield->recparentno]);
5388  erh = rec->erh;
5389 
5390  /*
5391  * If record variable is NULL, instantiate it if it has a
5392  * named composite type, else complain. (This won't change
5393  * the logical state of the record: it's still NULL.)
5394  */
5395  if (erh == NULL)
5396  {
5397  instantiate_empty_record_variable(estate, rec);
5398  erh = rec->erh;
5399  }
5400 
5401  /*
5402  * Look up the field's properties if we have not already, or
5403  * if the tuple descriptor ID changed since last time.
5404  */
5405  if (unlikely(recfield->rectupledescid != erh->er_tupdesc_id))
5406  {
5408  recfield->fieldname,
5409  &recfield->finfo))
5410  ereport(ERROR,
5411  (errcode(ERRCODE_UNDEFINED_COLUMN),
5412  errmsg("record \"%s\" has no field \"%s\"",
5413  rec->refname, recfield->fieldname)));
5414  recfield->rectupledescid = erh->er_tupdesc_id;
5415  }
5416 
5417  /* Report type data. */
5418  *typeid = recfield->finfo.ftypeid;
5419  *typetypmod = recfield->finfo.ftypmod;
5420 
5421  /* And fetch the field value. */
5423  recfield->finfo.fnumber,
5424  isnull);
5425  break;
5426  }
5427 
5428  default:
5429  elog(ERROR, "unrecognized dtype: %d", datum->dtype);
5430  }
5431 }
static HeapTuple make_tuple_from_row(PLpgSQL_execstate *estate, PLpgSQL_row *row, TupleDesc tupdesc)
Definition: pl_exec.c:7055
Oid tdtypeid
Definition: tupdesc.h:83
#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:296
static void plpgsql_fulfill_promise(PLpgSQL_execstate *estate, PLpgSQL_var *var)
Definition: pl_exec.c:1286
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:7369
ExpandedRecordHeader * erh
Definition: plpgsql.h:379
int errcode(int sqlerrcode)
Definition: elog.c:575
PLpgSQL_datum_type dtype
Definition: plpgsql.h:253
char * refname
Definition: plpgsql.h:364
int32 tdtypmod
Definition: tupdesc.h:84
PLpgSQL_datum ** datums
Definition: plpgsql.h:1015
#define ERROR
Definition: elog.h:43
TupleDesc BlessTupleDesc(TupleDesc tupdesc)
Definition: execTuples.c:1109
#define ereport(elevel, rest)
Definition: elog.h:122
uint64 rectupledescid
Definition: plpgsql.h:394
#define get_eval_mcontext(estate)
Definition: pl_exec.c:120
uintptr_t Datum
Definition: postgres.h:367
ExpandedRecordFieldInfo finfo
Definition: plpgsql.h:395
static struct @131 value
Datum value
Definition: plpgsql.h:309
#define HeapTupleGetDatum(tuple)
Definition: funcapi.h:231
int errmsg(const char *fmt,...)
Definition: elog.c:797
int32 atttypmod
Definition: plpgsql.h:209
TupleDesc rowtupdesc
Definition: plpgsql.h:350
#define unlikely(x)
Definition: c.h:208
#define elog
Definition: elog.h:219
Oid rectypeid
Definition: plpgsql.h:372
#define ExpandedRecordGetDatum(erh)
char * fieldname
Definition: plpgsql.h:391
bool isnull
Definition: plpgsql.h:310
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 5666 of file pl_exec.c.

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

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

5671 {
5672  Datum result = 0;
5673  int rc;
5674  Form_pg_attribute attr;
5675 
5676  /*
5677  * If first time through, create a plan for this expression.
5678  */
5679  if (expr->plan == NULL)
5680  exec_prepare_plan(estate, expr, CURSOR_OPT_PARALLEL_OK, true);
5681 
5682  /*
5683  * If this is a simple expression, bypass SPI and use the executor
5684  * directly
5685  */
5686  if (exec_eval_simple_expr(estate, expr,
5687  &result, isNull, rettype, rettypmod))
5688  return result;
5689 
5690  /*
5691  * Else do it the hard way via exec_run_select
5692  */
5693  rc = exec_run_select(estate, expr, 2, NULL);
5694  if (rc != SPI_OK_SELECT)
5695  ereport(ERROR,
5696  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
5697  errmsg("query \"%s\" did not return data", expr->query)));
5698 
5699  /*
5700  * Check that the expression returns exactly one column...
5701  */
5702  if (estate->eval_tuptable->tupdesc->natts != 1)
5703  ereport(ERROR,
5704  (errcode(ERRCODE_SYNTAX_ERROR),
5705  errmsg_plural("query \"%s\" returned %d column",
5706  "query \"%s\" returned %d columns",
5707  estate->eval_tuptable->tupdesc->natts,
5708  expr->query,
5709  estate->eval_tuptable->tupdesc->natts)));
5710 
5711  /*
5712  * ... and get the column's datatype.
5713  */
5714  attr = TupleDescAttr(estate->eval_tuptable->tupdesc, 0);
5715  *rettype = attr->atttypid;
5716  *rettypmod = attr->atttypmod;
5717 
5718  /*
5719  * If there are no rows selected, the result is a NULL of that type.
5720  */
5721  if (estate->eval_processed == 0)
5722  {
5723  *isNull = true;
5724  return (Datum) 0;
5725  }
5726 
5727  /*
5728  * Check that the expression returned no more than one row.
5729  */
5730  if (estate->eval_processed != 1)
5731  ereport(ERROR,
5732  (errcode(ERRCODE_CARDINALITY_VIOLATION),
5733  errmsg("query \"%s\" returned more than one row",
5734  expr->query)));
5735 
5736  /*
5737  * Return the single result Datum.
5738  */
5739  return SPI_getbinval(estate->eval_tuptable->vals[0],
5740  estate->eval_tuptable->tupdesc, 1, isNull);
5741 }
char * query
Definition: plpgsql.h:217
static void exec_prepare_plan(PLpgSQL_execstate *estate, PLpgSQL_expr *expr, int cursorOptions, bool keepplan)
Definition: pl_exec.c:3948
SPITupleTable * eval_tuptable
Definition: plpgsql.h:1039
uint64 eval_processed
Definition: plpgsql.h:1040
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:850
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:93
int errcode(int sqlerrcode)
Definition: elog.c:575
HeapTuple * vals
Definition: spi.h:28
int natts
Definition: tupdesc.h:82
SPIPlanPtr plan
Definition: plpgsql.h:218
#define ERROR
Definition: elog.h:43
Datum SPI_getbinval(HeapTuple tuple, TupleDesc tupdesc, int fnumber, bool *isnull)
Definition: spi.c:934
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:197
#define ereport(elevel, rest)
Definition: elog.h:122
uintptr_t Datum
Definition: postgres.h:367
TupleDesc tupdesc
Definition: spi.h:27
#define SPI_OK_SELECT
Definition: spi.h:54
static int exec_run_select(PLpgSQL_execstate *estate, PLpgSQL_expr *expr, long maxtuples, Portal *portalP)
Definition: pl_exec.c:5749
static bool exec_eval_simple_expr(PLpgSQL_execstate *estate, PLpgSQL_expr *expr, Datum *result, bool *isNull, Oid *rettype, int32 *rettypmod)
Definition: pl_exec.c:5987
#define CURSOR_OPT_PARALLEL_OK
Definition: parsenodes.h:2653
int errmsg(const char *fmt,...)
Definition: elog.c:797

◆ exec_eval_integer()

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

Definition at line 5620 of file pl_exec.c.

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

Referenced by exec_assign_value(), and exec_stmt_fetch().

5623 {
5624  Datum exprdatum;
5625  Oid exprtypeid;
5626  int32 exprtypmod;
5627 
5628  exprdatum = exec_eval_expr(estate, expr, isNull, &exprtypeid, &exprtypmod);
5629  exprdatum = exec_cast_value(estate, exprdatum, isNull,
5630  exprtypeid, exprtypmod,
5631  INT4OID, -1);
5632  return DatumGetInt32(exprdatum);
5633 }
#define DatumGetInt32(X)
Definition: postgres.h:457
unsigned int Oid
Definition: postgres_ext.h:31
signed int int32
Definition: c.h:313
static Datum exec_cast_value(PLpgSQL_execstate *estate, Datum value, bool *isnull, Oid valtype, int32 valtypmod, Oid reqtype, int32 reqtypmod)
Definition: pl_exec.c:7430
static Datum exec_eval_expr(PLpgSQL_execstate *estate, PLpgSQL_expr *expr, bool *isNull, Oid *rettype, int32 *rettypmod)
Definition: pl_exec.c:5666
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 5987 of file pl_exec.c.

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

Referenced by exec_eval_expr().

5993 {
5994  ExprContext *econtext = estate->eval_econtext;
5995  LocalTransactionId curlxid = MyProc->lxid;
5996  CachedPlan *cplan;
5997  void *save_setup_arg;
5998  MemoryContext oldcontext;
5999 
6000  /*
6001  * Forget it if expression wasn't simple before.
6002  */
6003  if (expr->expr_simple_expr == NULL)
6004  return false;
6005 
6006  /*
6007  * If expression is in use in current xact, don't touch it.
6008  */
6009  if (expr->expr_simple_in_use && expr->expr_simple_lxid == curlxid)
6010  return false;
6011 
6012  /*
6013  * Revalidate cached plan, so that we will notice if it became stale. (We
6014  * need to hold a refcount while using the plan, anyway.) If replanning
6015  * is needed, do that work in the eval_mcontext.
6016  */
6017  oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
6018  cplan = SPI_plan_get_cached_plan(expr->plan);
6019  MemoryContextSwitchTo(oldcontext);
6020 
6021  /*
6022  * We can't get a failure here, because the number of CachedPlanSources in
6023  * the SPI plan can't change from what exec_simple_check_plan saw; it's a
6024  * property of the raw parsetree generated from the query text.
6025  */
6026  Assert(cplan != NULL);
6027 
6028  /* If it got replanned, update our copy of the simple expression */
6029  if (cplan->generation != expr->expr_simple_generation)
6030  {
6031  exec_save_simple_expr(expr, cplan);
6032  /* better recheck r/w safety, as it could change due to inlining */
6033  if (expr->rwparam >= 0)
6034  exec_check_rw_parameter(expr, expr->rwparam);
6035  }
6036 
6037  /*
6038  * Pass back previously-determined result type.
6039  */
6040  *rettype = expr->expr_simple_type;
6041  *rettypmod = expr->expr_simple_typmod;
6042 
6043  /*
6044  * Set up ParamListInfo to pass to executor. For safety, save and restore
6045  * estate->paramLI->parserSetupArg around our use of the param list.
6046  */
6047  save_setup_arg = estate->paramLI->parserSetupArg;
6048 
6049  econtext->ecxt_param_list_info = setup_param_list(estate, expr);
6050 
6051  /*
6052  * Prepare the expression for execution, if it's not been done already in
6053  * the current transaction. (This will be forced to happen if we called
6054  * exec_save_simple_expr above.)
6055  */
6056  if (expr->expr_simple_lxid != curlxid)
6057  {
6058  oldcontext = MemoryContextSwitchTo(estate->simple_eval_estate->es_query_cxt);
6059  expr->expr_simple_state =
6061  econtext->ecxt_param_list_info);
6062  expr->expr_simple_in_use = false;
6063  expr->expr_simple_lxid = curlxid;
6064  MemoryContextSwitchTo(oldcontext);
6065  }
6066 
6067  /*
6068  * We have to do some of the things SPI_execute_plan would do, in
6069  * particular advance the snapshot if we are in a non-read-only function.
6070  * Without this, stable functions within the expression would fail to see
6071  * updates made so far by our own function.
6072  */
6073  oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
6074  if (!estate->readonly_func)
6075  {
6078  }
6079 
6080  /*
6081  * Mark expression as busy for the duration of the ExecEvalExpr call.
6082  */
6083  expr->expr_simple_in_use = true;
6084 
6085  /*
6086  * Finally we can call the executor to evaluate the expression
6087  */
6088  *result = ExecEvalExpr(expr->expr_simple_state,
6089  econtext,
6090  isNull);
6091 
6092  /* Assorted cleanup */
6093  expr->expr_simple_in_use = false;
6094 
6095  econtext->ecxt_param_list_info = NULL;
6096 
6097  estate->paramLI->parserSetupArg = save_setup_arg;
6098 
6099  if (!estate->readonly_func)
6101 
6102  MemoryContextSwitchTo(oldcontext);
6103 
6104  /*
6105  * Now we can release our refcount on the cached plan.
6106  */
6107  ReleaseCachedPlan(cplan, true);
6108 
6109  /*
6110  * That's it.
6111  */
6112  return true;
6113 }
int expr_simple_generation
Definition: plpgsql.h:230
void * parserSetupArg
Definition: params.h:117
static void exec_check_rw_parameter(PLpgSQL_expr *expr, int target_dno)
Definition: pl_exec.c:7822
PGPROC * MyProc
Definition: proc.c:67
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void PopActiveSnapshot(void)
Definition: snapmgr.c:812
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:304
static void exec_save_simple_expr(PLpgSQL_expr *expr, CachedPlan *cplan)
Definition: pl_exec.c:7735
SPIPlanPtr plan
Definition: plpgsql.h:218
CachedPlan * SPI_plan_get_cached_plan(SPIPlanPtr plan)
Definition: spi.c:1704
MemoryContext es_query_cxt
Definition: execnodes.h:523
ParamListInfo paramLI
Definition: plpgsql.h:1025
EState * simple_eval_estate
Definition: plpgsql.h:1028
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:733
static Datum ExecEvalExpr(ExprState *state, ExprContext *econtext, bool *isNull)
Definition: executor.h:280
ExprState * ExecInitExprWithParams(Expr *node, ParamListInfo ext_params)
Definition: execExpr.c:156
void ReleaseCachedPlan(CachedPlan *plan, bool useResOwner)
Definition: plancache.c:1258
Expr * expr_simple_expr
Definition: plpgsql.h:229
uint32 LocalTransactionId
Definition: c.h:476
static ParamListInfo setup_param_list(PLpgSQL_execstate *estate, PLpgSQL_expr *expr)
Definition: pl_exec.c:6132
int rwparam
Definition: plpgsql.h:220
#define get_eval_mcontext(estate)
Definition: pl_exec.c:120
ExprState * expr_simple_state
Definition: plpgsql.h:240
void CommandCounterIncrement(void)
Definition: xact.c:914
LocalTransactionId expr_simple_lxid
Definition: plpgsql.h:242
#define Assert(condition)
Definition: c.h:699
ExprContext * eval_econtext
Definition: plpgsql.h:1042
bool readonly_func
Definition: plpgsql.h:993
int generation
Definition: plancache.h:141
int32 expr_simple_typmod
Definition: plpgsql.h:232
bool expr_simple_in_use
Definition: plpgsql.h:241
ParamListInfo ecxt_param_list_info
Definition: execnodes.h:230
Oid expr_simple_type
Definition: plpgsql.h:231
LocalTransactionId lxid
Definition: proc.h:106

◆ exec_eval_using_params()

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

Definition at line 8168 of file pl_exec.c.

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

Referenced by exec_dynquery_with_params(), and exec_stmt_dynexecute().

8169 {
8170  PreparedParamsData *ppd;
8171  MemoryContext stmt_mcontext = get_stmt_mcontext(estate);
8172  int nargs;
8173  int i;
8174  ListCell *lc;
8175 
8176  ppd = (PreparedParamsData *)
8177  MemoryContextAlloc(stmt_mcontext, sizeof(PreparedParamsData));
8178  nargs = list_length(params);
8179 
8180  ppd->nargs = nargs;
8181  ppd->types = (Oid *)
8182  MemoryContextAlloc(stmt_mcontext, nargs * sizeof(Oid));
8183  ppd->values = (Datum *)
8184  MemoryContextAlloc(stmt_mcontext, nargs * sizeof(Datum));
8185  ppd->nulls = (char *)
8186  MemoryContextAlloc(stmt_mcontext, nargs * sizeof(char));
8187 
8188  i = 0;
8189  foreach(lc, params)
8190  {
8191  PLpgSQL_expr *param = (PLpgSQL_expr *) lfirst(lc);
8192  bool isnull;
8193  int32 ppdtypmod;
8194  MemoryContext oldcontext;
8195 
8196  ppd->values[i] = exec_eval_expr(estate, param,
8197  &isnull,
8198  &ppd->types[i],
8199  &ppdtypmod);
8200  ppd->nulls[i] = isnull ? 'n' : ' ';
8201 
8202  oldcontext = MemoryContextSwitchTo(stmt_mcontext);
8203 
8204  if (ppd->types[i] == UNKNOWNOID)
8205  {
8206  /*
8207  * Treat 'unknown' parameters as text, since that's what most
8208  * people would expect. SPI_execute_with_args can coerce unknown
8209  * constants in a more intelligent way, but not unknown Params.
8210  * This code also takes care of copying into the right context.
8211  * Note we assume 'unknown' has the representation of C-string.
8212  */
8213  ppd->types[i] = TEXTOID;
8214  if (!isnull)
8216  }
8217  /* pass-by-ref non null values must be copied into stmt_mcontext */
8218  else if (!isnull)
8219  {
8220  int16 typLen;
8221  bool typByVal;
8222 
8223  get_typlenbyval(ppd->types[i], &typLen, &typByVal);
8224  if (!typByVal)
8225  ppd->values[i] = datumCopy(ppd->values[i], typByVal, typLen);
8226  }
8227 
8228  MemoryContextSwitchTo(oldcontext);
8229 
8230  exec_eval_cleanup(estate);
8231 
8232  i++;
8233  }
8234 
8235  return ppd;
8236 }
signed short int16
Definition: c.h:312
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
static void exec_eval_cleanup(PLpgSQL_execstate *estate)
Definition: pl_exec.c:3927
Datum * values
Definition: pl_exec.c:57
unsigned int Oid
Definition: postgres_ext.h:31
signed int int32
Definition: c.h:313
#define DatumGetCString(X)
Definition: postgres.h:551
static Datum exec_eval_expr(PLpgSQL_execstate *estate, PLpgSQL_expr *expr, bool *isNull, Oid *rettype, int32 *rettypmod)
Definition: pl_exec.c:5666
static MemoryContext get_stmt_mcontext(PLpgSQL_execstate *estate)
Definition: pl_exec.c:1446
Datum datumCopy(Datum value, bool typByVal, int typLen)
Definition: datum.c:128
uintptr_t Datum
Definition: postgres.h:367
#define lfirst(lc)
Definition: pg_list.h:106
static int list_length(const List *l)
Definition: pg_list.h:89
void get_typlenbyval(Oid typid, int16 *typlen, bool *typbyval)
Definition: lsyscache.c:2005
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:771
int i
#define CStringGetTextDatum(s)
Definition: builtins.h:95

◆ exec_for_query()

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

Definition at line 5814 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, tupleDesc::tdtypeid, SPITupleTable::tupdesc, UnpinPortal(), SPITupleTable::vals, and PLpgSQL_stmt_forq::var.

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

5816 {
5817  PLpgSQL_variable *var;
5818  SPITupleTable *tuptab;
5819  bool found = false;
5820  int rc = PLPGSQL_RC_OK;
5821  uint64 previous_id = INVALID_TUPLEDESC_IDENTIFIER;
5822  bool tupdescs_match = true;
5823  uint64 n;
5824 
5825  /* Fetch loop variable's datum entry */
5826  var = (PLpgSQL_variable *) estate->datums[stmt->var->dno];
5827 
5828  /*
5829  * Make sure the portal doesn't get closed by the user statements we
5830  * execute.
5831  */
5832  PinPortal(portal);
5833 
5834  /*
5835  * Fetch the initial tuple(s). If prefetching is allowed then we grab a
5836  * few more rows to avoid multiple trips through executor startup
5837  * overhead.
5838  */
5839  SPI_cursor_fetch(portal, true, prefetch_ok ? 10 : 1);
5840  tuptab = SPI_tuptable;
5841  n = SPI_processed;
5842 
5843  /*
5844  * If the query didn't return any rows, set the target to NULL and fall
5845  * through with found = false.
5846  */
5847  if (n == 0)
5848  {
5849  exec_move_row(estate, var, NULL, tuptab->tupdesc);
5850  exec_eval_cleanup(estate);
5851  }
5852  else
5853  found = true; /* processed at least one tuple */
5854 
5855  /*
5856  * Now do the loop
5857  */
5858  while (n > 0)
5859  {
5860  uint64 i;
5861 
5862  for (i = 0; i < n; i++)
5863  {
5864  /*
5865  * Assign the tuple to the target. Here, because we know that all
5866  * loop iterations should be assigning the same tupdesc, we can
5867  * optimize away repeated creations of expanded records with
5868  * identical tupdescs. Testing for changes of er_tupdesc_id is
5869  * reliable even if the loop body contains assignments that
5870  * replace the target's value entirely, because it's assigned from
5871  * a process-global counter. The case where the tupdescs don't
5872  * match could possibly be handled more efficiently than this
5873  * coding does, but it's not clear extra effort is worthwhile.
5874  */
5875  if (var->dtype == PLPGSQL_DTYPE_REC)
5876  {
5877  PLpgSQL_rec *rec = (PLpgSQL_rec *) var;
5878 
5879  if (rec->erh &&
5880  rec->erh->er_tupdesc_id == previous_id &&
5881  tupdescs_match)
5882  {
5883  /* Only need to assign a new tuple value */
5884  expanded_record_set_tuple(rec->erh, tuptab->vals[i],
5885  true, !estate->atomic);
5886  }
5887  else
5888  {
5889  /*
5890  * First time through, or var's tupdesc changed in loop,
5891  * or we have to do it the hard way because type coercion
5892  * is needed.
5893  */
5894  exec_move_row(estate, var,
5895  tuptab->vals[i], tuptab->tupdesc);
5896 
5897  /*
5898  * Check to see if physical assignment is OK next time.
5899  * Once the tupdesc comparison has failed once, we don't
5900  * bother rechecking in subsequent loop iterations.
5901  */
5902  if (tupdescs_match)
5903  {
5904  tupdescs_match =
5905  (rec->rectypeid == RECORDOID ||
5906  rec->rectypeid == tuptab->tupdesc->tdtypeid ||
5907  compatible_tupdescs(tuptab->tupdesc,
5909  }
5910  previous_id = rec->erh->er_tupdesc_id;
5911  }
5912  }
5913  else
5914  exec_move_row(estate, var, tuptab->vals[i], tuptab->tupdesc);
5915 
5916  exec_eval_cleanup(estate);
5917 
5918  /*
5919  * Execute the statements
5920  */
5921  rc = exec_stmts(estate, stmt->body);
5922 
5923  LOOP_RC_PROCESSING(stmt->label, goto loop_exit);
5924  }
5925 
5926  SPI_freetuptable(tuptab);
5927 
5928  /*
5929  * Fetch more tuples. If prefetching is allowed, grab 50 at a time.
5930  */
5931  SPI_cursor_fetch(portal, true, prefetch_ok ? 50 : 1);
5932  tuptab = SPI_tuptable;
5933  n = SPI_processed;
5934  }
5935 
5936 loop_exit:
5937 
5938  /*
5939  * Release last group of tuples (if any)
5940  */
5941  SPI_freetuptable(tuptab);
5942 
5943  UnpinPortal(portal);
5944 
5945  /*
5946  * Set the FOUND variable to indicate the result of executing the loop
5947  * (namely, whether we looped one or more times). This must be set last so
5948  * that it does not interfere with the value of the FOUND variable inside
5949  * the loop processing itself.
5950  */
5951  exec_set_found(estate, found);
5952 
5953  return rc;
5954 }
void UnpinPortal(Portal portal)
Definition: portalmem.c:377
Oid tdtypeid
Definition: tupdesc.h:83
void expanded_record_set_tuple(ExpandedRecordHeader *erh, HeapTuple tuple, bool copy, bool expand_external)
SPITupleTable * SPI_tuptable
Definition: spi.c:41
ExpandedRecordHeader * erh
Definition: plpgsql.h:379
static void exec_eval_cleanup(PLpgSQL_execstate *estate)
Definition: pl_exec.c:3927
HeapTuple * vals
Definition: spi.h:28
#define INVALID_TUPLEDESC_IDENTIFIER
Definition: typcache.h:145
uint64 SPI_processed
Definition: spi.c:39
PLpgSQL_datum ** datums
Definition: plpgsql.h:1015
void PinPortal(Portal portal)
Definition: portalmem.c:368
#define LOOP_RC_PROCESSING(looplabel, exit_action)
Definition: pl_exec.c:186
static TupleDesc expanded_record_get_tupdesc(ExpandedRecordHeader *erh)
void SPI_freetuptable(SPITupleTable *tuptable)
Definition: spi.c:1068
static bool compatible_tupdescs(TupleDesc src_tupdesc, TupleDesc dst_tupdesc)
Definition: pl_exec.c:7011
TupleDesc tupdesc
Definition: spi.h:27
PLpgSQL_datum_type dtype
Definition: plpgsql.h:265
PLpgSQL_variable * var
Definition: plpgsql.h:669
static void exec_set_found(PLpgSQL_execstate *estate, bool state)
Definition: pl_exec.c:7921
static void exec_move_row(PLpgSQL_execstate *estate, PLpgSQL_variable *target, HeapTuple tup, TupleDesc tupdesc)
Definition: pl_exec.c:6625
int i
void SPI_cursor_fetch(Portal portal, bool forward, long count)
Definition: spi.c:1445
Oid rectypeid
Definition: plpgsql.h:372
static int exec_stmts(PLpgSQL_execstate *estate, List *stmts)
Definition: pl_exec.c:1857

◆ exec_init_tuple_store()

static void exec_init_tuple_store ( PLpgSQL_execstate estate)
static

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

3476 {
3477  ReturnSetInfo *rsi = estate->rsi;
3478  MemoryContext oldcxt;
3479  ResourceOwner oldowner;
3480 
3481  /*
3482  * Check caller can handle a set result in the way we want
3483  */
3484  if (!rsi || !IsA(rsi, ReturnSetInfo) ||
3485  (rsi->allowedModes & SFRM_Materialize) == 0 ||
3486  rsi->expectedDesc == NULL)
3487  ereport(ERROR,
3488  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3489  errmsg("set-valued function called in context that cannot accept a set")));
3490 
3491  /*
3492  * Switch to the right memory context and resource owner for storing the
3493  * tuplestore for return set. If we're within a subtransaction opened for
3494  * an exception-block, for example, we must still create the tuplestore in
3495  * the resource owner that was active when this function was entered, and
3496  * not in the subtransaction resource owner.
3497  */
3498  oldcxt = MemoryContextSwitchTo(estate->tuple_store_cxt);
3499  oldowner = CurrentResourceOwner;
3501 
3502  estate->tuple_store =
3504  false, work_mem);
3505 
3506  CurrentResourceOwner = oldowner;
3507  MemoryContextSwitchTo(oldcxt);
3508 
3509  estate->tuple_store_desc = rsi->expectedDesc;
3510 }
#define IsA(nodeptr, _type_)
Definition: nodes.h:567
ResourceOwner tuple_store_owner
Definition: plpgsql.h:1003
ResourceOwner CurrentResourceOwner
Definition: resowner.c:140
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
int errcode(int sqlerrcode)
Definition: elog.c:575
TupleDesc expectedDesc
Definition: execnodes.h:296
TupleDesc tuple_store_desc
Definition: plpgsql.h:1001
#define ERROR
Definition: elog.h:43
MemoryContext tuple_store_cxt
Definition: plpgsql.h:1002
ReturnSetInfo * rsi
Definition: plpgsql.h:1004
#define ereport(elevel, rest)
Definition: elog.h:122
Tuplestorestate * tuple_store
Definition: plpgsql.h:1000
Tuplestorestate * tuplestore_begin_heap(bool randomAccess, bool interXact, int maxKBytes)
Definition: tuplestore.c:318
int work_mem
Definition: globals.c:120
int allowedModes
Definition: execnodes.h:297
int errmsg(const char *fmt,...)
Definition: elog.c:797

◆ exec_move_row()

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

Definition at line 6625 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(), tupleDesc::natts, PLPGSQL_DTYPE_REC, PLpgSQL_rec::rectypeid, tupleDesc::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().

6628 {
6629  ExpandedRecordHeader *newerh = NULL;
6630 
6631  /*
6632  * If target is RECORD, we may be able to avoid field-by-field processing.
6633  */
6634  if (target->dtype == PLPGSQL_DTYPE_REC)
6635  {
6636  PLpgSQL_rec *rec = (PLpgSQL_rec *) target;
6637 
6638  /*
6639  * If we have no source tupdesc, just set the record variable to NULL.
6640  * (If we have a source tupdesc but not a tuple, we'll set the
6641  * variable to a row of nulls, instead. This is odd perhaps, but
6642  * backwards compatible.)
6643  */
6644  if (tupdesc == NULL)
6645  {
6646  if (rec->datatype &&
6647  rec->datatype->typtype == TYPTYPE_DOMAIN)
6648  {
6649  /*
6650  * If it's a composite domain, NULL might not be a legal
6651  * value, so we instead need to make an empty expanded record
6652  * and ensure that domain type checking gets done. If there
6653  * is already an expanded record, piggyback on its lookups.
6654  */
6655  newerh = make_expanded_record_for_rec(estate, rec,
6656  NULL, rec->erh);
6657  expanded_record_set_tuple(newerh, NULL, false, false);
6658  assign_record_var(estate, rec, newerh);
6659  }
6660  else
6661  {
6662  /* Just clear it to NULL */
6663  if (rec->erh)
6665  rec->erh = NULL;
6666  }
6667  return;
6668  }
6669 
6670  /*
6671  * Build a new expanded record with appropriate tupdesc.
6672  */
6673  newerh = make_expanded_record_for_rec(estate, rec, tupdesc, NULL);
6674 
6675  /*
6676  * If the rowtypes match, or if we have no tuple anyway, we can
6677  * complete the assignment without field-by-field processing.
6678  *
6679  * The tests here are ordered more or less in order of cheapness. We
6680  * can easily detect it will work if the target is declared RECORD or
6681  * has the same typeid as the source. But when assigning from a query
6682  * result, it's common to have a source tupdesc that's labeled RECORD
6683  * but is actually physically compatible with a named-composite-type
6684  * target, so it's worth spending extra cycles to check for that.
6685  */
6686  if (rec->rectypeid == RECORDOID ||
6687  rec->rectypeid == tupdesc->tdtypeid ||
6688  !HeapTupleIsValid(tup) ||
6690  {
6691  if (!HeapTupleIsValid(tup))
6692  {
6693  /* No data, so force the record into all-nulls state */
6695  }
6696  else
6697  {
6698  /* No coercion is needed, so just assign the row value */
6699  expanded_record_set_tuple(newerh, tup, true, !estate->atomic);
6700  }
6701 
6702  /* Complete the assignment */
6703  assign_record_var(estate, rec, newerh);
6704 
6705  return;
6706  }
6707  }
6708 
6709  /*
6710  * Otherwise, deconstruct the tuple and do field-by-field assignment,
6711  * using exec_move_row_from_fields.
6712  */
6713  if (tupdesc && HeapTupleIsValid(tup))
6714  {
6715  int td_natts = tupdesc->natts;
6716  Datum *values;
6717  bool *nulls;
6718  Datum values_local[64];
6719  bool nulls_local[64];
6720 
6721  /*
6722  * Need workspace arrays. If td_natts is small enough, use local
6723  * arrays to save doing a palloc. Even if it's not small, we can
6724  * allocate both the Datum and isnull arrays in one palloc chunk.
6725  */
6726  if (td_natts <= lengthof(values_local))
6727  {
6728  values = values_local;
6729  nulls = nulls_local;
6730  }
6731  else
6732  {
6733  char *chunk;
6734 
6735  chunk = eval_mcontext_alloc(estate,
6736  td_natts * (sizeof(Datum) + sizeof(bool)));
6737  values = (Datum *) chunk;
6738  nulls = (bool *) (chunk + td_natts * sizeof(Datum));
6739  }
6740 
6741  heap_deform_tuple(tup, tupdesc, values, nulls);
6742 
6743  exec_move_row_from_fields(estate, target, newerh,
6744  values, nulls, tupdesc);
6745  }
6746  else
6747  {
6748  /*
6749  * Assign all-nulls.
6750  */
6751  exec_move_row_from_fields(estate, target, newerh,
6752  NULL, NULL, NULL);
6753  }
6754 }
Oid tdtypeid
Definition: tupdesc.h:83
PLpgSQL_type * datatype
Definition: plpgsql.h:371
static void assign_record_var(PLpgSQL_execstate *estate, PLpgSQL_rec *rec, ExpandedRecordHeader *erh)
Definition: pl_exec.c:8145
void expanded_record_set_tuple(ExpandedRecordHeader *erh, HeapTuple tuple, bool copy, bool expand_external)
ExpandedRecordHeader * erh
Definition: plpgsql.h:379
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:6828
#define lengthof(array)
Definition: c.h:629
int natts
Definition: tupdesc.h:82
static ExpandedRecordHeader * make_expanded_record_for_rec(PLpgSQL_execstate *estate, PLpgSQL_rec *rec, TupleDesc srctupdesc, ExpandedRecordHeader *srcerh)
Definition: pl_exec.c:6770
#define eval_mcontext_alloc(estate, sz)
Definition: pl_exec.c:122
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:7011
void DeleteExpandedObject(Datum d)
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
PLpgSQL_datum_type dtype
Definition: plpgsql.h:265
char typtype
Definition: plpgsql.h:206
void heap_deform_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *values, bool *isnull)
Definition: heaptuple.c:1315
static Datum values[MAXATTR]
Definition: bootstrap.c:164
Oid rectypeid
Definition: plpgsql.h:372
#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 7141 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, 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().

7144 {
7145  /* Check to see if source is an expanded record */
7147  {
7149  ExpandedRecordHeader *newerh = NULL;
7150 
7151  Assert(erh->er_magic == ER_MAGIC);
7152 
7153  /* These cases apply if the target is record not row... */
7154  if (target->dtype == PLPGSQL_DTYPE_REC)
7155  {
7156  PLpgSQL_rec *rec = (PLpgSQL_rec *) target;
7157 
7158  /*
7159  * If it's the same record already stored in the variable, do
7160  * nothing. This would happen only in silly cases like "r := r",
7161  * but we need some check to avoid possibly freeing the variable's
7162  * live value below. Note that this applies even if what we have
7163  * is a R/O pointer.
7164  */
7165  if (erh == rec->erh)
7166  return;
7167 
7168  /*
7169  * If we have a R/W pointer, we're allowed to just commandeer
7170  * ownership of the expanded record. If it's of the right type to
7171  * put into the record variable, do that. (Note we don't accept
7172  * an expanded record of a composite-domain type as a RECORD
7173  * value. We'll treat it as the base composite type instead;
7174  * compare logic in make_expanded_record_for_rec.)
7175  */
7177  (rec->rectypeid == erh->er_decltypeid ||
7178  (rec->rectypeid == RECORDOID &&
7179  !ExpandedRecordIsDomain(erh))))
7180  {
7181  assign_record_var(estate, rec, erh);
7182  return;
7183  }
7184 
7185  /*
7186  * If we already have an expanded record object in the target
7187  * variable, and the source record contains a valid tuple
7188  * representation with the right rowtype, then we can skip making
7189  * a new expanded record and just assign the tuple with
7190  * expanded_record_set_tuple. (We can't do the equivalent if we
7191  * have to do field-by-field assignment, since that wouldn't be
7192  * atomic if there's an error.) We consider that there's a
7193  * rowtype match only if it's the same named composite type or
7194  * same registered rowtype; checking for matches of anonymous
7195  * rowtypes would be more expensive than this is worth.
7196  */
7197  if (rec->erh &&
7198  (erh->flags & ER_FLAG_FVALUE_VALID) &&
7199  erh->er_typeid == rec->erh->er_typeid &&
7200  (erh->er_typeid != RECORDOID ||
7201  (erh->er_typmod == rec->erh->er_typmod &&
7202  erh->er_typmod >= 0)))
7203  {
7205  true, !estate->atomic);
7206  return;
7207  }
7208 
7209  /*
7210  * Otherwise we're gonna need a new expanded record object. Make
7211  * it here in hopes of piggybacking on the source object's
7212  * previous typcache lookup.
7213  */
7214  newerh = make_expanded_record_for_rec(estate, rec, NULL, erh);
7215 
7216  /*
7217  * If the expanded record contains a valid tuple representation,
7218  * and we don't need rowtype conversion, then just copying the
7219  * tuple is probably faster than field-by-field processing. (This
7220  * isn't duplicative of the previous check, since here we will
7221  * catch the case where the record variable was previously empty.)
7222  */
7223  if ((erh->flags & ER_FLAG_FVALUE_VALID) &&
7224  (rec->rectypeid == RECORDOID ||
7225  rec->rectypeid == erh->er_typeid))
7226  {
7227  expanded_record_set_tuple(newerh, erh->fvalue,
7228  true, !estate->atomic);
7229  assign_record_var(estate, rec, newerh);
7230  return;
7231  }
7232 
7233  /*
7234  * Need to special-case empty source record, else code below would
7235  * leak newerh.
7236  */
7237  if (ExpandedRecordIsEmpty(erh))
7238  {
7239  /* Set newerh to a row of NULLs */
7241  assign_record_var(estate, rec, newerh);
7242  return;
7243  }
7244  } /* end of record-target-only cases */
7245 
7246  /*
7247  * If the source expanded record is empty, we should treat that like a
7248  * NULL tuple value. (We're unlikely to see such a case, but we must
7249  * check this; deconstruct_expanded_record would cause a change of
7250  * logical state, which is not OK.)
7251  */
7252  if (ExpandedRecordIsEmpty(erh))
7253  {
7254  exec_move_row(estate, target, NULL,
7256  return;
7257  }
7258 
7259  /*
7260  * Otherwise, ensure that the source record is deconstructed, and
7261  * assign from its field values.
7262  */
7264  exec_move_row_from_fields(estate, target, newerh,
7265  erh->dvalues, erh->dnulls,
7267  }
7268  else
7269  {
7270  /*
7271  * Nope, we've got a plain composite Datum. Deconstruct it; but we
7272  * don't use deconstruct_composite_datum(), because we may be able to
7273  * skip calling lookup_rowtype_tupdesc().
7274  */
7275  HeapTupleHeader td;
7276  HeapTupleData tmptup;
7277  Oid tupType;
7278  int32 tupTypmod;
7279  TupleDesc tupdesc;
7280  MemoryContext oldcontext;
7281 
7282  /* Ensure that any detoasted data winds up in the eval_mcontext */
7283  oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
7284  /* Get tuple body (note this could involve detoasting) */
7286  MemoryContextSwitchTo(oldcontext);
7287 
7288  /* Build a temporary HeapTuple control structure */
7289  tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
7290  ItemPointerSetInvalid(&(tmptup.t_self));
7291  tmptup.t_tableOid = InvalidOid;
7292  tmptup.t_data = td;
7293 
7294  /* Extract rowtype info */
7295  tupType = HeapTupleHeaderGetTypeId(td);
7296  tupTypmod = HeapTupleHeaderGetTypMod(td);
7297 
7298  /* Now, if the target is record not row, maybe we can optimize ... */
7299  if (target->dtype == PLPGSQL_DTYPE_REC)
7300  {
7301  PLpgSQL_rec *rec = (PLpgSQL_rec *) target;
7302 
7303  /*
7304  * If we already have an expanded record object in the target
7305  * variable, and the source datum has a matching rowtype, then we
7306  * can skip making a new expanded record and just assign the tuple
7307  * with expanded_record_set_tuple. We consider that there's a
7308  * rowtype match only if it's the same named composite type or
7309  * same registered rowtype. (Checking to reject an anonymous
7310  * rowtype here should be redundant, but let's be safe.)
7311  */
7312  if (rec->erh &&
7313  tupType == rec->erh->er_typeid &&
7314  (tupType != RECORDOID ||
7315  (tupTypmod == rec->erh->er_typmod &&
7316  tupTypmod >= 0)))
7317  {
7318  expanded_record_set_tuple(rec->erh, &tmptup,
7319  true, !estate->atomic);
7320  return;
7321  }
7322 
7323  /*
7324  * If the source datum has a rowtype compatible with the target
7325  * variable, just build a new expanded record and assign the tuple
7326  * into it. Using make_expanded_record_from_typeid() here saves
7327  * one typcache lookup compared to the code below.
7328  */
7329  if (rec->rectypeid == RECORDOID || rec->rectypeid == tupType)
7330  {
7331  ExpandedRecordHeader *newerh;
7332  MemoryContext mcontext = get_eval_mcontext(estate);
7333 
7334  newerh = make_expanded_record_from_typeid(tupType, tupTypmod,
7335  mcontext);
7336  expanded_record_set_tuple(newerh, &tmptup,
7337  true, !estate->atomic);
7338  assign_record_var(estate, rec, newerh);
7339  return;
7340  }
7341 
7342  /*
7343  * Otherwise, we're going to need conversion, so fall through to
7344  * do it the hard way.
7345  */
7346  }
7347 
7348  /*
7349  * ROW target, or unoptimizable RECORD target, so we have to expend a
7350  * lookup to obtain the source datum's tupdesc.
7351  */
7352  tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
7353 
7354  /* Do the move */
7355  exec_move_row(estate, target, &tmptup, tupdesc);
7356 
7357  /* Release tupdesc usage count */
7358  ReleaseTupleDesc(tupdesc);
7359  }
7360 }
#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:1641
static void assign_record_var(PLpgSQL_execstate *estate, PLpgSQL_rec *rec, ExpandedRecordHeader *erh)
Definition: pl_exec.c:8145
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:379
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:6828
unsigned int Oid
Definition: postgres_ext.h:31
#define DatumGetHeapTupleHeader(X)
Definition: fmgr.h:264
signed int int32
Definition: c.h:313
HeapTupleHeader t_data
Definition: htup.h:68
#define HeapTupleHeaderGetTypMod(tup)
Definition: htup_details.h:467
static ExpandedRecordHeader * make_expanded_record_for_rec(PLpgSQL_execstate *estate, PLpgSQL_rec *rec, TupleDesc srctupdesc, ExpandedRecordHeader *srcerh)
Definition: pl_exec.c:6770
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:120
#define ER_MAGIC
#define HeapTupleHeaderGetTypeId(tup)
Definition: htup_details.h:457
static struct @131 value
#define InvalidOid
Definition: postgres_ext.h:36
#define Assert(condition)
Definition: c.h:699
PLpgSQL_datum_type dtype
Definition: plpgsql.h:265
#define DatumGetPointer(X)
Definition: postgres.h:534
#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:6625
#define VARATT_IS_EXTERNAL_EXPANDED_RW(PTR)
Definition: postgres.h:320
Oid rectypeid
Definition: plpgsql.h:372
#define ReleaseTupleDesc(tupdesc)
Definition: tupdesc.h:124
#define ExpandedRecordIsDomain(erh)
void deconstruct_expanded_record(ExpandedRecordHeader *erh)
#define HeapTupleHeaderGetDatumLength(tup)
Definition: htup_details.h:451

◆ 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 6828 of file pl_exec.c.

References Assert, assign_record_var(), PLpgSQL_execstate::atomic, PLpgSQL_execstate::datums, PLpgSQL_variable::dtype, elog, ERROR, eval_mcontext_alloc, exec_assign_value(), exec_cast_value(), expanded_record_get_tupdesc(), expanded_record_set_fields(), lengthof, tupleDesc::natts, PLpgSQL_row::nfields, PLPGSQL_DTYPE_REC, PLPGSQL_DTYPE_ROW, TupleDescAttr, value, and PLpgSQL_row::varnos.

Referenced by exec_move_row(), and exec_move_row_from_datum().

6833 {
6834  int td_natts = tupdesc ? tupdesc->natts : 0;
6835  int fnum;
6836  int anum;
6837 
6838  /* Handle RECORD-target case */
6839  if (target->dtype == PLPGSQL_DTYPE_REC)
6840  {
6841  PLpgSQL_rec *rec = (PLpgSQL_rec *) target;
6842  TupleDesc var_tupdesc;
6843  Datum newvalues_local[64];
6844  bool newnulls_local[64];
6845 
6846  Assert(newerh != NULL); /* caller must have built new object */
6847 
6848  var_tupdesc = expanded_record_get_tupdesc(newerh);
6849 
6850  /*
6851  * Coerce field values if needed. This might involve dealing with
6852  * different sets of dropped columns and/or coercing individual column
6853  * types. That's sort of a pain, but historically plpgsql has allowed
6854  * it, so we preserve the behavior. However, it's worth a quick check
6855  * to see if the tupdescs are identical. (Since expandedrecord.c
6856  * prefers to use refcounted tupdescs from the typcache, expanded
6857  * records with the same rowtype will have pointer-equal tupdescs.)
6858  */
6859  if (var_tupdesc != tupdesc)
6860  {
6861  int vtd_natts = var_tupdesc->natts;
6862  Datum *newvalues;
6863  bool *newnulls;
6864 
6865  /*
6866  * Need workspace arrays. If vtd_natts is small enough, use local
6867  * arrays to save doing a palloc. Even if it's not small, we can
6868  * allocate both the Datum and isnull arrays in one palloc chunk.
6869  */
6870  if (vtd_natts <= lengthof(newvalues_local))
6871  {
6872  newvalues = newvalues_local;
6873  newnulls = newnulls_local;
6874  }
6875  else
6876  {
6877  char *chunk;
6878 
6879  chunk = eval_mcontext_alloc(estate,
6880  vtd_natts * (sizeof(Datum) + sizeof(bool)));
6881  newvalues = (Datum *) chunk;
6882  newnulls = (bool *) (chunk + vtd_natts * sizeof(Datum));
6883  }
6884 
6885  /* Walk over destination columns */
6886  anum = 0;
6887  for (fnum = 0; fnum < vtd_natts; fnum++)
6888  {
6889  Form_pg_attribute attr = TupleDescAttr(var_tupdesc, fnum);
6890  Datum value;
6891  bool isnull;
6892  Oid valtype;
6893  int32 valtypmod;
6894 
6895  if (attr->attisdropped)
6896  {
6897  /* expanded_record_set_fields should ignore this column */
6898  continue; /* skip dropped column in record */
6899  }
6900 
6901  while (anum < td_natts &&
6902  TupleDescAttr(tupdesc, anum)->attisdropped)
6903  anum++; /* skip dropped column in tuple */
6904 
6905  if (anum < td_natts)
6906  {
6907  value = values[anum];
6908  isnull = nulls[anum];
6909  valtype = TupleDescAttr(tupdesc, anum)->atttypid;
6910  valtypmod = TupleDescAttr(tupdesc, anum)->atttypmod;
6911  anum++;
6912  }
6913  else
6914  {
6915  value = (Datum) 0;
6916  isnull = true;
6917  valtype = UNKNOWNOID;
6918  valtypmod = -1;
6919  }
6920 
6921  /* Cast the new value to the right type, if needed. */
6922  newvalues[fnum] = exec_cast_value(estate,
6923  value,
6924  &isnull,
6925  valtype,
6926  valtypmod,
6927  attr->atttypid,
6928  attr->atttypmod);
6929  newnulls[fnum] = isnull;
6930  }
6931 
6932  values = newvalues;
6933  nulls = newnulls;
6934  }
6935 
6936  /* Insert the coerced field values into the new expanded record */
6937  expanded_record_set_fields(newerh, values, nulls, !estate->atomic);
6938 
6939  /* Complete the assignment */
6940  assign_record_var(estate, rec, newerh);
6941 
6942  return;
6943  }
6944 
6945  /* newerh should not have been passed in non-RECORD cases */
6946  Assert(newerh == NULL);
6947 
6948  /*
6949  * For a row, we assign the individual field values to the variables the
6950  * row points to.
6951  *
6952  * NOTE: both this code and the record code above silently ignore extra
6953  * columns in the source and assume NULL for missing columns. This is
6954  * pretty dubious but it's the historical behavior.
6955  *
6956  * If we have no input data at all, we'll assign NULL to all columns of
6957  * the row variable.
6958  */
6959  if (target->dtype == PLPGSQL_DTYPE_ROW)
6960  {
6961  PLpgSQL_row *row = (PLpgSQL_row *) target;
6962 
6963  anum = 0;
6964  for (fnum = 0; fnum < row->nfields; fnum++)
6965  {
6966  PLpgSQL_var *var;
6967  Datum value;
6968  bool isnull;
6969  Oid valtype;
6970  int32 valtypmod;
6971 
6972  var = (PLpgSQL_var *) (estate->datums[row->varnos[fnum]]);
6973 
6974  while (anum < td_natts &&
6975  TupleDescAttr(tupdesc, anum)->attisdropped)
6976  anum++; /* skip dropped column in tuple */
6977 
6978  if (anum < td_natts)
6979  {
6980  value = values[anum];
6981  isnull = nulls[anum];
6982  valtype = TupleDescAttr(tupdesc, anum)->atttypid;
6983  valtypmod = TupleDescAttr(tupdesc, anum)->atttypmod;
6984  anum++;
6985  }
6986  else
6987  {
6988  value = (Datum) 0;
6989  isnull = true;
6990  valtype = UNKNOWNOID;
6991  valtypmod = -1;
6992  }
6993 
6994  exec_assign_value(estate, (PLpgSQL_datum *) var,
6995  value, isnull, valtype, valtypmod);
6996  }
6997 
6998  return;
6999  }
7000 
7001  elog(ERROR, "unsupported target type: %d", target->dtype);
7002 }
static void assign_record_var(PLpgSQL_execstate *estate, PLpgSQL_rec *rec, ExpandedRecordHeader *erh)
Definition: pl_exec.c:8145
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:93
void expanded_record_set_fields(ExpandedRecordHeader *erh, const Datum *newValues, const bool *isnulls, bool expand_external)
#define lengthof(array)
Definition: c.h:629
unsigned int Oid
Definition: postgres_ext.h:31
int natts
Definition: tupdesc.h:82
signed int int32
Definition: c.h:313
PLpgSQL_datum ** datums
Definition: plpgsql.h:1015
static Datum exec_cast_value(PLpgSQL_execstate *estate, Datum value, bool *isnull, Oid valtype, int32 valtypmod, Oid reqtype, int32 reqtypmod)
Definition: pl_exec.c:7430
#define ERROR
Definition: elog.h:43
#define eval_mcontext_alloc(estate, sz)
Definition: pl_exec.c:122
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:197
static TupleDesc expanded_record_get_tupdesc(ExpandedRecordHeader *erh)
int * varnos
Definition: plpgsql.h:354
uintptr_t Datum
Definition: postgres.h:367
static struct @131 value
#define Assert(condition)
Definition: c.h:699
int nfields
Definition: plpgsql.h:352
PLpgSQL_datum_type dtype
Definition: plpgsql.h:265
static Datum values[MAXATTR]
Definition: bootstrap.c:164
#define elog
Definition: elog.h:219
static void exec_assign_value(PLpgSQL_execstate *estate, PLpgSQL_datum *target, Datum value, bool isNull, Oid valtype, int32 valtypmod)
Definition: pl_exec.c:4870

◆ exec_prepare_plan()

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

Definition at line 3948 of file pl_exec.c.

References elog, ereport, errcode(), errhint(), errmsg(), ERROR, exec_simple_check_plan(), PLpgSQL_expr::func, PLpgSQL_execstate::func, plpgsql_parser_setup(), PLpgSQL_expr::query, SPI_ERROR_COPY, SPI_ERROR_TRANSACTION, SPI_keepplan(), SPI_prepare_params(), SPI_result, and SPI_result_code_string().

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

3951 {
3952  SPIPlanPtr plan;
3953 
3954  /*
3955  * The grammar can't conveniently set expr->func while building the parse
3956  * tree, so make sure it's set before parser hooks need it.
3957  */
3958  expr->func = estate->func;
3959 
3960  /*
3961  * Generate and save the plan
3962  */
3963  plan = SPI_prepare_params(expr->query,
3965  (void *) expr,
3966  cursorOptions);
3967  if (plan == NULL)
3968  {
3969  /* Some SPI errors deserve specific error messages */
3970  switch (SPI_result)
3971  {
3972  case SPI_ERROR_COPY:
3973  ereport(ERROR,
3974  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3975  errmsg("cannot COPY to/from client in PL/pgSQL")));
3976  break;
3977  case SPI_ERROR_TRANSACTION:
3978  ereport(ERROR,
3979  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3980  errmsg("cannot begin/end transactions in PL/pgSQL"),
3981  errhint("Use a BEGIN block with an EXCEPTION clause instead.")));
3982  break;
3983  default:
3984  elog(ERROR, "SPI_prepare_params failed for \"%s\": %s",
3986  break;
3987  }
3988  }
3989  if (keepplan)
3990  SPI_keepplan(plan);
3991  expr->plan = plan;
3992 
3993  /* Check to see if it's a simple expression */
3994  exec_simple_check_plan(estate, expr);
3995 
3996  /*
3997  * Mark expression as not using a read-write param. exec_assign_value has
3998  * to take steps to override this if appropriate; that seems cleaner than
3999  * adding parameters to all other callers.
4000  */
4001  expr->rwparam = -1;
4002 }
int errhint(const char *fmt,...)
Definition: elog.c:987
char * query
Definition: plpgsql.h:217
#define SPI_ERROR_COPY
Definition: spi.h:37
int errcode(int sqlerrcode)
Definition: elog.c:575
PLpgSQL_function * func
Definition: plpgsql.h:980
static void exec_simple_check_plan(PLpgSQL_execstate *estate, PLpgSQL_expr *expr)
Definition: pl_exec.c:7636
SPIPlanPtr plan
Definition: plpgsql.h:218
int SPI_result
Definition: spi.c:42
#define ERROR
Definition: elog.h:43
const char * SPI_result_code_string(int code)
Definition: spi.c:1611
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:1051
int SPI_keepplan(SPIPlanPtr plan)
Definition: spi.c:656
#define ereport(elevel, rest)
Definition: elog.h:122
#define SPI_ERROR_TRANSACTION
Definition: spi.h:43
int rwparam
Definition: plpgsql.h:220
struct PLpgSQL_function * func
Definition: plpgsql.h:223
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define elog
Definition: elog.h:219
SPIPlanPtr SPI_prepare_params(const char *src, ParserSetupHook parserSetup, void *parserSetupArg, int cursorOptions)
Definition: spi.c:619

◆ exec_run_select()

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

Definition at line 5749 of file pl_exec.c.

References Assert, CURSOR_OPT_PARALLEL_OK, elog, ereport, errcode(), errmsg(), ERROR, PLpgSQL_execstate::eval_lastoid, 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_lastoid, SPI_OK_CURSOR, SPI_OK_SELECT, SPI_processed, SPI_result, SPI_result_code_string(), and SPI_tuptable.

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

5751 {
5752  ParamListInfo paramLI;
5753  int rc;
5754 
5755  /*
5756  * On the first call for this expression generate the plan.
5757  *
5758  * If we don't need to return a portal, then we're just going to execute
5759  * the query once, which means it's OK to use a parallel plan, even if the
5760  * number of rows being fetched is limited. If we do need to return a
5761  * portal, the caller might do cursor operations, which parallel query
5762  * can't support.
5763  */
5764  if (expr->plan == NULL)
5765  exec_prepare_plan(estate, expr,
5766  portalP == NULL ? CURSOR_OPT_PARALLEL_OK : 0, true);
5767 
5768  /*
5769  * Set up ParamListInfo to pass to executor
5770  */
5771  paramLI = setup_param_list(estate, expr);
5772 
5773  /*
5774  * If a portal was requested, put the query and paramlist into the portal
5775  */
5776  if (portalP != NULL)
5777  {
5778  *portalP = SPI_cursor_open_with_paramlist(NULL, expr->plan,
5779  paramLI,
5780  estate->readonly_func);
5781  if (*portalP == NULL)
5782  elog(ERROR, "could not open implicit cursor for query \"%s\": %s",
5784  exec_eval_cleanup(estate);
5785  return SPI_OK_CURSOR;
5786  }
5787 
5788  /*
5789  * Execute the query
5790  */
5791  rc = SPI_execute_plan_with_paramlist(expr->plan, paramLI,
5792  estate->readonly_func, maxtuples);
5793  if (rc != SPI_OK_SELECT)
5794  ereport(ERROR,
5795  (errcode(ERRCODE_SYNTAX_ERROR),
5796  errmsg("query \"%s\" is not a SELECT", expr->query)));
5797 
5798  /* Save query results for eventual cleanup */
5799  Assert(estate->eval_tuptable == NULL);
5800  estate->eval_tuptable = SPI_tuptable;
5801  estate->eval_processed = SPI_processed;
5802  estate->eval_lastoid = SPI_lastoid;
5803 
5804  return rc;
5805 }
char * query
Definition: plpgsql.h:217
static void exec_prepare_plan(PLpgSQL_execstate *estate, PLpgSQL_expr *expr, int cursorOptions, bool keepplan)
Definition: pl_exec.c:3948
SPITupleTable * eval_tuptable
Definition: plpgsql.h:1039
uint64 eval_processed
Definition: plpgsql.h:1040
Portal SPI_cursor_open_with_paramlist(const char *name, SPIPlanPtr plan, ParamListInfo params, bool read_only)
Definition: spi.c:1206
SPITupleTable * SPI_tuptable
Definition: spi.c:41
int errcode(int sqlerrcode)
Definition: elog.c:575
static void exec_eval_cleanup(PLpgSQL_execstate *estate)
Definition: pl_exec.c:3927
#define SPI_OK_CURSOR
Definition: spi.h:59
uint64 SPI_processed
Definition: spi.c:39
SPIPlanPtr plan
Definition: plpgsql.h:218
int SPI_result
Definition: spi.c:42
#define ERROR
Definition: elog.h:43
int SPI_execute_plan_with_paramlist(SPIPlanPtr plan, ParamListInfo params, bool read_only, long tcount)
Definition: spi.c:469
const char * SPI_result_code_string(int code)
Definition: spi.c:1611
static ParamListInfo setup_param_list(PLpgSQL_execstate *estate, PLpgSQL_expr *expr)
Definition: pl_exec.c:6132
#define ereport(elevel, rest)
Definition: elog.h:122
Oid SPI_lastoid
Definition: spi.c:40
#define SPI_OK_SELECT
Definition: spi.h:54
#define Assert(condition)
Definition: c.h:699
bool readonly_func
Definition: plpgsql.h:993
#define CURSOR_OPT_PARALLEL_OK
Definition: parsenodes.h:2653
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define elog
Definition: elog.h:219

◆ exec_save_simple_expr()

static void exec_save_simple_expr ( PLpgSQL_expr expr,
CachedPlan cplan 
)
static

Definition at line 7735 of file pl_exec.c.

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

Referenced by exec_eval_simple_expr(), and exec_simple_check_plan().

7736 {
7737  PlannedStmt *stmt;
7738  Plan *plan;
7739  Expr *tle_expr;
7740 
7741  /*
7742  * Given the checks that exec_simple_check_plan did, none of the Asserts
7743  * here should ever fail.
7744  */
7745 
7746  /* Extract the single PlannedStmt */
7747  Assert(list_length(cplan->stmt_list) == 1);
7748  stmt = linitial_node(PlannedStmt, cplan->stmt_list);
7749  Assert(stmt->commandType == CMD_SELECT);
7750 
7751  /*
7752  * Ordinarily, the plan node should be a simple Result. However, if
7753  * force_parallel_mode is on, the planner might've stuck a Gather node
7754  * atop that. The simplest way to deal with this is to look through the
7755  * Gather node. The Gather node's tlist would normally contain a Var
7756  * referencing the child node's output, but it could also be a Param, or
7757  * it could be a Const that setrefs.c copied as-is.
7758  */
7759  plan = stmt->planTree;
7760  for (;;)
7761  {
7762  /* Extract the single tlist expression */
7763  Assert(list_length(plan->targetlist) == 1);
7764  tle_expr = castNode(TargetEntry, linitial(plan->targetlist))->expr;
7765 
7766  if (IsA(plan, Result))
7767  {
7768  Assert(plan->lefttree == NULL &&
7769  plan->righttree == NULL &&
7770  plan->initPlan == NULL &&
7771  plan->qual == NULL &&
7772  ((Result *) plan)->resconstantqual == NULL);
7773  break;
7774  }
7775  else if (IsA(plan, Gather))
7776  {
7777  Assert(plan->lefttree != NULL &&
7778  plan->righttree == NULL &&
7779  plan->initPlan == NULL &&
7780  plan->qual == NULL);
7781  /* If setrefs.c copied up a Const, no need to look further */
7782  if (IsA(tle_expr, Const))
7783  break;
7784  /* Otherwise, it had better be a Param or an outer Var */
7785  Assert(IsA(tle_expr, Param) ||(IsA(tle_expr, Var) &&
7786  ((Var *) tle_expr)->varno == OUTER_VAR));
7787  /* Descend to the child node */
7788  plan = plan->lefttree;
7789  }
7790  else
7791  elog(ERROR, "unexpected plan node type: %d",
7792  (int) nodeTag(plan));
7793  }
7794 
7795  /*
7796  * Save the simple expression, and initialize state to "not valid in
7797  * current transaction".
7798  */
7799  expr->expr_simple_expr = tle_expr;
7800  expr->expr_simple_generation = cplan->generation;
7801  expr->expr_simple_state = NULL;
7802  expr->expr_simple_in_use = false;
7804  /* Also stash away the expression result type */
7805  expr->expr_simple_type = exprType((Node *) tle_expr);
7806  expr->expr_simple_typmod = exprTypmod((Node *) tle_expr);
7807 }
int expr_simple_generation
Definition: plpgsql.h:230
List * qual
Definition: plannodes.h:148
#define IsA(nodeptr, _type_)
Definition: nodes.h:567
#define castNode(_type_, nodeptr)
Definition: nodes.h:585
int32 exprTypmod(const Node *expr)
Definition: nodeFuncs.c:276
Definition: nodes.h:516
Definition: primnodes.h:163
#define linitial_node(type, l)
Definition: pg_list.h:114
struct Plan * planTree
Definition: plannodes.h:64
struct Plan * righttree
Definition: plannodes.h:150
#define linitial(l)
Definition: pg_list.h:111
#define ERROR
Definition: elog.h:43
Expr * expr_simple_expr
Definition: plpgsql.h:229
ExprState * expr_simple_state
Definition: plpgsql.h:240
CmdType commandType
Definition: plannodes.h:46
LocalTransactionId expr_simple_lxid
Definition: plpgsql.h:242
#define Assert(condition)
Definition: c.h:699
Oid exprType(const Node *expr)
Definition: nodeFuncs.c:42
int generation
Definition: plancache.h:141
static int list_length(const List *l)
Definition: pg_list.h:89
struct Plan * lefttree
Definition: plannodes.h:149
#define nodeTag(nodeptr)
Definition: nodes.h:521
List * targetlist
Definition: plannodes.h:147
int32 expr_simple_typmod
Definition: plpgsql.h:232
List * initPlan
Definition: plannodes.h:151
#define InvalidLocalTransactionId
Definition: lock.h:69
List * stmt_list
Definition: plancache.h:133
bool expr_simple_in_use
Definition: plpgsql.h:241
#define elog
Definition: elog.h:219
#define OUTER_VAR
Definition: primnodes.h:154
Oid expr_simple_type
Definition: plpgsql.h:231

◆ exec_set_found()

static void exec_set_found ( PLpgSQL_execstate estate,
bool  state 
)
static

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

7922 {
7923  PLpgSQL_var *var;
7924 
7925  var = (PLpgSQL_var *) (estate->datums[estate->found_varno]);
7926  assign_simple_var(estate, var, BoolGetDatum(state), false, false);
7927 }
static void assign_simple_var(PLpgSQL_execstate *estate, PLpgSQL_var *var, Datum newvalue, bool isnull, bool freeable)
Definition: pl_exec.c:8069
PLpgSQL_datum ** datums
Definition: plpgsql.h:1015
#define BoolGetDatum(X)
Definition: postgres.h:387
Definition: regguts.h:298

◆ exec_simple_check_plan()

static void exec_simple_check_plan ( PLpgSQL_execstate estate,
PLpgSQL_expr expr 
)
static

Definition at line 7636 of file pl_exec.c.

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

Referenced by exec_prepare_plan().

7637 {
7638  List *plansources;
7639  CachedPlanSource *plansource;
7640  Query *query;
7641  CachedPlan *cplan;
7642  MemoryContext oldcontext;
7643 
7644  /*
7645  * Initialize to "not simple".
7646  */
7647  expr->expr_simple_expr = NULL;
7648 
7649  /*
7650  * Check the analyzed-and-rewritten form of the query to see if we will be
7651  * able to treat it as a simple expression. Since this function is only
7652  * called immediately after creating the CachedPlanSource, we need not
7653  * worry about the query being stale.
7654  */
7655 
7656  /*
7657  * We can only test queries that resulted in exactly one CachedPlanSource
7658  */
7659  plansources = SPI_plan_get_plan_sources(expr->plan);
7660  if (list_length(plansources) != 1)
7661  return;
7662  plansource = (CachedPlanSource *) linitial(plansources);
7663 
7664  /*
7665  * 1. There must be one single querytree.
7666  */
7667  if (list_length(plansource->query_list) != 1)
7668  return;
7669  query = (Query *) linitial(plansource->query_list);
7670 
7671  /*
7672  * 2. It must be a plain SELECT query without any input tables
7673  */
7674  if (!IsA(query, Query))
7675  return;
7676  if (query->commandType != CMD_SELECT)
7677  return;
7678  if (query->rtable != NIL)
7679  return;
7680 
7681  /*
7682  * 3. Can't have any subplans, aggregates, qual clauses either. (These
7683  * tests should generally match what inline_function() checks before
7684  * inlining a SQL function; otherwise, inlining could change our
7685  * conclusion about whether an expression is simple, which we don't want.)
7686  */
7687  if (query->hasAggs ||
7688  query->hasWindowFuncs ||
7689  query->hasTargetSRFs ||
7690  query->hasSubLinks ||
7691  query->cteList ||
7692  query->jointree->fromlist ||
7693  query->jointree->quals ||
7694  query->groupClause ||
7695  query->groupingSets ||
7696  query->havingQual ||
7697  query->windowClause ||
7698  query->distinctClause ||
7699  query->sortClause ||
7700  query->limitOffset ||
7701  query->limitCount ||
7702  query->setOperations)
7703  return;
7704 
7705  /*
7706  * 4. The query must have a single attribute as result
7707  */
7708  if (list_length(query->targetList) != 1)
7709  return;
7710 
7711  /*
7712  * OK, we can treat it as a simple plan.
7713  *
7714  * Get the generic plan for the query. If replanning is needed, do that
7715  * work in the eval_mcontext.
7716  */
7717  oldcontext = MemoryContextSwitchTo(get_eval_mcontext(estate));
7718  cplan = SPI_plan_get_cached_plan(expr->plan);
7719  MemoryContextSwitchTo(oldcontext);
7720 
7721  /* Can't fail, because we checked for a single CachedPlanSource above */
7722  Assert(cplan != NULL);
7723 
7724  /* Share the remaining work with replan code path */
7725  exec_save_simple_expr(expr, cplan);
7726 
7727  /* Release our plan refcount */
7728  ReleaseCachedPlan(cplan, true);
7729 }
Node * limitOffset
Definition: parsenodes.h:160
#define NIL
Definition: pg_list.h:69
#define IsA(nodeptr, _type_)
Definition: nodes.h:567
List * sortClause
Definition: parsenodes.h:158
FromExpr * jointree
Definition: parsenodes.h:138
bool hasAggs
Definition: parsenodes.h:125
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
List * groupingSets
Definition: parsenodes.h:150
List * fromlist
Definition: primnodes.h:1478
Node * quals
Definition: primnodes.h:1479
static void exec_save_simple_expr(PLpgSQL_expr *expr, CachedPlan *cplan)
Definition: pl_exec.c:7735
SPIPlanPtr plan
Definition: plpgsql.h:218
List * windowClause
Definition: parsenodes.h:154
List * targetList
Definition: parsenodes.h:140
CachedPlan * SPI_plan_get_cached_plan(SPIPlanPtr plan)
Definition: spi.c:1704
#define linitial(l)
Definition: pg_list.h:111
List * rtable
Definition: parsenodes.h:137
List * distinctClause
Definition: parsenodes.h:156
Node * limitCount
Definition: parsenodes.h:161
void ReleaseCachedPlan(CachedPlan *plan, bool useResOwner)
Definition: plancache.c:1258
Expr * expr_simple_expr
Definition: plpgsql.h:229
#define get_eval_mcontext(estate)
Definition: pl_exec.c:120
CmdType commandType
Definition: parsenodes.h:112
bool hasTargetSRFs
Definition: parsenodes.h:127
#define Assert(condition)
Definition: c.h:699
bool hasWindowFuncs
Definition: parsenodes.h:126
static int list_length(const List *l)
Definition: pg_list.h:89
List * cteList
Definition: parsenodes.h:135
Node * setOperations
Definition: parsenodes.h:165
List * groupClause
Definition: parsenodes.h:148
bool hasSubLinks
Definition: parsenodes.h:128
List * SPI_plan_get_plan_sources(SPIPlanPtr plan)
Definition: spi.c:1688
List * query_list
Definition: plancache.h:95
Node * havingQual
Definition: parsenodes.h:152
Definition: pg_list.h:45

◆ exec_stmt()

static int exec_stmt ( PLpgSQL_execstate estate,
PLpgSQL_stmt stmt 
)
static

Definition at line 1891 of file pl_exec.c.

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

Referenced by exec_stmts().

1892 {
1893  PLpgSQL_stmt *save_estmt;
1894  int rc = -1;
1895 
1896  save_estmt = estate->err_stmt;
1897  estate->err_stmt = stmt;
1898 
1899  /* Let the plugin know that we are about to execute this statement */
1900  if (*plpgsql_plugin_ptr && (*plpgsql_plugin_ptr)->stmt_beg)
1901  ((*plpgsql_plugin_ptr)->stmt_beg) (estate, stmt);
1902 
1904 
1905  switch (stmt->cmd_type)
1906  {
1907  case PLPGSQL_STMT_BLOCK:
1908  rc = exec_stmt_block(estate, (PLpgSQL_stmt_block *) stmt);
1909  break;
1910 
1911  case PLPGSQL_STMT_ASSIGN:
1912  rc = exec_stmt_assign(estate, (PLpgSQL_stmt_assign *) stmt);
1913  break;
1914 
1915  case PLPGSQL_STMT_PERFORM:
1916  rc = exec_stmt_perform(estate, (PLpgSQL_stmt_perform *) stmt);
1917  break;
1918 
1919  case PLPGSQL_STMT_CALL:
1920  rc = exec_stmt_call(estate, (PLpgSQL_stmt_call *) stmt);
1921  break;
1922 
1923  case PLPGSQL_STMT_GETDIAG:
1924  rc = exec_stmt_getdiag(estate, (PLpgSQL_stmt_getdiag *) stmt);
1925  break;
1926 
1927  case PLPGSQL_STMT_IF:
1928  rc = exec_stmt_if(estate, (PLpgSQL_stmt_if *) stmt);
1929  break;
1930 
1931  case PLPGSQL_STMT_CASE:
1932  rc = exec_stmt_case(estate, (PLpgSQL_stmt_case *) stmt);
1933  break;
1934 
1935  case PLPGSQL_STMT_LOOP:
1936  rc = exec_stmt_loop(estate, (PLpgSQL_stmt_loop *) stmt);
1937  break;
1938 
1939  case PLPGSQL_STMT_WHILE:
1940  rc = exec_stmt_while(estate, (PLpgSQL_stmt_while *) stmt);
1941  break;
1942 
1943  case PLPGSQL_STMT_FORI:
1944  rc = exec_stmt_fori(estate, (PLpgSQL_stmt_fori *) stmt);
1945  break;
1946 
1947  case PLPGSQL_STMT_FORS:
1948  rc = exec_stmt_fors(estate, (PLpgSQL_stmt_fors *) stmt);
1949  break;
1950 
1951  case PLPGSQL_STMT_FORC:
1952  rc = exec_stmt_forc(estate, (PLpgSQL_stmt_forc *) stmt);
1953  break;
1954 
1956  rc = exec_stmt_foreach_a(estate, (PLpgSQL_stmt_foreach_a *) stmt);
1957  break;
1958 
1959  case PLPGSQL_STMT_EXIT:
1960  rc = exec_stmt_exit(estate, (PLpgSQL_stmt_exit *) stmt);
1961  break;
1962 
1963  case PLPGSQL_STMT_RETURN:
1964  rc = exec_stmt_return(estate, (PLpgSQL_stmt_return *) stmt);
1965  break;
1966 
1968  rc = exec_stmt_return_next(estate, (PLpgSQL_stmt_return_next *) stmt);
1969  break;
1970 
1972  rc = exec_stmt_return_query(estate, (PLpgSQL_stmt_return_query *) stmt);
1973  break;
1974 
1975  case PLPGSQL_STMT_RAISE:
1976  rc = exec_stmt_raise(estate, (PLpgSQL_stmt_raise *) stmt);
1977  break;
1978 
1979  case PLPGSQL_STMT_ASSERT:
1980  rc = exec_stmt_assert(estate, (PLpgSQL_stmt_assert *) stmt);
1981  break;
1982 
1983  case PLPGSQL_STMT_EXECSQL:
1984  rc = exec_stmt_execsql(estate, (PLpgSQL_stmt_execsql *) stmt);
1985  break;
1986 
1988  rc = exec_stmt_dynexecute(estate, (PLpgSQL_stmt_dynexecute *) stmt);
1989  break;
1990 
1991  case PLPGSQL_STMT_DYNFORS:
1992  rc = exec_stmt_dynfors(estate, (PLpgSQL_stmt_dynfors *) stmt);
1993  break;
1994 
1995  case PLPGSQL_STMT_OPEN:
1996  rc = exec_stmt_open(estate, (PLpgSQL_stmt_open *) stmt);
1997  break;
1998 
1999  case PLPGSQL_STMT_FETCH:
2000  rc = exec_stmt_fetch(estate, (PLpgSQL_stmt_fetch *) stmt);
2001  break;
2002 
2003  case PLPGSQL_STMT_CLOSE:
2004  rc = exec_stmt_close(estate, (PLpgSQL_stmt_close *) stmt);
2005  break;
2006 
2007  case PLPGSQL_STMT_COMMIT:
2008  rc = exec_stmt_commit(estate, (PLpgSQL_stmt_commit *) stmt);
2009  break;
2010 
2011  case PLPGSQL_STMT_ROLLBACK:
2012  rc = exec_stmt_rollback(estate, (PLpgSQL_stmt_rollback *) stmt);
2013  break;
2014 
2015  case PLPGSQL_STMT_SET:
2016  rc = exec_stmt_set(estate, (PLpgSQL_stmt_set *) stmt);
2017  break;
2018 
2019  default:
2020  estate->err_stmt = save_estmt;
2021  elog(ERROR, "unrecognized cmd_type: %d", stmt->cmd_type);
2022  }
2023 
2024  /* Let the plugin know that we have finished executing this statement */
2025  if (*plpgsql_plugin_ptr && (*plpgsql_plugin_ptr)->stmt_end)
2026  ((*plpgsql_plugin_ptr)->stmt_end) (estate, stmt);
2027 
2028  estate->err_stmt = save_estmt;
2029 
2030  return rc;
2031 }
static int exec_stmt_set(PLpgSQL_execstate *estate, PLpgSQL_stmt_set *stmt)
Definition: pl_exec.c:4780
static int exec_stmt_execsql(PLpgSQL_execstate *estate, PLpgSQL_stmt_execsql *stmt)
Definition: pl_exec.c:4013
static int exec_stmt_case(PLpgSQL_execstate *estate, PLpgSQL_stmt_case *stmt)
Definition: pl_exec.c:2401
PLpgSQL_stmt * err_stmt
Definition: plpgsql.h:1045
static int exec_stmt_call(PLpgSQL_execstate *estate, PLpgSQL_stmt_call *stmt)
Definition: pl_exec.c:2071
static int exec_stmt_return_query(PLpgSQL_execstate *estate, PLpgSQL_stmt_return_query *stmt)
Definition: pl_exec.c:3398
static int exec_stmt_foreach_a(PLpgSQL_execstate *estate, PLpgSQL_stmt_foreach_a *stmt)
Definition: pl_exec.c:2848
static int exec_stmt_open(PLpgSQL_execstate *estate, PLpgSQL_stmt_open *stmt)
Definition: pl_exec.c:4449
static int exec_stmt_dynfors(PLpgSQL_execstate *estate, PLpgSQL_stmt_dynfors *stmt)
Definition: pl_exec.c:4422
static int exec_stmt_loop(PLpgSQL_execstate *estate, PLpgSQL_stmt_loop *stmt)
Definition: pl_exec.c:2487
static int exec_stmt_fors(PLpgSQL_execstate *estate, PLpgSQL_stmt_fors *stmt)
Definition: pl_exec.c:2683
static int exec_stmt_assign(PLpgSQL_execstate *estate, PLpgSQL_stmt_assign *stmt)
Definition: pl_exec.c:2040
#define ERROR
Definition: elog.h:43
static int exec_stmt_rollback(PLpgSQL_execstate *estate, PLpgSQL_stmt_rollback *stmt)
Definition: pl_exec.c:4758
static int exec_stmt_assert(PLpgSQL_execstate *estate, PLpgSQL_stmt_assert *stmt)
Definition: pl_exec.c:3738
static int exec_stmt_raise(PLpgSQL_execstate *estate, PLpgSQL_stmt_raise *stmt)
Definition: pl_exec.c:3527
static int exec_stmt_fori(PLpgSQL_execstate *estate, PLpgSQL_stmt_fori *stmt)
Definition: pl_exec.c:2540
static int exec_stmt_dynexecute(PLpgSQL_execstate *estate, PLpgSQL_stmt_dynexecute *stmt)
Definition: pl_exec.c:4230
PLpgSQL_plugin ** plpgsql_plugin_ptr
Definition: pl_handler.c:58
static int exec_stmt_getdiag(PLpgSQL_execstate *estate, PLpgSQL_stmt_getdiag *stmt)
Definition: pl_exec.c:2255
static int exec_stmt_exit(PLpgSQL_execstate *estate, PLpgSQL_stmt_exit *stmt)
Definition: pl_exec.c:3004
static int exec_stmt_return(PLpgSQL_execstate *estate, PLpgSQL_stmt_return *stmt)
Definition: pl_exec.c:3037
static int exec_stmt_while(PLpgSQL_execstate *estate, PLpgSQL_stmt_while *stmt)
Definition: pl_exec.c:2509
static int exec_stmt_commit(PLpgSQL_execstate *estate, PLpgSQL_stmt_commit *stmt)
Definition: pl_exec.c:4739
static int exec_stmt_fetch(PLpgSQL_execstate *estate, PLpgSQL_stmt_fetch *stmt)
Definition: pl_exec.c:4605
static int exec_stmt_block(PLpgSQL_execstate *estate, PLpgSQL_stmt_block *block)
Definition: pl_exec.c:1531
static int exec_stmt_return_next(PLpgSQL_execstate *estate, PLpgSQL_stmt_return_next *stmt)
Definition: pl_exec.c:3180
static int exec_stmt_close(PLpgSQL_execstate *estate, PLpgSQL_stmt_close *stmt)
Definition: pl_exec.c:4696
static int exec_stmt_if(PLpgSQL_execstate *estate, PLpgSQL_stmt_if *stmt)
Definition: pl_exec.c:2371
static int exec_stmt_perform(PLpgSQL_execstate *estate, PLpgSQL_stmt_perform *stmt)
Definition: pl_exec.c:2056
PLpgSQL_stmt_type cmd_type
Definition: plpgsql.h:444
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:98
void(* stmt_end)(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
Definition: plpgsql.h:1088
#define elog
Definition: elog.h:219
void(* stmt_beg)(PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt)
Definition: plpgsql.h:1087
static int exec_stmt_forc(PLpgSQL_execstate *estate, PLpgSQL_stmt_forc *stmt)
Definition: pl_exec.c:2712

◆ exec_stmt_assert()

static int exec_stmt_assert ( PLpgSQL_execstate estate,
PLpgSQL_stmt_assert stmt 
)
static

Definition at line 3738 of file pl_exec.c.

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

Referenced by exec_stmt().

3739 {
3740  bool value;
3741  bool isnull;
3742 
3743  /* do nothing when asserts are not enabled */
3744  if (!plpgsql_check_asserts)
3745  return PLPGSQL_RC_OK;
3746 
3747  value = exec_eval_boolean(estate, stmt->cond, &isnull);
3748  exec_eval_cleanup(estate);
3749 
3750  if (isnull || !value)
3751  {
3752  char *message = NULL;
3753 
3754  if (stmt->message != NULL)
3755  {
3756  Datum val;
3757  Oid typeid;
3758  int32 typmod;
3759 
3760  val = exec_eval_expr(estate, stmt->message,
3761  &isnull, &typeid, &typmod);
3762  if (!isnull)
3763  message = convert_value_to_string(estate, val, typeid);
3764  /* we mustn't do exec_eval_cleanup here */
3765  }
3766 
3767  ereport(ERROR,
3768  (errcode(ERRCODE_ASSERT_FAILURE),
3769  message ? errmsg_internal("%s", message) :
3770  errmsg("assertion failed")));
3771  }
3772 
3773  return PLPGSQL_RC_OK;
3774 }
int errcode(int sqlerrcode)
Definition: elog.c:575
static void exec_eval_cleanup(PLpgSQL_execstate *estate)
Definition: pl_exec.c:3927
unsigned int Oid
Definition: postgres_ext.h:31
signed int int32
Definition: c.h:313
#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:5666
PLpgSQL_expr * message
Definition: plpgsql.h:849
static bool exec_eval_boolean(PLpgSQL_execstate *estate, PLpgSQL_expr *expr, bool *isNull)
Definition: pl_exec.c:5643
#define ereport(elevel, rest)
Definition: elog.h:122
uintptr_t Datum
Definition: postgres.h:367
static struct @131 value
int errmsg_internal(const char *fmt,...)
Definition: elog.c:827
int errmsg(const char *fmt,...)
Definition: elog.c:797
static char * convert_value_to_string(PLpgSQL_execstate *estate, Datum value, Oid valtype)
Definition: pl_exec.c:7401
PLpgSQL_expr * cond
Definition: plpgsql.h:848
bool plpgsql_check_asserts
Definition: pl_handler.c:50
long val
Definition: informix.c:689

◆ exec_stmt_assign()

static int exec_stmt_assign ( PLpgSQL_execstate estate,
PLpgSQL_stmt_assign stmt 
)
static

Definition at line 2040 of file pl_exec.c.

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

Referenced by exec_stmt().

2041 {
2042  Assert(stmt->varno >= 0);
2043 
2044  exec_assign_expr(estate, estate->datums[stmt->varno], stmt->expr);
2045 
2046  return PLPGSQL_RC_OK;
2047 }
PLpgSQL_datum ** datums
Definition: plpgsql.h:1015
static void exec_assign_expr(PLpgSQL_execstate *estate, PLpgSQL_datum *target, PLpgSQL_expr *expr)
Definition: pl_exec.c:4805
#define Assert(condition)
Definition: c.h:699
PLpgSQL_expr * expr
Definition: plpgsql.h:500

◆ exec_stmt_block()

static int exec_stmt_block ( PLpgSQL_execstate estate,
PLpgSQL_stmt_block block 
)
static

Definition at line 1531 of file pl_exec.c.

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

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

1532 {
1533  volatile int rc = -1;
1534  int i;
1535 
1536  /*
1537  * First initialize all variables declared in this block
1538  */
1539  estate->err_text = gettext_noop("during statement block local variable initialization");
1540 
1541  for (i = 0; i < block->n_initvars; i++)
1542  {
1543  int n = block->initvarnos[i];
1544  PLpgSQL_datum *datum = estate->datums[n];
1545 
1546  /*
1547  * The set of dtypes handled here must match plpgsql_add_initdatums().
1548  *
1549  * Note that we currently don't support promise datums within blocks,
1550  * only at a function's outermost scope, so we needn't handle those
1551  * here.
1552  */
1553  switch (datum->dtype)
1554  {
1555  case PLPGSQL_DTYPE_VAR:
1556  {
1557  PLpgSQL_var *var = (PLpgSQL_var *) datum;
1558 
1559  /*
1560  * Free any old value, in case re-entering block, and
1561  * initialize to NULL
1562  */
1563  assign_simple_var(estate, var, (Datum) 0, true, false);
1564 
1565  if (var->default_val == NULL)
1566  {
1567  /*
1568  * If needed, give the datatype a chance to reject
1569  * NULLs, by assigning a NULL to the variable. We
1570  * claim the value is of type UNKNOWN, not the var's
1571  * datatype, else coercion will be skipped.
1572  */
1573  if (var->datatype->typtype == TYPTYPE_DOMAIN)
1574  exec_assign_value(estate,
1575  (PLpgSQL_datum *) var,
1576  (Datum) 0,
1577  true,
1578  UNKNOWNOID,
1579  -1);
1580 
1581  /* parser should have rejected NOT NULL */
1582  Assert(!var->notnull);
1583  }
1584  else
1585  {
1586  exec_assign_expr(estate, (PLpgSQL_datum *) var,
1587  var->default_val);
1588  }
1589  }
1590  break;
1591 
1592  case PLPGSQL_DTYPE_REC:
1593  {
1594  PLpgSQL_rec *rec = (PLpgSQL_rec *) datum;
1595 
1596  /*
1597  * Deletion of any existing object will be handled during
1598  * the assignments below, and in some cases it's more
1599  * efficient for us not to get rid of it beforehand.
1600  */
1601  if (rec->default_val == NULL)
1602  {
1603  /*
1604  * If needed, give the datatype a chance to reject
1605  * NULLs, by assigning a NULL to the variable.
1606  */
1607  exec_move_row(estate, (PLpgSQL_variable *) rec,
1608  NULL, NULL);
1609 
1610  /* parser should have rejected NOT NULL */
1611  Assert(!rec->notnull);
1612  }
1613  else
1614  {
1615  exec_assign_expr(estate, (PLpgSQL_datum *) rec,
1616  rec->default_val);
1617  }
1618  }
1619  break;
1620 
1621  default:
1622  elog(ERROR, "unrecognized dtype: %d", datum->dtype);
1623  }
1624  }
1625 
1626  if (block->exceptions)
1627  {
1628  /*
1629  * Execute the statements in the block's body inside a sub-transaction
1630  */
1631  MemoryContext oldcontext = CurrentMemoryContext;
1633  ExprContext *old_eval_econtext = estate->eval_econtext;
1634  ErrorData *save_cur_error = estate->cur_error;
1635  MemoryContext stmt_mcontext;
1636 
1637  estate->err_text = gettext_noop("during statement block entry");
1638 
1639  /*
1640  * We will need a stmt_mcontext to hold the error data if an error
1641  * occurs. It seems best to force it to exist before entering the
1642  * subtransaction, so that we reduce the risk of out-of-memory during
1643  * error recovery, and because this greatly simplifies restoring the
1644  * stmt_mcontext stack to the correct state after an error. We can
1645  * ameliorate the cost of this by allowing the called statements to
1646  * use this mcontext too; so we don't push it down here.
1647  */
1648  stmt_mcontext = get_stmt_mcontext(estate);
1649 
1651  /* Want to run statements inside function's memory context */
1652  MemoryContextSwitchTo(oldcontext);
1653 
1654  PG_TRY();
1655  {
1656  /*
1657  * We need to run the block's statements with a new eval_econtext
1658  * that belongs to the current subtransaction; if we try to use
1659  * the outer econtext then ExprContext shutdown callbacks will be
1660  * called at the wrong times.
1661  */
1662  plpgsql_create_econtext(estate);
1663 
1664  estate->err_text = NULL;
1665 
1666  /* Run the block's statements */
1667  rc = exec_stmts(estate, block->body);
1668 
1669  estate->err_text = gettext_noop("during statement block exit");
1670 
1671  /*
1672  * If the block ended with RETURN, we may need to copy the return
1673  * value out of the subtransaction eval_context. We can avoid a
1674  * physical copy if the value happens to be a R/W expanded object.
1675  */
1676  if (rc == PLPGSQL_RC_RETURN &&
1677  !estate->retisset &&
1678  !estate->retisnull)
1679  {
1680  int16 resTypLen;
1681  bool resTypByVal;
1682 
1683  get_typlenbyval(estate->rettype, &resTypLen, &resTypByVal);
1684  estate->retval = datumTransfer(estate->retval,
1685  resTypByVal, resTypLen);
1686  }
1687 
1688  /* Commit the inner transaction, return to outer xact context */
1690  MemoryContextSwitchTo(oldcontext);
1691  CurrentResourceOwner = oldowner;
1692 
1693  /* Assert that the stmt_mcontext stack is unchanged */
1694  Assert(stmt_mcontext == estate->stmt_mcontext);
1695 
1696  /*
1697  * Revert to outer eval_econtext. (The inner one was
1698  * automatically cleaned up during subxact exit.)
1699  */
1700  estate->eval_econtext = old_eval_econtext;
1701  }
1702  PG_CATCH();
1703  {
1704  ErrorData *edata;
1705  ListCell *e;
1706 
1707  estate->err_text = gettext_noop("during exception cleanup");
1708 
1709  /* Save error info in our stmt_mcontext */
1710  MemoryContextSwitchTo(stmt_mcontext);
1711  edata = CopyErrorData();
1712  FlushErrorState();
1713 
1714  /* Abort the inner transaction */
1716  MemoryContextSwitchTo(oldcontext);
1717  CurrentResourceOwner = oldowner;
1718 
1719  /*
1720  * Set up the stmt_mcontext stack as though we had restored our
1721  * previous state and then done push_stmt_mcontext(). The push is
1722  * needed so that statements in the exception handler won't
1723  * clobber the error data that's in our stmt_mcontext.
1724  */
1725  estate->stmt_mcontext_parent = stmt_mcontext;
1726  estate->stmt_mcontext = NULL;
1727 
1728  /*
1729  * Now we can delete any nested stmt_mcontexts that might have
1730  * been created as children of ours. (Note: we do not immediately
1731  * release any statement-lifespan data that might have been left
1732  * behind in stmt_mcontext itself. We could attempt that by doing
1733  * a MemoryContextReset on it before collecting the error data
1734  * above, but it seems too risky to do any significant amount of
1735  * work before collecting the error.)
1736  */
1737  MemoryContextDeleteChildren(stmt_mcontext);
1738 
1739  /* Revert to outer eval_econtext */
1740  estate->eval_econtext = old_eval_econtext;
1741 
1742  /*
1743  * Must clean up the econtext too. However, any tuple table made
1744  * in the subxact will have been thrown away by SPI during subxact
1745  * abort, so we don't need to (and mustn't try to) free the
1746  * eval_tuptable.
1747  */
1748  estate->eval_tuptable = NULL;
1749  exec_eval_cleanup(estate);
1750 
1751  /* Look for a matching exception handler */
1752  foreach(e, block->exceptions->exc_list)
1753  {
1754  PLpgSQL_exception *exception = (PLpgSQL_exception *) lfirst(e);
1755 
1756  if (exception_matches_conditions(edata, exception->conditions))
1757  {
1758  /*
1759  * Initialize the magic SQLSTATE and SQLERRM variables for
1760  * the exception block; this also frees values from any
1761  * prior use of the same exception. We needn't do this
1762  * until we have found a matching exception.
1763  */
1764  PLpgSQL_var *state_var;
1765  PLpgSQL_var *errm_var;
1766 
1767  state_var = (PLpgSQL_var *)
1768  estate->datums[block->exceptions->sqlstate_varno];
1769  errm_var = (PLpgSQL_var *)
1770  estate->datums[block->exceptions->sqlerrm_varno];
1771 
1772  assign_text_var(estate, state_var,
1773  unpack_sql_state(edata->sqlerrcode));
1774  assign_text_var(estate, errm_var, edata->message);
1775 
1776  /*
1777  * Also set up cur_error so the error data is accessible
1778  * inside the handler.
1779  */
1780  estate->cur_error = edata;
1781 
1782  estate->err_text = NULL;
1783 
1784  rc = exec_stmts(estate, exception->action);
1785 
1786  break;
1787  }
1788  }
1789 
1790  /*
1791  * Restore previous state of cur_error, whether or not we executed
1792  * a handler. This is needed in case an error got thrown from
1793  * some inner block's exception handler.
1794  */
1795  estate->cur_error = save_cur_error;
1796 
1797  /* If no match found, re-throw the error */
1798  if (e == NULL)
1799  ReThrowError(edata);
1800 
1801  /* Restore stmt_mcontext stack and release the error data */
1802  pop_stmt_mcontext(estate);
1803  MemoryContextReset(stmt_mcontext);
1804  }
1805  PG_END_TRY();
1806 
1807  Assert(save_cur_error == estate->cur_error);
1808  }
1809  else
1810  {
1811  /*
1812  * Just execute the statements in the block's body
1813  */
1814  estate->err_text = NULL;
1815 
1816  rc = exec_stmts(estate, block->body);
1817  }
1818 
1819  estate->err_text = NULL;
1820 
1821  /*
1822  * Handle the return code. This is intentionally different from
1823  * LOOP_RC_PROCESSING(): CONTINUE never matches a block, and EXIT matches
1824  * a block only if there is a label match.
1825  */
1826  switch (rc)
1827  {
1828  case PLPGSQL_RC_OK:
1829  case PLPGSQL_RC_RETURN:
1830  case PLPGSQL_RC_CONTINUE:
1831  return rc;
1832 
1833  case PLPGSQL_RC_EXIT:
1834  if (estate->exitlabel == NULL)
1835  return PLPGSQL_RC_EXIT;
1836  if (block->label == NULL)
1837  return PLPGSQL_RC_EXIT;
1838  if (strcmp(block->label, estate->exitlabel) != 0)
1839  return PLPGSQL_RC_EXIT;
1840  estate->exitlabel = NULL;
1841  return PLPGSQL_RC_OK;
1842 
1843  default:
1844  elog(ERROR, "unrecognized rc: %d", rc);
1845  }
1846 
1847  return PLPGSQL_RC_OK;
1848 }
signed short int16
Definition: c.h:312
SPITupleTable * eval_tuptable
Definition: plpgsql.h:1039
int sqlerrcode
Definition: elog.h:342
ErrorData * CopyErrorData(void)
Definition: elog.c:1497
ResourceOwner CurrentResourceOwner
Definition: resowner.c:140
void ReleaseCurrentSubTransaction(void)
Definition: xact.c:4217
char * unpack_sql_state(int sql_state)
Definition: elog.c:2849
PLpgSQL_type * datatype
Definition: plpgsql.h:296
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define gettext_noop(x)
Definition: c.h:1036
static void assign_simple_var(PLpgSQL_execstate *estate, PLpgSQL_var *var, Datum newvalue, bool isnull, bool freeable)
Definition: pl_exec.c:8069
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:136
static void exec_eval_cleanup(PLpgSQL_execstate *estate)
Definition: pl_exec.c:3927
PLpgSQL_datum_type dtype
Definition: plpgsql.h:253
void FlushErrorState(void)
Definition: elog.c:1587
PLpgSQL_datum ** datums
Definition: plpgsql.h:1015
static void exec_assign_expr(PLpgSQL_execstate *estate, PLpgSQL_datum *target, PLpgSQL_expr *expr)
Definition: pl_exec.c:4805
#define ERROR
Definition: elog.h:43
PLpgSQL_expr * default_val
Definition: plpgsql.h:293
void RollbackAndReleaseCurrentSubTransaction(void)
Definition: xact.c:4251
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
static MemoryContext get_stmt_mcontext(PLpgSQL_execstate *estate)
Definition: pl_exec.c:1446
static bool exception_matches_conditions(ErrorData *edata, PLpgSQL_condition *cond)
Definition: pl_exec.c:1497
void MemoryContextDeleteChildren(MemoryContext context)
Definition: mcxt.c:256
ErrorData * cur_error
Definition: plpgsql.h:998
MemoryContext stmt_mcontext_parent
Definition: plpgsql.h:1036
uintptr_t Datum
Definition: postgres.h:367
const char * err_text
Definition: plpgsql.h:1046
PLpgSQL_condition * conditions
Definition: plpgsql.h:474
Datum datumTransfer(Datum value, bool typByVal, int typLen)
Definition: datum.c:190
#define PG_CATCH()
Definition: elog.h:293
static void assign_text_var(PLpgSQL_execstate *estate, PLpgSQL_var *var, const char *str)
Definition: pl_exec.c:8136
#define Assert(condition)
Definition: c.h:699
#define lfirst(lc)
Definition: pg_list.h:106
PLpgSQL_exception_block * exceptions
Definition: plpgsql.h:489
void BeginInternalSubTransaction(const char *name)
Definition: xact.c:4146
ExprContext * eval_econtext
Definition: plpgsql.h:1042
void get_typlenbyval(Oid typid, int16 *typlen, bool *typbyval)
Definition: lsyscache.c:2005
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:6625
int i
static void plpgsql_create_econtext(PLpgSQL_execstate *estate)
Definition: pl_exec.c:7937
MemoryContext stmt_mcontext
Definition: plpgsql.h:1035
static void pop_stmt_mcontext(PLpgSQL_execstate *estate)
Definition: pl_exec.c:1484
#define elog
Definition: elog.h:219
char * exitlabel
Definition: plpgsql.h:996
#define PG_TRY()
Definition: elog.h:284
PLpgSQL_expr * default_val