PostgreSQL Source Code  git master
plperl.c File Reference
#include "postgres.h"
#include <ctype.h>
#include <fcntl.h>
#include <limits.h>
#include <unistd.h>
#include "access/htup_details.h"
#include "access/xact.h"
#include "catalog/pg_language.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_type.h"
#include "commands/event_trigger.h"
#include "commands/trigger.h"
#include "executor/spi.h"
#include "funcapi.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "parser/parse_type.h"
#include "storage/ipc.h"
#include "tcop/tcopprot.h"
#include "utils/builtins.h"
#include "utils/fmgroids.h"
#include "utils/guc.h"
#include "utils/hsearch.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/rel.h"
#include "utils/syscache.h"
#include "utils/typcache.h"
#include "perlchunks.h"
#include "plperl.h"
#include "plperl_opmask.h"
Include dependency graph for plperl.c:

Go to the source code of this file.

Data Structures

struct  plperl_interp_desc
 
struct  plperl_proc_desc
 
struct  plperl_proc_key
 
struct  plperl_proc_ptr
 
struct  plperl_call_data
 
struct  plperl_query_desc
 
struct  plperl_query_entry
 
struct  plperl_array_info
 

Macros

#define TEXTDOMAIN   PG_TEXTDOMAIN("plperl")
 
#define increment_prodesc_refcount(prodesc)    ((prodesc)->fn_refcount++)
 
#define decrement_prodesc_refcount(prodesc)
 
#define setlocale_perl(a, b)   Perl_setlocale(a,b)
 

Typedefs

typedef struct plperl_interp_desc plperl_interp_desc
 
typedef struct plperl_proc_desc plperl_proc_desc
 
typedef struct plperl_proc_key plperl_proc_key
 
typedef struct plperl_proc_ptr plperl_proc_ptr
 
typedef struct plperl_call_data plperl_call_data
 
typedef struct plperl_query_desc plperl_query_desc
 
typedef struct plperl_query_entry plperl_query_entry
 
typedef struct plperl_array_info plperl_array_info
 

Functions

EXTERN_C void boot_DynaLoader (pTHX_ CV *cv)
 
EXTERN_C void boot_PostgreSQL__InServer__Util (pTHX_ CV *cv)
 
EXTERN_C void boot_PostgreSQL__InServer__SPI (pTHX_ CV *cv)
 
static PerlInterpreter * plperl_init_interp (void)
 
static void plperl_destroy_interp (PerlInterpreter **)
 
static void plperl_fini (int code, Datum arg)
 
static void set_interp_require (bool trusted)
 
static Datum plperl_func_handler (PG_FUNCTION_ARGS)
 
static Datum plperl_trigger_handler (PG_FUNCTION_ARGS)
 
static void plperl_event_trigger_handler (PG_FUNCTION_ARGS)
 
static void free_plperl_function (plperl_proc_desc *prodesc)
 
static plperl_proc_desccompile_plperl_function (Oid fn_oid, bool is_trigger, bool is_event_trigger)
 
static SV * plperl_hash_from_tuple (HeapTuple tuple, TupleDesc tupdesc, bool include_generated)
 
static SV * plperl_hash_from_datum (Datum attr)
 
static void check_spi_usage_allowed (void)
 
static SV * plperl_ref_from_pg_array (Datum arg, Oid typid)
 
static SV * split_array (plperl_array_info *info, int first, int last, int nest)
 
static SV * make_array_ref (plperl_array_info *info, int first, int last)
 
static SV * get_perl_array_ref (SV *sv)
 
static Datum plperl_sv_to_datum (SV *sv, Oid typid, int32 typmod, FunctionCallInfo fcinfo, FmgrInfo *finfo, Oid typioparam, bool *isnull)
 
static void _sv_to_datum_finfo (Oid typid, FmgrInfo *finfo, Oid *typioparam)
 
static Datum plperl_array_to_datum (SV *src, Oid typid, int32 typmod)
 
static void array_to_datum_internal (AV *av, ArrayBuildState **astatep, int *ndims, int *dims, int cur_depth, Oid elemtypid, int32 typmod, FmgrInfo *finfo, Oid typioparam)
 
static Datum plperl_hash_to_datum (SV *src, TupleDesc td)
 
static void plperl_init_shared_libs (pTHX)
 
static void plperl_trusted_init (void)
 
static void plperl_untrusted_init (void)
 
static HV * plperl_spi_execute_fetch_result (SPITupleTable *, uint64, int)
 
static void plperl_return_next_internal (SV *sv)
 
static char * hek2cstr (HE *he)
 
static SV ** hv_store_string (HV *hv, const char *key, SV *val)
 
static SV ** hv_fetch_string (HV *hv, const char *key)
 
static void plperl_create_sub (plperl_proc_desc *desc, const char *s, Oid fn_oid)
 
static SV * plperl_call_perl_func (plperl_proc_desc *desc, FunctionCallInfo fcinfo)
 
static void plperl_compile_callback (void *arg)
 
static void plperl_exec_callback (void *arg)
 
static void plperl_inline_callback (void *arg)
 
static char * strip_trailing_ws (const char *msg)
 
static OP * pp_require_safe (pTHX)
 
static void activate_interpreter (plperl_interp_desc *interp_desc)
 
static void SvREFCNT_dec_current (SV *sv)
 
void _PG_init (void)
 
static void select_perl_context (bool trusted)
 
static HeapTuple plperl_build_tuple_result (HV *perlhash, TupleDesc td)
 
char * plperl_sv_to_literal (SV *sv, char *fqtypename)
 
static SV * plperl_trigger_build_args (FunctionCallInfo fcinfo)
 
static SV * plperl_event_trigger_build_args (FunctionCallInfo fcinfo)
 
static HeapTuple plperl_modify_tuple (HV *hvTD, TriggerData *tdata, HeapTuple otup)
 
 PG_FUNCTION_INFO_V1 (plperl_call_handler)
 
Datum plperl_call_handler (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (plperl_inline_handler)
 
Datum plperl_inline_handler (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (plperl_validator)
 
Datum plperl_validator (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (plperlu_call_handler)
 
Datum plperlu_call_handler (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (plperlu_inline_handler)
 
Datum plperlu_inline_handler (PG_FUNCTION_ARGS)
 
 PG_FUNCTION_INFO_V1 (plperlu_validator)
 
Datum plperlu_validator (PG_FUNCTION_ARGS)
 
static SV * plperl_call_perl_trigger_func (plperl_proc_desc *desc, FunctionCallInfo fcinfo, SV *td)
 
static void plperl_call_perl_event_trigger_func (plperl_proc_desc *desc, FunctionCallInfo fcinfo, SV *td)
 
static bool validate_plperl_function (plperl_proc_ptr *proc_ptr, HeapTuple procTup)
 
HV * plperl_spi_exec (char *query, int limit)
 
void plperl_return_next (SV *sv)
 
SV * plperl_spi_query (char *query)
 
SV * plperl_spi_fetchrow (char *cursor)
 
void plperl_spi_cursor_close (char *cursor)
 
SV * plperl_spi_prepare (char *query, int argc, SV **argv)
 
HV * plperl_spi_exec_prepared (char *query, HV *attr, int argc, SV **argv)
 
SV * plperl_spi_query_prepared (char *query, int argc, SV **argv)
 
void plperl_spi_freeplan (char *query)
 
void plperl_spi_commit (void)
 
void plperl_spi_rollback (void)
 
void plperl_util_elog (int level, SV *msg)
 

Variables

 PG_MODULE_MAGIC
 
static HTABplperl_interp_hash = NULL
 
static HTABplperl_proc_hash = NULL
 
static plperl_interp_descplperl_active_interp = NULL
 
static PerlInterpreter * plperl_held_interp = NULL
 
static bool plperl_use_strict = false
 
static char * plperl_on_init = NULL
 
static char * plperl_on_plperl_init = NULL
 
static char * plperl_on_plperlu_init = NULL
 
static bool plperl_ending = false
 
static OP *(* pp_require_orig )(pTHX) = NULL
 
static char plperl_opmask [MAXO]
 
static plperl_call_datacurrent_call_data = NULL
 

Macro Definition Documentation

◆ decrement_prodesc_refcount

#define decrement_prodesc_refcount (   prodesc)
Value:
do { \
Assert((prodesc)->fn_refcount > 0); \
if (--((prodesc)->fn_refcount) == 0) \
free_plperl_function(prodesc); \
} while(0)

Definition at line 129 of file plperl.c.

◆ increment_prodesc_refcount

#define increment_prodesc_refcount (   prodesc)     ((prodesc)->fn_refcount++)

Definition at line 127 of file plperl.c.

◆ setlocale_perl

#define setlocale_perl (   a,
  b 
)    Perl_setlocale(a,b)

Definition at line 302 of file plperl.c.

◆ TEXTDOMAIN

#define TEXTDOMAIN   PG_TEXTDOMAIN("plperl")

Definition at line 43 of file plperl.c.

Typedef Documentation

◆ plperl_array_info

◆ plperl_call_data

◆ plperl_interp_desc

◆ plperl_proc_desc

◆ plperl_proc_key

◆ plperl_proc_ptr

◆ plperl_query_desc

◆ plperl_query_entry

Function Documentation

◆ _PG_init()

void _PG_init ( void  )

Definition at line 380 of file plperl.c.

381 {
382  /*
383  * Be sure we do initialization only once.
384  *
385  * If initialization fails due to, e.g., plperl_init_interp() throwing an
386  * exception, then we'll return here on the next usage and the user will
387  * get a rather cryptic: ERROR: attempt to redefine parameter
388  * "plperl.use_strict"
389  */
390  static bool inited = false;
391  HASHCTL hash_ctl;
392 
393  if (inited)
394  return;
395 
396  /*
397  * Support localized messages.
398  */
400 
401  /*
402  * Initialize plperl's GUCs.
403  */
404  DefineCustomBoolVariable("plperl.use_strict",
405  gettext_noop("If true, trusted and untrusted Perl code will be compiled in strict mode."),
406  NULL,
408  false,
409  PGC_USERSET, 0,
410  NULL, NULL, NULL);
411 
412  /*
413  * plperl.on_init is marked PGC_SIGHUP to support the idea that it might
414  * be executed in the postmaster (if plperl is loaded into the postmaster
415  * via shared_preload_libraries). This isn't really right either way,
416  * though.
417  */
418  DefineCustomStringVariable("plperl.on_init",
419  gettext_noop("Perl initialization code to execute when a Perl interpreter is initialized."),
420  NULL,
422  NULL,
423  PGC_SIGHUP, 0,
424  NULL, NULL, NULL);
425 
426  /*
427  * plperl.on_plperl_init is marked PGC_SUSET to avoid issues whereby a
428  * user who might not even have USAGE privilege on the plperl language
429  * could nonetheless use SET plperl.on_plperl_init='...' to influence the
430  * behaviour of any existing plperl function that they can execute (which
431  * might be SECURITY DEFINER, leading to a privilege escalation). See
432  * http://archives.postgresql.org/pgsql-hackers/2010-02/msg00281.php and
433  * the overall thread.
434  *
435  * Note that because plperl.use_strict is USERSET, a nefarious user could
436  * set it to be applied against other people's functions. This is judged
437  * OK since the worst result would be an error. Your code oughta pass
438  * use_strict anyway ;-)
439  */
440  DefineCustomStringVariable("plperl.on_plperl_init",
441  gettext_noop("Perl initialization code to execute once when plperl is first used."),
442  NULL,
444  NULL,
445  PGC_SUSET, 0,
446  NULL, NULL, NULL);
447 
448  DefineCustomStringVariable("plperl.on_plperlu_init",
449  gettext_noop("Perl initialization code to execute once when plperlu is first used."),
450  NULL,
452  NULL,
453  PGC_SUSET, 0,
454  NULL, NULL, NULL);
455 
456  MarkGUCPrefixReserved("plperl");
457 
458  /*
459  * Create hash tables.
460  */
461  hash_ctl.keysize = sizeof(Oid);
462  hash_ctl.entrysize = sizeof(plperl_interp_desc);
463  plperl_interp_hash = hash_create("PL/Perl interpreters",
464  8,
465  &hash_ctl,
467 
468  hash_ctl.keysize = sizeof(plperl_proc_key);
469  hash_ctl.entrysize = sizeof(plperl_proc_ptr);
470  plperl_proc_hash = hash_create("PL/Perl procedures",
471  32,
472  &hash_ctl,
474 
475  /*
476  * Save the default opmask.
477  */
478  PLPERL_SET_OPMASK(plperl_opmask);
479 
480  /*
481  * Create the first Perl interpreter, but only partially initialize it.
482  */
484 
485  inited = true;
486 }
#define gettext_noop(x)
Definition: c.h:1196
HTAB * hash_create(const char *tabname, long nelem, const HASHCTL *info, int flags)
Definition: dynahash.c:352
void DefineCustomStringVariable(const char *name, const char *short_desc, const char *long_desc, char **valueAddr, const char *bootValue, GucContext context, int flags, GucStringCheckHook check_hook, GucStringAssignHook assign_hook, GucShowHook show_hook)
Definition: guc.c:5177
void DefineCustomBoolVariable(const char *name, const char *short_desc, const char *long_desc, bool *valueAddr, bool bootValue, GucContext context, int flags, GucBoolCheckHook check_hook, GucBoolAssignHook assign_hook, GucShowHook show_hook)
Definition: guc.c:5091
void MarkGUCPrefixReserved(const char *className)
Definition: guc.c:5238
@ PGC_SUSET
Definition: guc.h:74
@ PGC_USERSET
Definition: guc.h:75
@ PGC_SIGHUP
Definition: guc.h:71
#define HASH_ELEM
Definition: hsearch.h:95
#define HASH_BLOBS
Definition: hsearch.h:97
void pg_bindtextdomain(const char *domain)
Definition: miscinit.c:1880
static HTAB * plperl_interp_hash
Definition: plperl.c:223
static char plperl_opmask[MAXO]
Definition: plperl.c:238
static bool plperl_use_strict
Definition: plperl.c:231
struct plperl_proc_key plperl_proc_key
static HTAB * plperl_proc_hash
Definition: plperl.c:224
static PerlInterpreter * plperl_held_interp
Definition: plperl.c:228
#define TEXTDOMAIN
Definition: plperl.c:43
static char * plperl_on_init
Definition: plperl.c:232
static char * plperl_on_plperl_init
Definition: plperl.c:233
struct plperl_proc_ptr plperl_proc_ptr
struct plperl_interp_desc plperl_interp_desc
static PerlInterpreter * plperl_init_interp(void)
Definition: plperl.c:705
static char * plperl_on_plperlu_init
Definition: plperl.c:234
unsigned int Oid
Definition: postgres_ext.h:31
Size keysize
Definition: hsearch.h:75
Size entrysize
Definition: hsearch.h:76

References DefineCustomBoolVariable(), DefineCustomStringVariable(), HASHCTL::entrysize, gettext_noop, HASH_BLOBS, hash_create(), HASH_ELEM, HASHCTL::keysize, MarkGUCPrefixReserved(), pg_bindtextdomain(), PGC_SIGHUP, PGC_SUSET, PGC_USERSET, plperl_held_interp, plperl_init_interp(), plperl_interp_hash, plperl_on_init, plperl_on_plperl_init, plperl_on_plperlu_init, plperl_opmask, plperl_proc_hash, plperl_use_strict, and TEXTDOMAIN.

◆ _sv_to_datum_finfo()

static void _sv_to_datum_finfo ( Oid  typid,
FmgrInfo finfo,
Oid typioparam 
)
static

Definition at line 1300 of file plperl.c.

1301 {
1302  Oid typinput;
1303 
1304  /* XXX would be better to cache these lookups */
1305  getTypeInputInfo(typid,
1306  &typinput, typioparam);
1307  fmgr_info(typinput, finfo);
1308 }
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:127
void getTypeInputInfo(Oid type, Oid *typInput, Oid *typIOParam)
Definition: lsyscache.c:2874

References fmgr_info(), and getTypeInputInfo().

Referenced by plperl_array_to_datum(), and plperl_sv_to_datum().

◆ activate_interpreter()

static void activate_interpreter ( plperl_interp_desc interp_desc)
static

Definition at line 684 of file plperl.c.

685 {
686  if (interp_desc && plperl_active_interp != interp_desc)
687  {
688  Assert(interp_desc->interp);
689  PERL_SET_CONTEXT(interp_desc->interp);
690  /* trusted iff user_id isn't InvalidOid */
691  set_interp_require(OidIsValid(interp_desc->user_id));
692  plperl_active_interp = interp_desc;
693  }
694 }
#define Assert(condition)
Definition: c.h:858
#define OidIsValid(objectId)
Definition: c.h:775
static void set_interp_require(bool trusted)
Definition: plperl.c:490
static plperl_interp_desc * plperl_active_interp
Definition: plperl.c:225
PerlInterpreter * interp
Definition: plperl.c:86

References Assert, plperl_interp_desc::interp, OidIsValid, plperl_active_interp, set_interp_require(), and plperl_interp_desc::user_id.

Referenced by compile_plperl_function(), free_plperl_function(), plperl_call_handler(), plperl_event_trigger_handler(), plperl_fini(), plperl_func_handler(), plperl_inline_handler(), plperl_trigger_handler(), and select_perl_context().

◆ array_to_datum_internal()

static void array_to_datum_internal ( AV *  av,
ArrayBuildState **  astatep,
int *  ndims,
int *  dims,
int  cur_depth,
Oid  elemtypid,
int32  typmod,
FmgrInfo finfo,
Oid  typioparam 
)
static

Definition at line 1170 of file plperl.c.

1174 {
1175  dTHX;
1176  int i;
1177  int len = av_len(av) + 1;
1178 
1179  for (i = 0; i < len; i++)
1180  {
1181  /* fetch the array element */
1182  SV **svp = av_fetch(av, i, FALSE);
1183 
1184  /* see if this element is an array, if so get that */
1185  SV *sav = svp ? get_perl_array_ref(*svp) : NULL;
1186 
1187  /* multi-dimensional array? */
1188  if (sav)
1189  {
1190  AV *nav = (AV *) SvRV(sav);
1191 
1192  /* set size when at first element in this level, else compare */
1193  if (i == 0 && *ndims == cur_depth)
1194  {
1195  /* array after some scalars at same level? */
1196  if (*astatep != NULL)
1197  ereport(ERROR,
1198  (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1199  errmsg("multidimensional arrays must have array expressions with matching dimensions")));
1200  /* too many dimensions? */
1201  if (cur_depth + 1 > MAXDIM)
1202  ereport(ERROR,
1203  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1204  errmsg("number of array dimensions exceeds the maximum allowed (%d)",
1205  MAXDIM)));
1206  /* OK, add a dimension */
1207  dims[*ndims] = av_len(nav) + 1;
1208  (*ndims)++;
1209  }
1210  else if (cur_depth >= *ndims ||
1211  av_len(nav) + 1 != dims[cur_depth])
1212  ereport(ERROR,
1213  (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1214  errmsg("multidimensional arrays must have array expressions with matching dimensions")));
1215 
1216  /* recurse to fetch elements of this sub-array */
1217  array_to_datum_internal(nav, astatep,
1218  ndims, dims, cur_depth + 1,
1219  elemtypid, typmod,
1220  finfo, typioparam);
1221  }
1222  else
1223  {
1224  Datum dat;
1225  bool isnull;
1226 
1227  /* scalar after some sub-arrays at same level? */
1228  if (*ndims != cur_depth)
1229  ereport(ERROR,
1230  (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1231  errmsg("multidimensional arrays must have array expressions with matching dimensions")));
1232 
1233  dat = plperl_sv_to_datum(svp ? *svp : NULL,
1234  elemtypid,
1235  typmod,
1236  NULL,
1237  finfo,
1238  typioparam,
1239  &isnull);
1240 
1241  /* Create ArrayBuildState if we didn't already */
1242  if (*astatep == NULL)
1243  *astatep = initArrayResult(elemtypid,
1244  CurrentMemoryContext, true);
1245 
1246  /* ... and save the element value in it */
1247  (void) accumArrayResult(*astatep, dat, isnull,
1248  elemtypid, CurrentMemoryContext);
1249  }
1250  }
1251 }
#define MAXDIM
Definition: array.h:75
ArrayBuildState * accumArrayResult(ArrayBuildState *astate, Datum dvalue, bool disnull, Oid element_type, MemoryContext rcontext)
Definition: arrayfuncs.c:5338
ArrayBuildState * initArrayResult(Oid element_type, MemoryContext rcontext, bool subcontext)
Definition: arrayfuncs.c:5281
int errcode(int sqlerrcode)
Definition: elog.c:853
int errmsg(const char *fmt,...)
Definition: elog.c:1070
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149
int i
Definition: isn.c:73
MemoryContext CurrentMemoryContext
Definition: mcxt.c:143
const void size_t len
static Datum plperl_sv_to_datum(SV *sv, Oid typid, int32 typmod, FunctionCallInfo fcinfo, FmgrInfo *finfo, Oid typioparam, bool *isnull)
Definition: plperl.c:1323
static SV * get_perl_array_ref(SV *sv)
Definition: plperl.c:1138
static void array_to_datum_internal(AV *av, ArrayBuildState **astatep, int *ndims, int *dims, int cur_depth, Oid elemtypid, int32 typmod, FmgrInfo *finfo, Oid typioparam)
Definition: plperl.c:1170
uintptr_t Datum
Definition: postgres.h:64
#define dTHX
Definition: ppport.h:11306
struct @10::@11 av[32]

References accumArrayResult(), av, CurrentMemoryContext, dTHX, ereport, errcode(), errmsg(), ERROR, get_perl_array_ref(), i, initArrayResult(), len, MAXDIM, and plperl_sv_to_datum().

Referenced by plperl_array_to_datum().

◆ boot_DynaLoader()

EXTERN_C void boot_DynaLoader ( pTHX_ CV *  cv)

Referenced by plperl_init_shared_libs().

◆ boot_PostgreSQL__InServer__SPI()

EXTERN_C void boot_PostgreSQL__InServer__SPI ( pTHX_ CV *  cv)

Referenced by select_perl_context().

◆ boot_PostgreSQL__InServer__Util()

EXTERN_C void boot_PostgreSQL__InServer__Util ( pTHX_ CV *  cv)

Referenced by plperl_init_shared_libs().

◆ check_spi_usage_allowed()

static void check_spi_usage_allowed ( void  )
static

Definition at line 3102 of file plperl.c.

3103 {
3104  /* see comment in plperl_fini() */
3105  if (plperl_ending)
3106  {
3107  /* simple croak as we don't want to involve PostgreSQL code */
3108  croak("SPI functions can not be used in END blocks");
3109  }
3110 
3111  /*
3112  * Disallow SPI usage if we're not executing a fully-compiled plperl
3113  * function. It might seem impossible to get here in that case, but there
3114  * are cases where Perl will try to execute code during compilation. If
3115  * we proceed we are likely to crash trying to dereference the prodesc
3116  * pointer. Working around that might be possible, but it seems unwise
3117  * because it'd allow code execution to happen while validating a
3118  * function, which is undesirable.
3119  */
3120  if (current_call_data == NULL || current_call_data->prodesc == NULL)
3121  {
3122  /* simple croak as we don't want to involve PostgreSQL code */
3123  croak("SPI functions can not be used during function compilation");
3124  }
3125 }
static bool plperl_ending
Definition: plperl.c:236
static plperl_call_data * current_call_data
Definition: plperl.c:241
plperl_proc_desc * prodesc
Definition: plperl.c:173

References current_call_data, plperl_ending, and plperl_call_data::prodesc.

Referenced by plperl_return_next(), plperl_spi_commit(), plperl_spi_cursor_close(), plperl_spi_exec(), plperl_spi_exec_prepared(), plperl_spi_execute_fetch_result(), plperl_spi_fetchrow(), plperl_spi_freeplan(), plperl_spi_prepare(), plperl_spi_query(), plperl_spi_query_prepared(), plperl_spi_rollback(), and plperl_sv_to_literal().

◆ compile_plperl_function()

static plperl_proc_desc * compile_plperl_function ( Oid  fn_oid,
bool  is_trigger,
bool  is_event_trigger 
)
static

Definition at line 2714 of file plperl.c.

2715 {
2716  HeapTuple procTup;
2717  Form_pg_proc procStruct;
2718  plperl_proc_key proc_key;
2719  plperl_proc_ptr *proc_ptr;
2720  plperl_proc_desc *volatile prodesc = NULL;
2721  volatile MemoryContext proc_cxt = NULL;
2723  ErrorContextCallback plperl_error_context;
2724 
2725  /* We'll need the pg_proc tuple in any case... */
2726  procTup = SearchSysCache1(PROCOID, ObjectIdGetDatum(fn_oid));
2727  if (!HeapTupleIsValid(procTup))
2728  elog(ERROR, "cache lookup failed for function %u", fn_oid);
2729  procStruct = (Form_pg_proc) GETSTRUCT(procTup);
2730 
2731  /*
2732  * Try to find function in plperl_proc_hash. The reason for this
2733  * overcomplicated-seeming lookup procedure is that we don't know whether
2734  * it's plperl or plperlu, and don't want to spend a lookup in pg_language
2735  * to find out.
2736  */
2737  proc_key.proc_id = fn_oid;
2738  proc_key.is_trigger = is_trigger;
2739  proc_key.user_id = GetUserId();
2740  proc_ptr = hash_search(plperl_proc_hash, &proc_key,
2741  HASH_FIND, NULL);
2742  if (validate_plperl_function(proc_ptr, procTup))
2743  {
2744  /* Found valid plperl entry */
2745  ReleaseSysCache(procTup);
2746  return proc_ptr->proc_ptr;
2747  }
2748 
2749  /* If not found or obsolete, maybe it's plperlu */
2750  proc_key.user_id = InvalidOid;
2751  proc_ptr = hash_search(plperl_proc_hash, &proc_key,
2752  HASH_FIND, NULL);
2753  if (validate_plperl_function(proc_ptr, procTup))
2754  {
2755  /* Found valid plperlu entry */
2756  ReleaseSysCache(procTup);
2757  return proc_ptr->proc_ptr;
2758  }
2759 
2760  /************************************************************
2761  * If we haven't found it in the hashtable, we analyze
2762  * the function's arguments and return type and store
2763  * the in-/out-functions in the prodesc block,
2764  * then we load the procedure into the Perl interpreter,
2765  * and last we create a new hashtable entry for it.
2766  ************************************************************/
2767 
2768  /* Set a callback for reporting compilation errors */
2769  plperl_error_context.callback = plperl_compile_callback;
2770  plperl_error_context.previous = error_context_stack;
2771  plperl_error_context.arg = NameStr(procStruct->proname);
2772  error_context_stack = &plperl_error_context;
2773 
2774  PG_TRY();
2775  {
2776  HeapTuple langTup;
2777  HeapTuple typeTup;
2778  Form_pg_language langStruct;
2779  Form_pg_type typeStruct;
2780  Datum protrftypes_datum;
2781  Datum prosrcdatum;
2782  bool isnull;
2783  char *proc_source;
2784  MemoryContext oldcontext;
2785 
2786  /************************************************************
2787  * Allocate a context that will hold all PG data for the procedure.
2788  ************************************************************/
2790  "PL/Perl function",
2792 
2793  /************************************************************
2794  * Allocate and fill a new procedure description block.
2795  * struct prodesc and subsidiary data must all live in proc_cxt.
2796  ************************************************************/
2797  oldcontext = MemoryContextSwitchTo(proc_cxt);
2798  prodesc = (plperl_proc_desc *) palloc0(sizeof(plperl_proc_desc));
2799  prodesc->proname = pstrdup(NameStr(procStruct->proname));
2800  MemoryContextSetIdentifier(proc_cxt, prodesc->proname);
2801  prodesc->fn_cxt = proc_cxt;
2802  prodesc->fn_refcount = 0;
2803  prodesc->fn_xmin = HeapTupleHeaderGetRawXmin(procTup->t_data);
2804  prodesc->fn_tid = procTup->t_self;
2805  prodesc->nargs = procStruct->pronargs;
2806  prodesc->arg_out_func = (FmgrInfo *) palloc0(prodesc->nargs * sizeof(FmgrInfo));
2807  prodesc->arg_is_rowtype = (bool *) palloc0(prodesc->nargs * sizeof(bool));
2808  prodesc->arg_arraytype = (Oid *) palloc0(prodesc->nargs * sizeof(Oid));
2809  MemoryContextSwitchTo(oldcontext);
2810 
2811  /* Remember if function is STABLE/IMMUTABLE */
2812  prodesc->fn_readonly =
2813  (procStruct->provolatile != PROVOLATILE_VOLATILE);
2814 
2815  /* Fetch protrftypes */
2816  protrftypes_datum = SysCacheGetAttr(PROCOID, procTup,
2817  Anum_pg_proc_protrftypes, &isnull);
2818  MemoryContextSwitchTo(proc_cxt);
2819  prodesc->trftypes = isnull ? NIL : oid_array_to_list(protrftypes_datum);
2820  MemoryContextSwitchTo(oldcontext);
2821 
2822  /************************************************************
2823  * Lookup the pg_language tuple by Oid
2824  ************************************************************/
2825  langTup = SearchSysCache1(LANGOID,
2826  ObjectIdGetDatum(procStruct->prolang));
2827  if (!HeapTupleIsValid(langTup))
2828  elog(ERROR, "cache lookup failed for language %u",
2829  procStruct->prolang);
2830  langStruct = (Form_pg_language) GETSTRUCT(langTup);
2831  prodesc->lang_oid = langStruct->oid;
2832  prodesc->lanpltrusted = langStruct->lanpltrusted;
2833  ReleaseSysCache(langTup);
2834 
2835  /************************************************************
2836  * Get the required information for input conversion of the
2837  * return value.
2838  ************************************************************/
2839  if (!is_trigger && !is_event_trigger)
2840  {
2841  Oid rettype = procStruct->prorettype;
2842 
2843  typeTup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(rettype));
2844  if (!HeapTupleIsValid(typeTup))
2845  elog(ERROR, "cache lookup failed for type %u", rettype);
2846  typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
2847 
2848  /* Disallow pseudotype result, except VOID or RECORD */
2849  if (typeStruct->typtype == TYPTYPE_PSEUDO)
2850  {
2851  if (rettype == VOIDOID ||
2852  rettype == RECORDOID)
2853  /* okay */ ;
2854  else if (rettype == TRIGGEROID ||
2855  rettype == EVENT_TRIGGEROID)
2856  ereport(ERROR,
2857  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2858  errmsg("trigger functions can only be called "
2859  "as triggers")));
2860  else
2861  ereport(ERROR,
2862  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2863  errmsg("PL/Perl functions cannot return type %s",
2864  format_type_be(rettype))));
2865  }
2866 
2867  prodesc->result_oid = rettype;
2868  prodesc->fn_retisset = procStruct->proretset;
2869  prodesc->fn_retistuple = type_is_rowtype(rettype);
2870  prodesc->fn_retisarray = IsTrueArrayType(typeStruct);
2871 
2872  fmgr_info_cxt(typeStruct->typinput,
2873  &(prodesc->result_in_func),
2874  proc_cxt);
2875  prodesc->result_typioparam = getTypeIOParam(typeTup);
2876 
2877  ReleaseSysCache(typeTup);
2878  }
2879 
2880  /************************************************************
2881  * Get the required information for output conversion
2882  * of all procedure arguments
2883  ************************************************************/
2884  if (!is_trigger && !is_event_trigger)
2885  {
2886  int i;
2887 
2888  for (i = 0; i < prodesc->nargs; i++)
2889  {
2890  Oid argtype = procStruct->proargtypes.values[i];
2891 
2892  typeTup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(argtype));
2893  if (!HeapTupleIsValid(typeTup))
2894  elog(ERROR, "cache lookup failed for type %u", argtype);
2895  typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
2896 
2897  /* Disallow pseudotype argument, except RECORD */
2898  if (typeStruct->typtype == TYPTYPE_PSEUDO &&
2899  argtype != RECORDOID)
2900  ereport(ERROR,
2901  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2902  errmsg("PL/Perl functions cannot accept type %s",
2903  format_type_be(argtype))));
2904 
2905  if (type_is_rowtype(argtype))
2906  prodesc->arg_is_rowtype[i] = true;
2907  else
2908  {
2909  prodesc->arg_is_rowtype[i] = false;
2910  fmgr_info_cxt(typeStruct->typoutput,
2911  &(prodesc->arg_out_func[i]),
2912  proc_cxt);
2913  }
2914 
2915  /* Identify array-type arguments */
2916  if (IsTrueArrayType(typeStruct))
2917  prodesc->arg_arraytype[i] = argtype;
2918  else
2919  prodesc->arg_arraytype[i] = InvalidOid;
2920 
2921  ReleaseSysCache(typeTup);
2922  }
2923  }
2924 
2925  /************************************************************
2926  * create the text of the anonymous subroutine.
2927  * we do not use a named subroutine so that we can call directly
2928  * through the reference.
2929  ************************************************************/
2930  prosrcdatum = SysCacheGetAttrNotNull(PROCOID, procTup,
2931  Anum_pg_proc_prosrc);
2932  proc_source = TextDatumGetCString(prosrcdatum);
2933 
2934  /************************************************************
2935  * Create the procedure in the appropriate interpreter
2936  ************************************************************/
2937 
2939 
2940  prodesc->interp = plperl_active_interp;
2941 
2942  plperl_create_sub(prodesc, proc_source, fn_oid);
2943 
2944  activate_interpreter(oldinterp);
2945 
2946  pfree(proc_source);
2947 
2948  if (!prodesc->reference) /* can this happen? */
2949  elog(ERROR, "could not create PL/Perl internal procedure");
2950 
2951  /************************************************************
2952  * OK, link the procedure into the correct hashtable entry.
2953  * Note we assume that the hashtable entry either doesn't exist yet,
2954  * or we already cleared its proc_ptr during the validation attempts
2955  * above. So no need to decrement an old refcount here.
2956  ************************************************************/
2957  proc_key.user_id = prodesc->lanpltrusted ? GetUserId() : InvalidOid;
2958 
2959  proc_ptr = hash_search(plperl_proc_hash, &proc_key,
2960  HASH_ENTER, NULL);
2961  /* We assume these two steps can't throw an error: */
2962  proc_ptr->proc_ptr = prodesc;
2963  increment_prodesc_refcount(prodesc);
2964  }
2965  PG_CATCH();
2966  {
2967  /*
2968  * If we got as far as creating a reference, we should be able to use
2969  * free_plperl_function() to clean up. If not, then at most we have
2970  * some PG memory resources in proc_cxt, which we can just delete.
2971  */
2972  if (prodesc && prodesc->reference)
2973  free_plperl_function(prodesc);
2974  else if (proc_cxt)
2975  MemoryContextDelete(proc_cxt);
2976 
2977  /* Be sure to restore the previous interpreter, too, for luck */
2978  activate_interpreter(oldinterp);
2979 
2980  PG_RE_THROW();
2981  }
2982  PG_END_TRY();
2983 
2984  /* restore previous error callback */
2985  error_context_stack = plperl_error_context.previous;
2986 
2987  ReleaseSysCache(procTup);
2988 
2989  return prodesc;
2990 }
#define TextDatumGetCString(d)
Definition: builtins.h:98
#define NameStr(name)
Definition: c.h:746
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:955
ErrorContextCallback * error_context_stack
Definition: elog.c:94
#define PG_RE_THROW()
Definition: elog.h:412
#define PG_TRY(...)
Definition: elog.h:371
#define PG_END_TRY(...)
Definition: elog.h:396
#define PG_CATCH(...)
Definition: elog.h:381
#define elog(elevel,...)
Definition: elog.h:225
void fmgr_info_cxt(Oid functionId, FmgrInfo *finfo, MemoryContext mcxt)
Definition: fmgr.c:137
char * format_type_be(Oid type_oid)
Definition: format_type.c:343
@ HASH_FIND
Definition: hsearch.h:113
@ HASH_ENTER
Definition: hsearch.h:114
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define HeapTupleHeaderGetRawXmin(tup)
Definition: htup_details.h:304
#define GETSTRUCT(TUP)
Definition: htup_details.h:653
bool type_is_rowtype(Oid typid)
Definition: lsyscache.c:2655
Oid getTypeIOParam(HeapTuple typeTuple)
Definition: lsyscache.c:2303
char * pstrdup(const char *in)
Definition: mcxt.c:1696
void pfree(void *pointer)
Definition: mcxt.c:1521
MemoryContext TopMemoryContext
Definition: mcxt.c:149
void * palloc0(Size size)
Definition: mcxt.c:1347
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:454
void MemoryContextSetIdentifier(MemoryContext context, const char *id)
Definition: mcxt.c:612
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_SMALL_SIZES
Definition: memutils.h:170
Oid GetUserId(void)
Definition: miscinit.c:514
FormData_pg_language * Form_pg_language
Definition: pg_language.h:65
#define NIL
Definition: pg_list.h:68
List * oid_array_to_list(Datum datum)
Definition: pg_proc.c:1184
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:136
FormData_pg_type * Form_pg_type
Definition: pg_type.h:261
static void plperl_create_sub(plperl_proc_desc *desc, const char *s, Oid fn_oid)
Definition: plperl.c:2094
#define increment_prodesc_refcount(prodesc)
Definition: plperl.c:127
static void free_plperl_function(plperl_proc_desc *prodesc)
Definition: plperl.c:2696
static void select_perl_context(bool trusted)
Definition: plperl.c:553
static void plperl_compile_callback(void *arg)
Definition: plperl.c:4151
static bool validate_plperl_function(plperl_proc_ptr *proc_ptr, HeapTuple procTup)
Definition: plperl.c:2667
static void activate_interpreter(plperl_interp_desc *interp_desc)
Definition: plperl.c:684
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:252
#define InvalidOid
Definition: postgres_ext.h:36
MemoryContextSwitchTo(old_ctx)
struct ErrorContextCallback * previous
Definition: elog.h:296
void(* callback)(void *arg)
Definition: elog.h:297
Definition: fmgr.h:57
ItemPointerData t_self
Definition: htup.h:65
HeapTupleHeader t_data
Definition: htup.h:68
char * proname
Definition: plperl.c:102
FmgrInfo result_in_func
Definition: plperl.c:118
bool fn_readonly
Definition: plperl.c:109
unsigned long fn_refcount
Definition: plperl.c:104
MemoryContext fn_cxt
Definition: plperl.c:103
bool fn_retisarray
Definition: plperl.c:115
FmgrInfo * arg_out_func
Definition: plperl.c:122
Oid * arg_arraytype
Definition: plperl.c:124
ItemPointerData fn_tid
Definition: plperl.c:106
plperl_interp_desc * interp
Definition: plperl.c:108
bool fn_retistuple
Definition: plperl.c:113
SV * reference
Definition: plperl.c:107
TransactionId fn_xmin
Definition: plperl.c:105
bool * arg_is_rowtype
Definition: plperl.c:123
Oid result_typioparam
Definition: plperl.c:119
bool fn_retisset
Definition: plperl.c:114
List * trftypes
Definition: plperl.c:111
bool lanpltrusted
Definition: plperl.c:112
Oid is_trigger
Definition: plperl.c:157
plperl_proc_desc * proc_ptr
Definition: plperl.c:164
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:266
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:218
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:479
Datum SysCacheGetAttrNotNull(int cacheId, HeapTuple tup, AttrNumber attributeNumber)
Definition: syscache.c:510

References activate_interpreter(), ALLOCSET_SMALL_SIZES, AllocSetContextCreate, ErrorContextCallback::arg, plperl_proc_desc::arg_arraytype, plperl_proc_desc::arg_is_rowtype, plperl_proc_desc::arg_out_func, ErrorContextCallback::callback, elog, ereport, errcode(), errmsg(), ERROR, error_context_stack, fmgr_info_cxt(), plperl_proc_desc::fn_cxt, plperl_proc_desc::fn_readonly, plperl_proc_desc::fn_refcount, plperl_proc_desc::fn_retisarray, plperl_proc_desc::fn_retisset, plperl_proc_desc::fn_retistuple, plperl_proc_desc::fn_tid, plperl_proc_desc::fn_xmin, format_type_be(), free_plperl_function(), GETSTRUCT, getTypeIOParam(), GetUserId(), HASH_ENTER, HASH_FIND, hash_search(), HeapTupleHeaderGetRawXmin, HeapTupleIsValid, i, increment_prodesc_refcount, plperl_proc_desc::interp, InvalidOid, plperl_proc_key::is_trigger, plperl_proc_desc::lang_oid, plperl_proc_desc::lanpltrusted, MemoryContextDelete(), MemoryContextSetIdentifier(), MemoryContextSwitchTo(), NameStr, plperl_proc_desc::nargs, NIL, ObjectIdGetDatum(), oid_array_to_list(), palloc0(), pfree(), PG_CATCH, PG_END_TRY, PG_RE_THROW, PG_TRY, plperl_active_interp, plperl_compile_callback(), plperl_create_sub(), plperl_proc_hash, ErrorContextCallback::previous, plperl_proc_key::proc_id, plperl_proc_ptr::proc_ptr, plperl_proc_desc::proname, pstrdup(), plperl_proc_desc::reference, ReleaseSysCache(), plperl_proc_desc::result_in_func, plperl_proc_desc::result_oid, plperl_proc_desc::result_typioparam, SearchSysCache1(), select_perl_context(), SysCacheGetAttr(), SysCacheGetAttrNotNull(), HeapTupleData::t_data, HeapTupleData::t_self, TextDatumGetCString, TopMemoryContext, plperl_proc_desc::trftypes, type_is_rowtype(), plperl_proc_key::user_id, and validate_plperl_function().

Referenced by plperl_event_trigger_handler(), plperl_func_handler(), plperl_trigger_handler(), and plperl_validator().

◆ free_plperl_function()

static void free_plperl_function ( plperl_proc_desc prodesc)
static

Definition at line 2696 of file plperl.c.

2697 {
2698  Assert(prodesc->fn_refcount == 0);
2699  /* Release CODE reference, if we have one, from the appropriate interp */
2700  if (prodesc->reference)
2701  {
2703 
2704  activate_interpreter(prodesc->interp);
2705  SvREFCNT_dec_current(prodesc->reference);
2706  activate_interpreter(oldinterp);
2707  }
2708  /* Release all PG-owned data for this proc */
2709  MemoryContextDelete(prodesc->fn_cxt);
2710 }
static void SvREFCNT_dec_current(SV *sv)
Definition: plperl.c:312

References activate_interpreter(), Assert, plperl_proc_desc::fn_cxt, plperl_proc_desc::fn_refcount, plperl_proc_desc::interp, MemoryContextDelete(), plperl_active_interp, plperl_proc_desc::reference, and SvREFCNT_dec_current().

Referenced by compile_plperl_function().

◆ get_perl_array_ref()

static SV * get_perl_array_ref ( SV *  sv)
static

Definition at line 1138 of file plperl.c.

1139 {
1140  dTHX;
1141 
1142  if (SvOK(sv) && SvROK(sv))
1143  {
1144  if (SvTYPE(SvRV(sv)) == SVt_PVAV)
1145  return sv;
1146  else if (sv_isa(sv, "PostgreSQL::InServer::ARRAY"))
1147  {
1148  HV *hv = (HV *) SvRV(sv);
1149  SV **sav = hv_fetch_string(hv, "array");
1150 
1151  if (*sav && SvOK(*sav) && SvROK(*sav) &&
1152  SvTYPE(SvRV(*sav)) == SVt_PVAV)
1153  return *sav;
1154 
1155  elog(ERROR, "could not get array reference from PostgreSQL::InServer::ARRAY object");
1156  }
1157  }
1158  return NULL;
1159 }
static SV ** hv_fetch_string(HV *hv, const char *key)
Definition: plperl.c:4116

References dTHX, elog, ERROR, and hv_fetch_string().

Referenced by array_to_datum_internal(), plperl_func_handler(), and plperl_sv_to_datum().

◆ hek2cstr()

static char * hek2cstr ( HE *  he)
static

Definition at line 323 of file plperl.c.

324 {
325  dTHX;
326  char *ret;
327  SV *sv;
328 
329  /*
330  * HeSVKEY_force will return a temporary mortal SV*, so we need to make
331  * sure to free it with ENTER/SAVE/FREE/LEAVE
332  */
333  ENTER;
334  SAVETMPS;
335 
336  /*-------------------------
337  * Unfortunately, while HeUTF8 is true for most things > 256, for values
338  * 128..255 it's not, but perl will treat them as unicode code points if
339  * the utf8 flag is not set ( see The "Unicode Bug" in perldoc perlunicode
340  * for more)
341  *
342  * So if we did the expected:
343  * if (HeUTF8(he))
344  * utf_u2e(key...);
345  * else // must be ascii
346  * return HePV(he);
347  * we won't match columns with codepoints from 128..255
348  *
349  * For a more concrete example given a column with the name of the unicode
350  * codepoint U+00ae (registered sign) and a UTF8 database and the perl
351  * return_next { "\N{U+00ae}=>'text } would always fail as heUTF8 returns
352  * 0 and HePV() would give us a char * with 1 byte contains the decimal
353  * value 174
354  *
355  * Perl has the brains to know when it should utf8 encode 174 properly, so
356  * here we force it into an SV so that perl will figure it out and do the
357  * right thing
358  *-------------------------
359  */
360 
361  sv = HeSVKEY_force(he);
362  if (HeUTF8(he))
363  SvUTF8_on(sv);
364  ret = sv2cstr(sv);
365 
366  /* free sv */
367  FREETMPS;
368  LEAVE;
369 
370  return ret;
371 }
static char * sv2cstr(SV *sv)
Definition: plperl.h:89
#define HeUTF8(he)

References dTHX, HeUTF8, and sv2cstr().

Referenced by plperl_build_tuple_result(), and plperl_modify_tuple().

◆ hv_fetch_string()

static SV ** hv_fetch_string ( HV *  hv,
const char *  key 
)
static

Definition at line 4116 of file plperl.c.

4117 {
4118  dTHX;
4119  int32 hlen;
4120  char *hkey;
4121  SV **ret;
4122 
4123  hkey = pg_server_to_any(key, strlen(key), PG_UTF8);
4124 
4125  /* See notes in hv_store_string */
4126  hlen = -(int) strlen(hkey);
4127  ret = hv_fetch(hv, hkey, hlen, 0);
4128 
4129  if (hkey != key)
4130  pfree(hkey);
4131 
4132  return ret;
4133 }
signed int int32
Definition: c.h:494
char * pg_server_to_any(const char *s, int len, int encoding)
Definition: mbutils.c:749
@ PG_UTF8
Definition: pg_wchar.h:232

References dTHX, sort-test::key, pfree(), pg_server_to_any(), and PG_UTF8.

Referenced by get_perl_array_ref(), plperl_modify_tuple(), and plperl_spi_exec_prepared().

◆ hv_store_string()

static SV ** hv_store_string ( HV *  hv,
const char *  key,
SV *  val 
)
static

Definition at line 4089 of file plperl.c.

4090 {
4091  dTHX;
4092  int32 hlen;
4093  char *hkey;
4094  SV **ret;
4095 
4096  hkey = pg_server_to_any(key, strlen(key), PG_UTF8);
4097 
4098  /*
4099  * hv_store() recognizes a negative klen parameter as meaning a UTF-8
4100  * encoded key.
4101  */
4102  hlen = -(int) strlen(hkey);
4103  ret = hv_store(hv, hkey, hlen, val, 0);
4104 
4105  if (hkey != key)
4106  pfree(hkey);
4107 
4108  return ret;
4109 }
long val
Definition: informix.c:689

References dTHX, sort-test::key, pfree(), pg_server_to_any(), PG_UTF8, and val.

Referenced by plperl_create_sub(), plperl_event_trigger_build_args(), plperl_hash_from_tuple(), plperl_spi_execute_fetch_result(), and plperl_trigger_build_args().

◆ make_array_ref()

static SV * make_array_ref ( plperl_array_info info,
int  first,
int  last 
)
static

Definition at line 1593 of file plperl.c.

1594 {
1595  dTHX;
1596  int i;
1597  AV *result = newAV();
1598 
1599  for (i = first; i < last; i++)
1600  {
1601  if (info->nulls[i])
1602  {
1603  /*
1604  * We can't use &PL_sv_undef here. See "AVs, HVs and undefined
1605  * values" in perlguts.
1606  */
1607  av_push(result, newSV(0));
1608  }
1609  else
1610  {
1611  Datum itemvalue = info->elements[i];
1612 
1613  if (info->transform_proc.fn_oid)
1614  av_push(result, (SV *) DatumGetPointer(FunctionCall1(&info->transform_proc, itemvalue)));
1615  else if (info->elem_is_rowtype)
1616  /* Handle composite type elements */
1617  av_push(result, plperl_hash_from_datum(itemvalue));
1618  else
1619  {
1620  char *val = OutputFunctionCall(&info->proc, itemvalue);
1621 
1622  av_push(result, cstr2sv(val));
1623  }
1624  }
1625  }
1626  return newRV_noinc((SV *) result);
1627 }
char * OutputFunctionCall(FmgrInfo *flinfo, Datum val)
Definition: fmgr.c:1683
#define FunctionCall1(flinfo, arg1)
Definition: fmgr.h:659
static SV * plperl_hash_from_datum(Datum attr)
Definition: plperl.c:2994
static SV * cstr2sv(const char *str)
Definition: plperl.h:147
static Pointer DatumGetPointer(Datum X)
Definition: postgres.h:312
#define newRV_noinc(sv)
Definition: ppport.h:15247
Oid fn_oid
Definition: fmgr.h:59
bool elem_is_rowtype
Definition: plperl.c:211
bool * nulls
Definition: plperl.c:213
FmgrInfo transform_proc
Definition: plperl.c:216
FmgrInfo proc
Definition: plperl.c:215
Datum * elements
Definition: plperl.c:212

References cstr2sv(), DatumGetPointer(), dTHX, plperl_array_info::elem_is_rowtype, plperl_array_info::elements, FmgrInfo::fn_oid, FunctionCall1, i, newRV_noinc, plperl_array_info::nulls, OutputFunctionCall(), plperl_hash_from_datum(), plperl_array_info::proc, plperl_array_info::transform_proc, and val.

Referenced by split_array().

◆ PG_FUNCTION_INFO_V1() [1/6]

PG_FUNCTION_INFO_V1 ( plperl_call_handler  )

◆ PG_FUNCTION_INFO_V1() [2/6]

PG_FUNCTION_INFO_V1 ( plperl_inline_handler  )

◆ PG_FUNCTION_INFO_V1() [3/6]

PG_FUNCTION_INFO_V1 ( plperl_validator  )

◆ PG_FUNCTION_INFO_V1() [4/6]

PG_FUNCTION_INFO_V1 ( plperlu_call_handler  )

◆ PG_FUNCTION_INFO_V1() [5/6]

PG_FUNCTION_INFO_V1 ( plperlu_inline_handler  )

◆ PG_FUNCTION_INFO_V1() [6/6]

PG_FUNCTION_INFO_V1 ( plperlu_validator  )

◆ plperl_array_to_datum()

static Datum plperl_array_to_datum ( SV *  src,
Oid  typid,
int32  typmod 
)
static

Definition at line 1257 of file plperl.c.

1258 {
1259  dTHX;
1260  AV *nav = (AV *) SvRV(src);
1261  ArrayBuildState *astate = NULL;
1262  Oid elemtypid;
1263  FmgrInfo finfo;
1264  Oid typioparam;
1265  int dims[MAXDIM];
1266  int lbs[MAXDIM];
1267  int ndims = 1;
1268  int i;
1269 
1270  elemtypid = get_element_type(typid);
1271  if (!elemtypid)
1272  ereport(ERROR,
1273  (errcode(ERRCODE_DATATYPE_MISMATCH),
1274  errmsg("cannot convert Perl array to non-array type %s",
1275  format_type_be(typid))));
1276 
1277  _sv_to_datum_finfo(elemtypid, &finfo, &typioparam);
1278 
1279  memset(dims, 0, sizeof(dims));
1280  dims[0] = av_len(nav) + 1;
1281 
1282  array_to_datum_internal(nav, &astate,
1283  &ndims, dims, 1,
1284  elemtypid, typmod,
1285  &finfo, typioparam);
1286 
1287  /* ensure we get zero-D array for no inputs, as per PG convention */
1288  if (astate == NULL)
1289  return PointerGetDatum(construct_empty_array(elemtypid));
1290 
1291  for (i = 0; i < ndims; i++)
1292  lbs[i] = 1;
1293 
1294  return makeMdArrayResult(astate, ndims, dims, lbs,
1295  CurrentMemoryContext, true);
1296 }
Datum makeMdArrayResult(ArrayBuildState *astate, int ndims, int *dims, int *lbs, MemoryContext rcontext, bool release)
Definition: arrayfuncs.c:5440
ArrayType * construct_empty_array(Oid elmtype)
Definition: arrayfuncs.c:3568
Oid get_element_type(Oid typid)
Definition: lsyscache.c:2759
static void _sv_to_datum_finfo(Oid typid, FmgrInfo *finfo, Oid *typioparam)
Definition: plperl.c:1300
static Datum PointerGetDatum(const void *X)
Definition: postgres.h:322

References _sv_to_datum_finfo(), array_to_datum_internal(), construct_empty_array(), CurrentMemoryContext, dTHX, ereport, errcode(), errmsg(), ERROR, format_type_be(), get_element_type(), i, makeMdArrayResult(), MAXDIM, and PointerGetDatum().

Referenced by plperl_sv_to_datum().

◆ plperl_build_tuple_result()

static HeapTuple plperl_build_tuple_result ( HV *  perlhash,
TupleDesc  td 
)
static

Definition at line 1075 of file plperl.c.

1076 {
1077  dTHX;
1078  Datum *values;
1079  bool *nulls;
1080  HE *he;
1081  HeapTuple tup;
1082 
1083  values = palloc0(sizeof(Datum) * td->natts);
1084  nulls = palloc(sizeof(bool) * td->natts);
1085  memset(nulls, true, sizeof(bool) * td->natts);
1086 
1087  hv_iterinit(perlhash);
1088  while ((he = hv_iternext(perlhash)))
1089  {
1090  SV *val = HeVAL(he);
1091  char *key = hek2cstr(he);
1092  int attn = SPI_fnumber(td, key);
1093  Form_pg_attribute attr = TupleDescAttr(td, attn - 1);
1094 
1095  if (attn == SPI_ERROR_NOATTRIBUTE)
1096  ereport(ERROR,
1097  (errcode(ERRCODE_UNDEFINED_COLUMN),
1098  errmsg("Perl hash contains nonexistent column \"%s\"",
1099  key)));
1100  if (attn <= 0)
1101  ereport(ERROR,
1102  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1103  errmsg("cannot set system attribute \"%s\"",
1104  key)));
1105 
1106  values[attn - 1] = plperl_sv_to_datum(val,
1107  attr->atttypid,
1108  attr->atttypmod,
1109  NULL,
1110  NULL,
1111  InvalidOid,
1112  &nulls[attn - 1]);
1113 
1114  pfree(key);
1115  }
1116  hv_iterinit(perlhash);
1117 
1118  tup = heap_form_tuple(td, values, nulls);
1119  pfree(values);
1120  pfree(nulls);
1121  return tup;
1122 }
static Datum values[MAXATTR]
Definition: bootstrap.c:150
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, const Datum *values, const bool *isnull)
Definition: heaptuple.c:1116
void * palloc(Size size)
Definition: mcxt.c:1317
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:209
static char * hek2cstr(HE *he)
Definition: plperl.c:323
int SPI_fnumber(TupleDesc tupdesc, const char *fname)
Definition: spi.c:1172
#define SPI_ERROR_NOATTRIBUTE
Definition: spi.h:76
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92

References dTHX, ereport, errcode(), errmsg(), ERROR, heap_form_tuple(), hek2cstr(), InvalidOid, sort-test::key, TupleDescData::natts, palloc(), palloc0(), pfree(), plperl_sv_to_datum(), SPI_ERROR_NOATTRIBUTE, SPI_fnumber(), TupleDescAttr, val, and values.

Referenced by plperl_hash_to_datum(), and plperl_return_next_internal().

◆ plperl_call_handler()

Datum plperl_call_handler ( PG_FUNCTION_ARGS  )

Definition at line 1852 of file plperl.c.

1853 {
1854  Datum retval = (Datum) 0;
1855  plperl_call_data *volatile save_call_data = current_call_data;
1856  plperl_interp_desc *volatile oldinterp = plperl_active_interp;
1857  plperl_call_data this_call_data;
1858 
1859  /* Initialize current-call status record */
1860  MemSet(&this_call_data, 0, sizeof(this_call_data));
1861  this_call_data.fcinfo = fcinfo;
1862 
1863  PG_TRY();
1864  {
1865  current_call_data = &this_call_data;
1866  if (CALLED_AS_TRIGGER(fcinfo))
1867  retval = plperl_trigger_handler(fcinfo);
1868  else if (CALLED_AS_EVENT_TRIGGER(fcinfo))
1869  {
1871  retval = (Datum) 0;
1872  }
1873  else
1874  retval = plperl_func_handler(fcinfo);
1875  }
1876  PG_FINALLY();
1877  {
1878  current_call_data = save_call_data;
1879  activate_interpreter(oldinterp);
1880  if (this_call_data.prodesc)
1881  decrement_prodesc_refcount(this_call_data.prodesc);
1882  }
1883  PG_END_TRY();
1884 
1885  return retval;
1886 }
#define MemSet(start, val, len)
Definition: c.h:1020
#define PG_FINALLY(...)
Definition: elog.h:388
#define CALLED_AS_EVENT_TRIGGER(fcinfo)
Definition: event_trigger.h:43
static void plperl_event_trigger_handler(PG_FUNCTION_ARGS)
Definition: plperl.c:2631
static Datum plperl_func_handler(PG_FUNCTION_ARGS)
Definition: plperl.c:2401
#define decrement_prodesc_refcount(prodesc)
Definition: plperl.c:129
static Datum plperl_trigger_handler(PG_FUNCTION_ARGS)
Definition: plperl.c:2519
FunctionCallInfo fcinfo
Definition: plperl.c:174
#define CALLED_AS_TRIGGER(fcinfo)
Definition: trigger.h:26

References activate_interpreter(), CALLED_AS_EVENT_TRIGGER, CALLED_AS_TRIGGER, current_call_data, decrement_prodesc_refcount, plperl_call_data::fcinfo, MemSet, PG_END_TRY, PG_FINALLY, PG_TRY, plperl_active_interp, plperl_event_trigger_handler(), plperl_func_handler(), plperl_trigger_handler(), and plperl_call_data::prodesc.

Referenced by plperlu_call_handler().

◆ plperl_call_perl_event_trigger_func()

static void plperl_call_perl_event_trigger_func ( plperl_proc_desc desc,
FunctionCallInfo  fcinfo,
SV *  td 
)
static

Definition at line 2340 of file plperl.c.

2343 {
2344  dTHX;
2345  dSP;
2346  SV *retval,
2347  *TDsv;
2348  int count;
2349 
2350  ENTER;
2351  SAVETMPS;
2352 
2353  TDsv = get_sv("main::_TD", 0);
2354  if (!TDsv)
2355  ereport(ERROR,
2356  (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
2357  errmsg("couldn't fetch $_TD")));
2358 
2359  save_item(TDsv); /* local $_TD */
2360  sv_setsv(TDsv, td);
2361 
2362  PUSHMARK(sp);
2363  PUTBACK;
2364 
2365  /* Do NOT use G_KEEPERR here */
2366  count = call_sv(desc->reference, G_SCALAR | G_EVAL);
2367 
2368  SPAGAIN;
2369 
2370  if (count != 1)
2371  {
2372  PUTBACK;
2373  FREETMPS;
2374  LEAVE;
2375  ereport(ERROR,
2376  (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
2377  errmsg("didn't get a return item from trigger function")));
2378  }
2379 
2380  if (SvTRUE(ERRSV))
2381  {
2382  (void) POPs;
2383  PUTBACK;
2384  FREETMPS;
2385  LEAVE;
2386  /* XXX need to find a way to determine a better errcode here */
2387  ereport(ERROR,
2388  (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
2390  }
2391 
2392  retval = newSVsv(POPs);
2393  (void) retval; /* silence compiler warning */
2394 
2395  PUTBACK;
2396  FREETMPS;
2397  LEAVE;
2398 }
static char * strip_trailing_ws(const char *msg)
Definition: plperl.c:1061
#define call_sv
Definition: ppport.h:15060
#define get_sv
Definition: ppport.h:12463
#define ERRSV
Definition: ppport.h:12444

References call_sv, dTHX, ereport, errcode(), errmsg(), ERROR, ERRSV, get_sv, plperl_proc_desc::reference, strip_trailing_ws(), and sv2cstr().

Referenced by plperl_event_trigger_handler().

◆ plperl_call_perl_func()

static SV * plperl_call_perl_func ( plperl_proc_desc desc,
FunctionCallInfo  fcinfo 
)
static

Definition at line 2179 of file plperl.c.

2180 {
2181  dTHX;
2182  dSP;
2183  SV *retval;
2184  int i;
2185  int count;
2186  Oid *argtypes = NULL;
2187  int nargs = 0;
2188 
2189  ENTER;
2190  SAVETMPS;
2191 
2192  PUSHMARK(SP);
2193  EXTEND(sp, desc->nargs);
2194 
2195  /* Get signature for true functions; inline blocks have no args. */
2196  if (fcinfo->flinfo->fn_oid)
2197  get_func_signature(fcinfo->flinfo->fn_oid, &argtypes, &nargs);
2198  Assert(nargs == desc->nargs);
2199 
2200  for (i = 0; i < desc->nargs; i++)
2201  {
2202  if (fcinfo->args[i].isnull)
2203  PUSHs(&PL_sv_undef);
2204  else if (desc->arg_is_rowtype[i])
2205  {
2206  SV *sv = plperl_hash_from_datum(fcinfo->args[i].value);
2207 
2208  PUSHs(sv_2mortal(sv));
2209  }
2210  else
2211  {
2212  SV *sv;
2213  Oid funcid;
2214 
2215  if (OidIsValid(desc->arg_arraytype[i]))
2216  sv = plperl_ref_from_pg_array(fcinfo->args[i].value, desc->arg_arraytype[i]);
2218  sv = (SV *) DatumGetPointer(OidFunctionCall1(funcid, fcinfo->args[i].value));
2219  else
2220  {
2221  char *tmp;
2222 
2223  tmp = OutputFunctionCall(&(desc->arg_out_func[i]),
2224  fcinfo->args[i].value);
2225  sv = cstr2sv(tmp);
2226  pfree(tmp);
2227  }
2228 
2229  PUSHs(sv_2mortal(sv));
2230  }
2231  }
2232  PUTBACK;
2233 
2234  /* Do NOT use G_KEEPERR here */
2235  count = call_sv(desc->reference, G_SCALAR | G_EVAL);
2236 
2237  SPAGAIN;
2238 
2239  if (count != 1)
2240  {
2241  PUTBACK;
2242  FREETMPS;
2243  LEAVE;
2244  ereport(ERROR,
2245  (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
2246  errmsg("didn't get a return item from function")));
2247  }
2248 
2249  if (SvTRUE(ERRSV))
2250  {
2251  (void) POPs;
2252  PUTBACK;
2253  FREETMPS;
2254  LEAVE;
2255  /* XXX need to find a way to determine a better errcode here */
2256  ereport(ERROR,
2257  (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
2259  }
2260 
2261  retval = newSVsv(POPs);
2262 
2263  PUTBACK;
2264  FREETMPS;
2265  LEAVE;
2266 
2267  return retval;
2268 }
#define OidFunctionCall1(functionId, arg1)
Definition: fmgr.h:679
Oid get_func_signature(Oid funcid, Oid **argtypes, int *nargs)
Definition: lsyscache.c:1696
Oid get_transform_fromsql(Oid typid, Oid langid, List *trftypes)
Definition: lsyscache.c:2120
static SV * plperl_ref_from_pg_array(Datum arg, Oid typid)
Definition: plperl.c:1480
#define PL_sv_undef
Definition: ppport.h:11780
FmgrInfo * flinfo
Definition: fmgr.h:87
NullableDatum args[FLEXIBLE_ARRAY_MEMBER]
Definition: fmgr.h:95
Datum value
Definition: postgres.h:75
bool isnull
Definition: postgres.h:77

References plperl_proc_desc::arg_arraytype, plperl_proc_desc::arg_is_rowtype, plperl_proc_desc::arg_out_func, FunctionCallInfoBaseData::args, Assert, call_sv, cstr2sv(), current_call_data, DatumGetPointer(), dTHX, ereport, errcode(), errmsg(), ERROR, ERRSV, FunctionCallInfoBaseData::flinfo, FmgrInfo::fn_oid, get_func_signature(), get_transform_fromsql(), i, NullableDatum::isnull, plperl_proc_desc::lang_oid, plperl_proc_desc::nargs, OidFunctionCall1, OidIsValid, OutputFunctionCall(), pfree(), PL_sv_undef, plperl_hash_from_datum(), plperl_ref_from_pg_array(), plperl_call_data::prodesc, plperl_proc_desc::reference, strip_trailing_ws(), sv2cstr(), plperl_proc_desc::trftypes, and NullableDatum::value.

Referenced by plperl_func_handler(), and plperl_inline_handler().

◆ plperl_call_perl_trigger_func()

static SV* plperl_call_perl_trigger_func ( plperl_proc_desc desc,
FunctionCallInfo  fcinfo,
SV *  td 
)
static

Definition at line 2272 of file plperl.c.

2274 {
2275  dTHX;
2276  dSP;
2277  SV *retval,
2278  *TDsv;
2279  int i,
2280  count;
2281  Trigger *tg_trigger = ((TriggerData *) fcinfo->context)->tg_trigger;
2282 
2283  ENTER;
2284  SAVETMPS;
2285 
2286  TDsv = get_sv("main::_TD", 0);
2287  if (!TDsv)
2288  ereport(ERROR,
2289  (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
2290  errmsg("couldn't fetch $_TD")));
2291 
2292  save_item(TDsv); /* local $_TD */
2293  sv_setsv(TDsv, td);
2294 
2295  PUSHMARK(sp);
2296  EXTEND(sp, tg_trigger->tgnargs);
2297 
2298  for (i = 0; i < tg_trigger->tgnargs; i++)
2299  PUSHs(sv_2mortal(cstr2sv(tg_trigger->tgargs[i])));
2300  PUTBACK;
2301 
2302  /* Do NOT use G_KEEPERR here */
2303  count = call_sv(desc->reference, G_SCALAR | G_EVAL);
2304 
2305  SPAGAIN;
2306 
2307  if (count != 1)
2308  {
2309  PUTBACK;
2310  FREETMPS;
2311  LEAVE;
2312  ereport(ERROR,
2313  (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
2314  errmsg("didn't get a return item from trigger function")));
2315  }
2316 
2317  if (SvTRUE(ERRSV))
2318  {
2319  (void) POPs;
2320  PUTBACK;
2321  FREETMPS;
2322  LEAVE;
2323  /* XXX need to find a way to determine a better errcode here */
2324  ereport(ERROR,
2325  (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
2327  }
2328 
2329  retval = newSVsv(POPs);
2330 
2331  PUTBACK;
2332  FREETMPS;
2333  LEAVE;
2334 
2335  return retval;
2336 }
fmNodePtr context
Definition: fmgr.h:88
int16 tgnargs
Definition: reltrigger.h:38
char ** tgargs
Definition: reltrigger.h:41

References call_sv, FunctionCallInfoBaseData::context, cstr2sv(), dTHX, ereport, errcode(), errmsg(), ERROR, ERRSV, get_sv, i, plperl_proc_desc::reference, strip_trailing_ws(), sv2cstr(), Trigger::tgargs, and Trigger::tgnargs.

Referenced by plperl_trigger_handler().

◆ plperl_compile_callback()

static void plperl_compile_callback ( void *  arg)
static

Definition at line 4151 of file plperl.c.

4152 {
4153  char *procname = (char *) arg;
4154 
4155  if (procname)
4156  errcontext("compilation of PL/Perl function \"%s\"", procname);
4157 }
#define errcontext
Definition: elog.h:196
void * arg

References arg, and errcontext.

Referenced by compile_plperl_function().

◆ plperl_create_sub()

static void plperl_create_sub ( plperl_proc_desc desc,
const char *  s,
Oid  fn_oid 
)
static

Definition at line 2094 of file plperl.c.

2095 {
2096  dTHX;
2097  dSP;
2098  char subname[NAMEDATALEN + 40];
2099  HV *pragma_hv = newHV();
2100  SV *subref = NULL;
2101  int count;
2102 
2103  sprintf(subname, "%s__%u", prodesc->proname, fn_oid);
2104 
2105  if (plperl_use_strict)
2106  hv_store_string(pragma_hv, "strict", (SV *) newAV());
2107 
2108  ENTER;
2109  SAVETMPS;
2110  PUSHMARK(SP);
2111  EXTEND(SP, 4);
2112  PUSHs(sv_2mortal(cstr2sv(subname)));
2113  PUSHs(sv_2mortal(newRV_noinc((SV *) pragma_hv)));
2114 
2115  /*
2116  * Use 'false' for $prolog in mkfunc, which is kept for compatibility in
2117  * case a module such as PostgreSQL::PLPerl::NYTprof replaces the function
2118  * compiler.
2119  */
2120  PUSHs(&PL_sv_no);
2121  PUSHs(sv_2mortal(cstr2sv(s)));
2122  PUTBACK;
2123 
2124  /*
2125  * G_KEEPERR seems to be needed here, else we don't recognize compile
2126  * errors properly. Perhaps it's because there's another level of eval
2127  * inside mkfunc?
2128  */
2129  count = call_pv("PostgreSQL::InServer::mkfunc",
2130  G_SCALAR | G_EVAL | G_KEEPERR);
2131  SPAGAIN;
2132 
2133  if (count == 1)
2134  {
2135  SV *sub_rv = (SV *) POPs;
2136 
2137  if (sub_rv && SvROK(sub_rv) && SvTYPE(SvRV(sub_rv)) == SVt_PVCV)
2138  {
2139  subref = newRV_inc(SvRV(sub_rv));
2140  }
2141  }
2142 
2143  PUTBACK;
2144  FREETMPS;
2145  LEAVE;
2146 
2147  if (SvTRUE(ERRSV))
2148  ereport(ERROR,
2149  (errcode(ERRCODE_SYNTAX_ERROR),
2151 
2152  if (!subref)
2153  ereport(ERROR,
2154  (errcode(ERRCODE_SYNTAX_ERROR),
2155  errmsg("didn't get a CODE reference from compiling function \"%s\"",
2156  prodesc->proname)));
2157 
2158  prodesc->reference = subref;
2159 }
#define NAMEDATALEN
NameData subname
static SV ** hv_store_string(HV *hv, const char *key, SV *val)
Definition: plperl.c:4089
#define sprintf
Definition: port.h:240
#define newRV_inc(sv)
Definition: ppport.h:15240
#define call_pv
Definition: ppport.h:14998
#define PL_sv_no
Definition: ppport.h:11779

References call_pv, cstr2sv(), dTHX, ereport, errcode(), errmsg(), ERROR, ERRSV, hv_store_string(), NAMEDATALEN, newRV_inc, newRV_noinc, PL_sv_no, plperl_use_strict, plperl_proc_desc::proname, plperl_proc_desc::reference, sprintf, strip_trailing_ws(), subname, and sv2cstr().

Referenced by compile_plperl_function(), and plperl_inline_handler().

◆ plperl_destroy_interp()

static void plperl_destroy_interp ( PerlInterpreter **  interp)
static

Definition at line 918 of file plperl.c.

919 {
920  if (interp && *interp)
921  {
922  /*
923  * Only a very minimal destruction is performed: - just call END
924  * blocks.
925  *
926  * We could call perl_destruct() but we'd need to audit its actions
927  * very carefully and work-around any that impact us. (Calling
928  * sv_clean_objs() isn't an option because it's not part of perl's
929  * public API so isn't portably available.) Meanwhile END blocks can
930  * be used to perform manual cleanup.
931  */
932  dTHX;
933 
934  /* Run END blocks - based on perl's perl_destruct() */
935  if (PL_exit_flags & PERL_EXIT_DESTRUCT_END)
936  {
937  dJMPENV;
938  int x = 0;
939 
940  JMPENV_PUSH(x);
942  if (PL_endav && !PL_minus_c)
943  call_list(PL_scopestack_ix, PL_endav);
944  JMPENV_POP;
945  }
946  LEAVE;
947  FREETMPS;
948 
949  *interp = NULL;
950  }
951 }
int x
Definition: isn.c:71
#define PERL_UNUSED_VAR(x)
Definition: ppport.h:12293

References dTHX, PERL_UNUSED_VAR, and x.

Referenced by plperl_fini().

◆ plperl_event_trigger_build_args()

static SV* plperl_event_trigger_build_args ( FunctionCallInfo  fcinfo)
static

Definition at line 1744 of file plperl.c.

1745 {
1746  dTHX;
1747  EventTriggerData *tdata;
1748  HV *hv;
1749 
1750  hv = newHV();
1751 
1752  tdata = (EventTriggerData *) fcinfo->context;
1753 
1754  hv_store_string(hv, "event", cstr2sv(tdata->event));
1755  hv_store_string(hv, "tag", cstr2sv(GetCommandTagName(tdata->tag)));
1756 
1757  return newRV_noinc((SV *) hv);
1758 }
const char * GetCommandTagName(CommandTag commandTag)
Definition: cmdtag.c:47
CommandTag tag
Definition: event_trigger.h:29
const char * event
Definition: event_trigger.h:27

References FunctionCallInfoBaseData::context, cstr2sv(), dTHX, EventTriggerData::event, GetCommandTagName(), hv_store_string(), newRV_noinc, and EventTriggerData::tag.

Referenced by plperl_event_trigger_handler().

◆ plperl_event_trigger_handler()

static void plperl_event_trigger_handler ( PG_FUNCTION_ARGS  )
static

Definition at line 2631 of file plperl.c.

2632 {
2633  plperl_proc_desc *prodesc;
2634  SV *svTD;
2635  ErrorContextCallback pl_error_context;
2636 
2637  /* Connect to SPI manager */
2638  SPI_connect();
2639 
2640  /* Find or compile the function */
2641  prodesc = compile_plperl_function(fcinfo->flinfo->fn_oid, false, true);
2642  current_call_data->prodesc = prodesc;
2643  increment_prodesc_refcount(prodesc);
2644 
2645  /* Set a callback for error reporting */
2646  pl_error_context.callback = plperl_exec_callback;
2647  pl_error_context.previous = error_context_stack;
2648  pl_error_context.arg = prodesc->proname;
2649  error_context_stack = &pl_error_context;
2650 
2651  activate_interpreter(prodesc->interp);
2652 
2653  svTD = plperl_event_trigger_build_args(fcinfo);
2654  plperl_call_perl_event_trigger_func(prodesc, fcinfo, svTD);
2655 
2656  if (SPI_finish() != SPI_OK_FINISH)
2657  elog(ERROR, "SPI_finish() failed");
2658 
2659  /* Restore the previous error callback */
2660  error_context_stack = pl_error_context.previous;
2661 
2662  SvREFCNT_dec_current(svTD);
2663 }
static SV * plperl_event_trigger_build_args(FunctionCallInfo fcinfo)
Definition: plperl.c:1744
static void plperl_exec_callback(void *arg)
Definition: plperl.c:4139
static plperl_proc_desc * compile_plperl_function(Oid fn_oid, bool is_trigger, bool is_event_trigger)
Definition: plperl.c:2714
static void plperl_call_perl_event_trigger_func(plperl_proc_desc *desc, FunctionCallInfo fcinfo, SV *td)
Definition: plperl.c:2340
int SPI_connect(void)
Definition: spi.c:94
int SPI_finish(void)
Definition: spi.c:182
#define SPI_OK_FINISH
Definition: spi.h:83

References activate_interpreter(), ErrorContextCallback::arg, ErrorContextCallback::callback, compile_plperl_function(), current_call_data, elog, ERROR, error_context_stack, increment_prodesc_refcount, plperl_proc_desc::interp, plperl_call_perl_event_trigger_func(), plperl_event_trigger_build_args(), plperl_exec_callback(), ErrorContextCallback::previous, plperl_call_data::prodesc, plperl_proc_desc::proname, SPI_connect(), SPI_finish(), SPI_OK_FINISH, and SvREFCNT_dec_current().

Referenced by plperl_call_handler().

◆ plperl_exec_callback()

static void plperl_exec_callback ( void *  arg)
static

Definition at line 4139 of file plperl.c.

4140 {
4141  char *procname = (char *) arg;
4142 
4143  if (procname)
4144  errcontext("PL/Perl function \"%s\"", procname);
4145 }

References arg, and errcontext.

Referenced by plperl_event_trigger_handler(), plperl_func_handler(), and plperl_trigger_handler().

◆ plperl_fini()

static void plperl_fini ( int  code,
Datum  arg 
)
static

Definition at line 509 of file plperl.c.

510 {
511  HASH_SEQ_STATUS hash_seq;
512  plperl_interp_desc *interp_desc;
513 
514  elog(DEBUG3, "plperl_fini");
515 
516  /*
517  * Indicate that perl is terminating. Disables use of spi_* functions when
518  * running END/DESTROY code. See check_spi_usage_allowed(). Could be
519  * enabled in future, with care, using a transaction
520  * http://archives.postgresql.org/pgsql-hackers/2010-01/msg02743.php
521  */
522  plperl_ending = true;
523 
524  /* Only perform perl cleanup if we're exiting cleanly */
525  if (code)
526  {
527  elog(DEBUG3, "plperl_fini: skipped");
528  return;
529  }
530 
531  /* Zap the "held" interpreter, if we still have it */
533 
534  /* Zap any fully-initialized interpreters */
535  hash_seq_init(&hash_seq, plperl_interp_hash);
536  while ((interp_desc = hash_seq_search(&hash_seq)) != NULL)
537  {
538  if (interp_desc->interp)
539  {
540  activate_interpreter(interp_desc);
541  plperl_destroy_interp(&interp_desc->interp);
542  }
543  }
544 
545  elog(DEBUG3, "plperl_fini: done");
546 }
void * hash_seq_search(HASH_SEQ_STATUS *status)
Definition: dynahash.c:1420
void hash_seq_init(HASH_SEQ_STATUS *status, HTAB *hashp)
Definition: dynahash.c:1385
#define DEBUG3
Definition: elog.h:28
static void plperl_destroy_interp(PerlInterpreter **)
Definition: plperl.c:918

References activate_interpreter(), DEBUG3, elog, hash_seq_init(), hash_seq_search(), plperl_interp_desc::interp, plperl_destroy_interp(), plperl_ending, plperl_held_interp, and plperl_interp_hash.

Referenced by select_perl_context().

◆ plperl_func_handler()

static Datum plperl_func_handler ( PG_FUNCTION_ARGS  )
static

Definition at line 2401 of file plperl.c.

2402 {
2403  bool nonatomic;
2404  plperl_proc_desc *prodesc;
2405  SV *perlret;
2406  Datum retval = 0;
2407  ReturnSetInfo *rsi;
2408  ErrorContextCallback pl_error_context;
2409 
2410  nonatomic = fcinfo->context &&
2411  IsA(fcinfo->context, CallContext) &&
2412  !castNode(CallContext, fcinfo->context)->atomic;
2413 
2414  SPI_connect_ext(nonatomic ? SPI_OPT_NONATOMIC : 0);
2415 
2416  prodesc = compile_plperl_function(fcinfo->flinfo->fn_oid, false, false);
2417  current_call_data->prodesc = prodesc;
2418  increment_prodesc_refcount(prodesc);
2419 
2420  /* Set a callback for error reporting */
2421  pl_error_context.callback = plperl_exec_callback;
2422  pl_error_context.previous = error_context_stack;
2423  pl_error_context.arg = prodesc->proname;
2424  error_context_stack = &pl_error_context;
2425 
2426  rsi = (ReturnSetInfo *) fcinfo->resultinfo;
2427 
2428  if (prodesc->fn_retisset)
2429  {
2430  /* Check context before allowing the call to go through */
2431  if (!rsi || !IsA(rsi, ReturnSetInfo))
2432  ereport(ERROR,
2433  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2434  errmsg("set-valued function called in context that cannot accept a set")));
2435 
2436  if (!(rsi->allowedModes & SFRM_Materialize))
2437  ereport(ERROR,
2438  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2439  errmsg("materialize mode required, but it is not allowed in this context")));
2440  }
2441 
2442  activate_interpreter(prodesc->interp);
2443 
2444  perlret = plperl_call_perl_func(prodesc, fcinfo);
2445 
2446  /************************************************************
2447  * Disconnect from SPI manager and then create the return
2448  * values datum (if the input function does a palloc for it
2449  * this must not be allocated in the SPI memory context
2450  * because SPI_finish would free it).
2451  ************************************************************/
2452  if (SPI_finish() != SPI_OK_FINISH)
2453  elog(ERROR, "SPI_finish() failed");
2454 
2455  if (prodesc->fn_retisset)
2456  {
2457  SV *sav;
2458 
2459  /*
2460  * If the Perl function returned an arrayref, we pretend that it
2461  * called return_next() for each element of the array, to handle old
2462  * SRFs that didn't know about return_next(). Any other sort of return
2463  * value is an error, except undef which means return an empty set.
2464  */
2465  sav = get_perl_array_ref(perlret);
2466  if (sav)
2467  {
2468  dTHX;
2469  int i = 0;
2470  SV **svp = 0;
2471  AV *rav = (AV *) SvRV(sav);
2472 
2473  while ((svp = av_fetch(rav, i, FALSE)) != NULL)
2474  {
2476  i++;
2477  }
2478  }
2479  else if (SvOK(perlret))
2480  {
2481  ereport(ERROR,
2482  (errcode(ERRCODE_DATATYPE_MISMATCH),
2483  errmsg("set-returning PL/Perl function must return "
2484  "reference to array or use return_next")));
2485  }
2486 
2489  {
2492  }
2493  retval = (Datum) 0;
2494  }
2495  else if (prodesc->result_oid)
2496  {
2497  retval = plperl_sv_to_datum(perlret,
2498  prodesc->result_oid,
2499  -1,
2500  fcinfo,
2501  &prodesc->result_in_func,
2502  prodesc->result_typioparam,
2503  &fcinfo->isnull);
2504 
2505  if (fcinfo->isnull && rsi && IsA(rsi, ReturnSetInfo))
2506  rsi->isDone = ExprEndResult;
2507  }
2508 
2509  /* Restore the previous error callback */
2510  error_context_stack = pl_error_context.previous;
2511 
2512  SvREFCNT_dec_current(perlret);
2513 
2514  return retval;
2515 }
@ ExprEndResult
Definition: execnodes.h:307
@ SFRM_Materialize
Definition: execnodes.h:319
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:77
#define IsA(nodeptr, _type_)
Definition: nodes.h:158
#define castNode(_type_, nodeptr)
Definition: nodes.h:176
static SV * plperl_call_perl_func(plperl_proc_desc *desc, FunctionCallInfo fcinfo)
Definition: plperl.c:2179
static void plperl_return_next_internal(SV *sv)
Definition: plperl.c:3271
int SPI_connect_ext(int options)
Definition: spi.c:100
#define SPI_OPT_NONATOMIC
Definition: spi.h:102
SetFunctionReturnMode returnMode
Definition: execnodes.h:338
TupleDesc setDesc
Definition: execnodes.h:342
Tuplestorestate * setResult
Definition: execnodes.h:341
int allowedModes
Definition: execnodes.h:336
ExprDoneCond isDone
Definition: execnodes.h:339
TupleDesc ret_tdesc
Definition: plperl.c:177
Tuplestorestate * tuple_store
Definition: plperl.c:176

References activate_interpreter(), ReturnSetInfo::allowedModes, ErrorContextCallback::arg, ErrorContextCallback::callback, castNode, compile_plperl_function(), current_call_data, dTHX, elog, ereport, errcode(), errmsg(), ERROR, error_context_stack, ExprEndResult, plperl_proc_desc::fn_retisset, get_perl_array_ref(), i, if(), increment_prodesc_refcount, plperl_proc_desc::interp, IsA, ReturnSetInfo::isDone, plperl_call_perl_func(), plperl_exec_callback(), plperl_return_next_internal(), plperl_sv_to_datum(), ErrorContextCallback::previous, plperl_call_data::prodesc, plperl_proc_desc::proname, plperl_proc_desc::result_in_func, plperl_proc_desc::result_oid, plperl_proc_desc::result_typioparam, plperl_call_data::ret_tdesc, ReturnSetInfo::returnMode, ReturnSetInfo::setDesc, ReturnSetInfo::setResult, SFRM_Materialize, SPI_connect_ext(), SPI_finish(), SPI_OK_FINISH, SPI_OPT_NONATOMIC, SvREFCNT_dec_current(), and plperl_call_data::tuple_store.

Referenced by plperl_call_handler().

◆ plperl_hash_from_datum()

static SV * plperl_hash_from_datum ( Datum  attr)
static

Definition at line 2994 of file plperl.c.

2995 {
2996  HeapTupleHeader td;
2997  Oid tupType;
2998  int32 tupTypmod;
2999  TupleDesc tupdesc;
3000  HeapTupleData tmptup;
3001  SV *sv;
3002 
3003  td = DatumGetHeapTupleHeader(attr);
3004 
3005  /* Extract rowtype info and find a tupdesc */
3006  tupType = HeapTupleHeaderGetTypeId(td);
3007  tupTypmod = HeapTupleHeaderGetTypMod(td);
3008  tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
3009 
3010  /* Build a temporary HeapTuple control structure */
3011  tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
3012  tmptup.t_data = td;
3013 
3014  sv = plperl_hash_from_tuple(&tmptup, tupdesc, true);
3015  ReleaseTupleDesc(tupdesc);
3016 
3017  return sv;
3018 }
#define DatumGetHeapTupleHeader(X)
Definition: fmgr.h:295
#define HeapTupleHeaderGetTypMod(tup)
Definition: htup_details.h:466
#define HeapTupleHeaderGetTypeId(tup)
Definition: htup_details.h:456
#define HeapTupleHeaderGetDatumLength(tup)
Definition: htup_details.h:450
static SV * plperl_hash_from_tuple(HeapTuple tuple, TupleDesc tupdesc, bool include_generated)
Definition: plperl.c:3022
uint32 t_len
Definition: htup.h:64
#define ReleaseTupleDesc(tupdesc)
Definition: tupdesc.h:122
TupleDesc lookup_rowtype_tupdesc(Oid type_id, int32 typmod)
Definition: typcache.c:1850

References DatumGetHeapTupleHeader, HeapTupleHeaderGetDatumLength, HeapTupleHeaderGetTypeId, HeapTupleHeaderGetTypMod, lookup_rowtype_tupdesc(), plperl_hash_from_tuple(), ReleaseTupleDesc, HeapTupleData::t_data, and HeapTupleData::t_len.

Referenced by make_array_ref(), plperl_call_perl_func(), and plperl_hash_from_tuple().

◆ plperl_hash_from_tuple()

static SV * plperl_hash_from_tuple ( HeapTuple  tuple,
TupleDesc  tupdesc,
bool  include_generated 
)
static

Definition at line 3022 of file plperl.c.

3023 {
3024  dTHX;
3025  HV *hv;
3026  int i;
3027 
3028  /* since this function recurses, it could be driven to stack overflow */
3030 
3031  hv = newHV();
3032  hv_ksplit(hv, tupdesc->natts); /* pre-grow the hash */
3033 
3034  for (i = 0; i < tupdesc->natts; i++)
3035  {
3036  Datum attr;
3037  bool isnull,
3038  typisvarlena;
3039  char *attname;
3040  Oid typoutput;
3041  Form_pg_attribute att = TupleDescAttr(tupdesc, i);
3042 
3043  if (att->attisdropped)
3044  continue;
3045 
3046  if (att->attgenerated)
3047  {
3048  /* don't include unless requested */
3049  if (!include_generated)
3050  continue;
3051  }
3052 
3053  attname = NameStr(att->attname);
3054  attr = heap_getattr(tuple, i + 1, tupdesc, &isnull);
3055 
3056  if (isnull)
3057  {
3058  /*
3059  * Store (attname => undef) and move on. Note we can't use
3060  * &PL_sv_undef here; see "AVs, HVs and undefined values" in
3061  * perlguts for an explanation.
3062  */
3063  hv_store_string(hv, attname, newSV(0));
3064  continue;
3065  }
3066 
3067  if (type_is_rowtype(att->atttypid))
3068  {
3069  SV *sv = plperl_hash_from_datum(attr);
3070 
3071  hv_store_string(hv, attname, sv);
3072  }
3073  else
3074  {
3075  SV *sv;
3076  Oid funcid;
3077 
3078  if (OidIsValid(get_base_element_type(att->atttypid)))
3079  sv = plperl_ref_from_pg_array(attr, att->atttypid);
3081  sv = (SV *) DatumGetPointer(OidFunctionCall1(funcid, attr));
3082  else
3083  {
3084  char *outputstr;
3085 
3086  /* XXX should have a way to cache these lookups */
3087  getTypeOutputInfo(att->atttypid, &typoutput, &typisvarlena);
3088 
3089  outputstr = OidOutputFunctionCall(typoutput, attr);
3090  sv = cstr2sv(outputstr);
3091  pfree(outputstr);
3092  }
3093 
3094  hv_store_string(hv, attname, sv);
3095  }
3096  }
3097  return newRV_noinc((SV *) hv);
3098 }
char * OidOutputFunctionCall(Oid functionId, Datum val)
Definition: fmgr.c:1763
static Datum heap_getattr(HeapTuple tup, int attnum, TupleDesc tupleDesc, bool *isnull)
Definition: htup_details.h:792
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:2907
Oid get_base_element_type(Oid typid)
Definition: lsyscache.c:2832
NameData attname
Definition: pg_attribute.h:41
void check_stack_depth(void)
Definition: postgres.c:3540

References attname, check_stack_depth(), cstr2sv(), current_call_data, DatumGetPointer(), dTHX, get_base_element_type(), get_transform_fromsql(), getTypeOutputInfo(), heap_getattr(), hv_store_string(), i, plperl_proc_desc::lang_oid, NameStr, TupleDescData::natts, newRV_noinc, OidFunctionCall1, OidIsValid, OidOutputFunctionCall(), pfree(), plperl_hash_from_datum(), plperl_ref_from_pg_array(), plperl_call_data::prodesc, plperl_proc_desc::trftypes, TupleDescAttr, and type_is_rowtype().

Referenced by plperl_hash_from_datum(), plperl_spi_execute_fetch_result(), plperl_spi_fetchrow(), and plperl_trigger_build_args().

◆ plperl_hash_to_datum()

static Datum plperl_hash_to_datum ( SV *  src,
TupleDesc  td 
)
static

Definition at line 1126 of file plperl.c.

1127 {
1128  HeapTuple tup = plperl_build_tuple_result((HV *) SvRV(src), td);
1129 
1130  return HeapTupleGetDatum(tup);
1131 }
static Datum HeapTupleGetDatum(const HeapTupleData *tuple)
Definition: funcapi.h:230
static HeapTuple plperl_build_tuple_result(HV *perlhash, TupleDesc td)
Definition: plperl.c:1075

References HeapTupleGetDatum(), and plperl_build_tuple_result().

Referenced by plperl_sv_to_datum().

◆ plperl_init_interp()

static PerlInterpreter * plperl_init_interp ( void  )
static

Definition at line 705 of file plperl.c.

706 {
707  PerlInterpreter *plperl;
708 
709  static char *embedding[3 + 2] = {
710  "", "-e", PLC_PERLBOOT
711  };
712  int nargs = 3;
713 
714 #ifdef WIN32
715 
716  /*
717  * The perl library on startup does horrible things like call
718  * setlocale(LC_ALL,""). We have protected against that on most platforms
719  * by setting the environment appropriately. However, on Windows,
720  * setlocale() does not consult the environment, so we need to save the
721  * existing locale settings before perl has a chance to mangle them and
722  * restore them after its dirty deeds are done.
723  *
724  * MSDN ref:
725  * http://msdn.microsoft.com/library/en-us/vclib/html/_crt_locale.asp
726  *
727  * It appears that we only need to do this on interpreter startup, and
728  * subsequent calls to the interpreter don't mess with the locale
729  * settings.
730  *
731  * We restore them using setlocale_perl(), defined below, so that Perl
732  * doesn't have a different idea of the locale from Postgres.
733  *
734  */
735 
736  char *loc;
737  char *save_collate,
738  *save_ctype,
739  *save_monetary,
740  *save_numeric,
741  *save_time;
742 
743  loc = setlocale(LC_COLLATE, NULL);
744  save_collate = loc ? pstrdup(loc) : NULL;
745  loc = setlocale(LC_CTYPE, NULL);
746  save_ctype = loc ? pstrdup(loc) : NULL;
747  loc = setlocale(LC_MONETARY, NULL);
748  save_monetary = loc ? pstrdup(loc) : NULL;
749  loc = setlocale(LC_NUMERIC, NULL);
750  save_numeric = loc ? pstrdup(loc) : NULL;
751  loc = setlocale(LC_TIME, NULL);
752  save_time = loc ? pstrdup(loc) : NULL;
753 
754 #define PLPERL_RESTORE_LOCALE(name, saved) \
755  STMT_START { \
756  if (saved != NULL) { setlocale_perl(name, saved); pfree(saved); } \
757  } STMT_END
758 #endif /* WIN32 */
759 
761  {
762  embedding[nargs++] = "-e";
763  embedding[nargs++] = plperl_on_init;
764  }
765 
766  /*
767  * The perl API docs state that PERL_SYS_INIT3 should be called before
768  * allocating interpreters. Unfortunately, on some platforms this fails in
769  * the Perl_do_taint() routine, which is called when the platform is using
770  * the system's malloc() instead of perl's own. Other platforms, notably
771  * Windows, fail if PERL_SYS_INIT3 is not called. So we call it if it's
772  * available, unless perl is using the system malloc(), which is true when
773  * MYMALLOC is set.
774  */
775 #if defined(PERL_SYS_INIT3) && !defined(MYMALLOC)
776  {
777  static int perl_sys_init_done;
778 
779  /* only call this the first time through, as per perlembed man page */
780  if (!perl_sys_init_done)
781  {
782  char *dummy_env[1] = {NULL};
783 
784  PERL_SYS_INIT3(&nargs, (char ***) &embedding, (char ***) &dummy_env);
785 
786  /*
787  * For unclear reasons, PERL_SYS_INIT3 sets the SIGFPE handler to
788  * SIG_IGN. Aside from being extremely unfriendly behavior for a
789  * library, this is dumb on the grounds that the results of a
790  * SIGFPE in this state are undefined according to POSIX, and in
791  * fact you get a forced process kill at least on Linux. Hence,
792  * restore the SIGFPE handler to the backend's standard setting.
793  * (See Perl bug 114574 for more information.)
794  */
796 
797  perl_sys_init_done = 1;
798  /* quiet warning if PERL_SYS_INIT3 doesn't use the third argument */
799  dummy_env[0] = NULL;
800  }
801  }
802 #endif
803 
804  plperl = perl_alloc();
805  if (!plperl)
806  elog(ERROR, "could not allocate Perl interpreter");
807 
808  PERL_SET_CONTEXT(plperl);
809  perl_construct(plperl);
810 
811  /*
812  * Run END blocks in perl_destruct instead of perl_run. Note that dTHX
813  * loads up a pointer to the current interpreter, so we have to postpone
814  * it to here rather than put it at the function head.
815  */
816  {
817  dTHX;
818 
819  PL_exit_flags |= PERL_EXIT_DESTRUCT_END;
820 
821  /*
822  * Record the original function for the 'require' and 'dofile'
823  * opcodes. (They share the same implementation.) Ensure it's used
824  * for new interpreters.
825  */
826  if (!pp_require_orig)
827  pp_require_orig = PL_ppaddr[OP_REQUIRE];
828  else
829  {
830  PL_ppaddr[OP_REQUIRE] = pp_require_orig;
831  PL_ppaddr[OP_DOFILE] = pp_require_orig;
832  }
833 
834 #ifdef PLPERL_ENABLE_OPMASK_EARLY
835 
836  /*
837  * For regression testing to prove that the PLC_PERLBOOT and
838  * PLC_TRUSTED code doesn't even compile any unsafe ops. In future
839  * there may be a valid need for them to do so, in which case this
840  * could be softened (perhaps moved to plperl_trusted_init()) or
841  * removed.
842  */
843  PL_op_mask = plperl_opmask;
844 #endif
845 
846  if (perl_parse(plperl, plperl_init_shared_libs,
847  nargs, embedding, NULL) != 0)
848  ereport(ERROR,
849  (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
851  errcontext("while parsing Perl initialization")));
852 
853  if (perl_run(plperl) != 0)
854  ereport(ERROR,
855  (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
857  errcontext("while running Perl initialization")));
858 
859 #ifdef PLPERL_RESTORE_LOCALE
860  PLPERL_RESTORE_LOCALE(LC_COLLATE, save_collate);
861  PLPERL_RESTORE_LOCALE(LC_CTYPE, save_ctype);
862  PLPERL_RESTORE_LOCALE(LC_MONETARY, save_monetary);
863  PLPERL_RESTORE_LOCALE(LC_NUMERIC, save_numeric);
864  PLPERL_RESTORE_LOCALE(LC_TIME, save_time);
865 #endif
866  }
867 
868  return plperl;
869 }
static void plperl_init_shared_libs(pTHX)
Definition: plperl.c:2167
static OP *(* pp_require_orig)(pTHX)
Definition: plperl.c:237
pqsigfunc pqsignal(int signo, pqsigfunc func)
void FloatExceptionHandler(SIGNAL_ARGS)
Definition: postgres.c:3028
#define PL_ppaddr
Definition: ppport.h:11735
#define setlocale(a, b)
Definition: win32_port.h:485

References dTHX, elog, ereport, errcode(), errcontext, errmsg(), ERROR, ERRSV, FloatExceptionHandler(), PL_ppaddr, plperl_init_shared_libs(), plperl_on_init, plperl_opmask, pp_require_orig, pqsignal(), pstrdup(), setlocale, strip_trailing_ws(), and sv2cstr().

Referenced by _PG_init(), and select_perl_context().

◆ plperl_init_shared_libs()

static void plperl_init_shared_libs ( pTHX  )
static

Definition at line 2167 of file plperl.c.

2168 {
2169  char *file = __FILE__;
2170 
2171  newXS("DynaLoader::boot_DynaLoader", boot_DynaLoader, file);
2172  newXS("PostgreSQL::InServer::Util::bootstrap",
2174  /* newXS for...::SPI::bootstrap is in select_perl_context() */
2175 }
EXTERN_C void boot_DynaLoader(pTHX_ CV *cv)
EXTERN_C void boot_PostgreSQL__InServer__Util(pTHX_ CV *cv)

References boot_DynaLoader(), and boot_PostgreSQL__InServer__Util().

Referenced by plperl_init_interp().

◆ plperl_inline_callback()

static void plperl_inline_callback ( void *  arg)
static

Definition at line 4163 of file plperl.c.

4164 {
4165  errcontext("PL/Perl anonymous code block");
4166 }

References errcontext.

Referenced by plperl_inline_handler().

◆ plperl_inline_handler()

Datum plperl_inline_handler ( PG_FUNCTION_ARGS  )

Definition at line 1894 of file plperl.c.

1895 {
1896  LOCAL_FCINFO(fake_fcinfo, 0);
1898  FmgrInfo flinfo;
1899  plperl_proc_desc desc;
1900  plperl_call_data *volatile save_call_data = current_call_data;
1901  plperl_interp_desc *volatile oldinterp = plperl_active_interp;
1902  plperl_call_data this_call_data;
1903  ErrorContextCallback pl_error_context;
1904 
1905  /* Initialize current-call status record */
1906  MemSet(&this_call_data, 0, sizeof(this_call_data));
1907 
1908  /* Set up a callback for error reporting */
1909  pl_error_context.callback = plperl_inline_callback;
1910  pl_error_context.previous = error_context_stack;
1911  pl_error_context.arg = NULL;
1912  error_context_stack = &pl_error_context;
1913 
1914  /*
1915  * Set up a fake fcinfo and descriptor with just enough info to satisfy
1916  * plperl_call_perl_func(). In particular note that this sets things up
1917  * with no arguments passed, and a result type of VOID.
1918  */
1919  MemSet(fake_fcinfo, 0, SizeForFunctionCallInfo(0));
1920  MemSet(&flinfo, 0, sizeof(flinfo));
1921  MemSet(&desc, 0, sizeof(desc));
1922  fake_fcinfo->flinfo = &flinfo;
1923  flinfo.fn_oid = InvalidOid;
1924  flinfo.fn_mcxt = CurrentMemoryContext;
1925 
1926  desc.proname = "inline_code_block";
1927  desc.fn_readonly = false;
1928 
1929  desc.lang_oid = codeblock->langOid;
1930  desc.trftypes = NIL;
1931  desc.lanpltrusted = codeblock->langIsTrusted;
1932 
1933  desc.fn_retistuple = false;
1934  desc.fn_retisset = false;
1935  desc.fn_retisarray = false;
1936  desc.result_oid = InvalidOid;
1937  desc.nargs = 0;
1938  desc.reference = NULL;
1939 
1940  this_call_data.fcinfo = fake_fcinfo;
1941  this_call_data.prodesc = &desc;
1942  /* we do not bother with refcounting the fake prodesc */
1943 
1944  PG_TRY();
1945  {
1946  SV *perlret;
1947 
1948  current_call_data = &this_call_data;
1949 
1950  SPI_connect_ext(codeblock->atomic ? 0 : SPI_OPT_NONATOMIC);
1951 
1953 
1954  plperl_create_sub(&desc, codeblock->source_text, 0);
1955 
1956  if (!desc.reference) /* can this happen? */
1957  elog(ERROR, "could not create internal procedure for anonymous code block");
1958 
1959  perlret = plperl_call_perl_func(&desc, fake_fcinfo);
1960 
1961  SvREFCNT_dec_current(perlret);
1962 
1963  if (SPI_finish() != SPI_OK_FINISH)
1964  elog(ERROR, "SPI_finish() failed");
1965  }
1966  PG_FINALLY();
1967  {
1968  if (desc.reference)
1970  current_call_data = save_call_data;
1971  activate_interpreter(oldinterp);
1972  }
1973  PG_END_TRY();
1974 
1975  error_context_stack = pl_error_context.previous;
1976 
1977  PG_RETURN_VOID();
1978 }
#define PG_RETURN_VOID()
Definition: fmgr.h:349
#define PG_GETARG_POINTER(n)
Definition: fmgr.h:276
#define SizeForFunctionCallInfo(nargs)
Definition: fmgr.h:102
#define LOCAL_FCINFO(name, nargs)
Definition: fmgr.h:110
static void plperl_inline_callback(void *arg)
Definition: plperl.c:4163
MemoryContext fn_mcxt
Definition: fmgr.h:65
char * source_text
Definition: parsenodes.h:3484

References activate_interpreter(), ErrorContextCallback::arg, InlineCodeBlock::atomic, ErrorContextCallback::callback, current_call_data, CurrentMemoryContext, elog, ERROR, error_context_stack, plperl_call_data::fcinfo, FmgrInfo::fn_mcxt, FmgrInfo::fn_oid, plperl_proc_desc::fn_readonly, plperl_proc_desc::fn_retisarray, plperl_proc_desc::fn_retisset, plperl_proc_desc::fn_retistuple, InvalidOid, plperl_proc_desc::lang_oid, InlineCodeBlock::langIsTrusted, InlineCodeBlock::langOid, plperl_proc_desc::lanpltrusted, LOCAL_FCINFO, MemSet, plperl_proc_desc::nargs, NIL, PG_END_TRY, PG_FINALLY, PG_GETARG_POINTER, PG_RETURN_VOID, PG_TRY, plperl_active_interp, plperl_call_perl_func(), plperl_create_sub(), plperl_inline_callback(), ErrorContextCallback::previous, plperl_call_data::prodesc, plperl_proc_desc::proname, plperl_proc_desc::reference, plperl_proc_desc::result_oid, select_perl_context(), SizeForFunctionCallInfo, InlineCodeBlock::source_text, SPI_connect_ext(), SPI_finish(), SPI_OK_FINISH, SPI_OPT_NONATOMIC, SvREFCNT_dec_current(), and plperl_proc_desc::trftypes.

Referenced by plperlu_inline_handler().

◆ plperl_modify_tuple()

static HeapTuple plperl_modify_tuple ( HV *  hvTD,
TriggerData tdata,
HeapTuple  otup 
)
static

Definition at line 1762 of file plperl.c.

1763 {
1764  dTHX;
1765  SV **svp;
1766  HV *hvNew;
1767  HE *he;
1768  HeapTuple rtup;
1769  TupleDesc tupdesc;
1770  int natts;
1771  Datum *modvalues;
1772  bool *modnulls;
1773  bool *modrepls;
1774 
1775  svp = hv_fetch_string(hvTD, "new");
1776  if (!svp)
1777  ereport(ERROR,
1778  (errcode(ERRCODE_UNDEFINED_COLUMN),
1779  errmsg("$_TD->{new} does not exist")));
1780  if (!SvOK(*svp) || !SvROK(*svp) || SvTYPE(SvRV(*svp)) != SVt_PVHV)
1781  ereport(ERROR,
1782  (errcode(ERRCODE_DATATYPE_MISMATCH),
1783  errmsg("$_TD->{new} is not a hash reference")));
1784  hvNew = (HV *) SvRV(*svp);
1785 
1786  tupdesc = tdata->tg_relation->rd_att;
1787  natts = tupdesc->natts;
1788 
1789  modvalues = (Datum *) palloc0(natts * sizeof(Datum));
1790  modnulls = (bool *) palloc0(natts * sizeof(bool));
1791  modrepls = (bool *) palloc0(natts * sizeof(bool));
1792 
1793  hv_iterinit(hvNew);
1794  while ((he = hv_iternext(hvNew)))
1795  {
1796  char *key = hek2cstr(he);
1797  SV *val = HeVAL(he);
1798  int attn = SPI_fnumber(tupdesc, key);
1799  Form_pg_attribute attr = TupleDescAttr(tupdesc, attn - 1);
1800 
1801  if (attn == SPI_ERROR_NOATTRIBUTE)
1802  ereport(ERROR,
1803  (errcode(ERRCODE_UNDEFINED_COLUMN),
1804  errmsg("Perl hash contains nonexistent column \"%s\"",
1805  key)));
1806  if (attn <= 0)
1807  ereport(ERROR,
1808  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1809  errmsg("cannot set system attribute \"%s\"",
1810  key)));
1811  if (attr->attgenerated)
1812  ereport(ERROR,
1813  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
1814  errmsg("cannot set generated column \"%s\"",
1815  key)));
1816 
1817  modvalues[attn - 1] = plperl_sv_to_datum(val,
1818  attr->atttypid,
1819  attr->atttypmod,
1820  NULL,
1821  NULL,
1822  InvalidOid,
1823  &modnulls[attn - 1]);
1824  modrepls[attn - 1] = true;
1825 
1826  pfree(key);
1827  }
1828  hv_iterinit(hvNew);
1829 
1830  rtup = heap_modify_tuple(otup, tupdesc, modvalues, modnulls, modrepls);
1831 
1832  pfree(modvalues);
1833  pfree(modnulls);
1834  pfree(modrepls);
1835 
1836  return rtup;
1837 }
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, const Datum *replValues, const bool *replIsnull, const bool *doReplace)
Definition: heaptuple.c:1209
TupleDesc rd_att
Definition: rel.h:112
Relation tg_relation
Definition: trigger.h:35

References dTHX, ereport, errcode(), errmsg(), ERROR, heap_modify_tuple(), hek2cstr(), hv_fetch_string(), InvalidOid, sort-test::key, TupleDescData::natts, palloc0(), pfree(), plperl_sv_to_datum(), RelationData::rd_att, SPI_ERROR_NOATTRIBUTE, SPI_fnumber(), TriggerData::tg_relation, TupleDescAttr, and val.

Referenced by plperl_trigger_handler().

◆ plperl_ref_from_pg_array()

static SV * plperl_ref_from_pg_array ( Datum  arg,
Oid  typid 
)
static

Definition at line 1480 of file plperl.c.

1481 {
1482  dTHX;
1484  Oid elementtype = ARR_ELEMTYPE(ar);
1485  int16 typlen;
1486  bool typbyval;
1487  char typalign,
1488  typdelim;
1489  Oid typioparam;
1490  Oid typoutputfunc;
1491  Oid transform_funcid;
1492  int i,
1493  nitems,
1494  *dims;
1495  plperl_array_info *info;
1496  SV *av;
1497  HV *hv;
1498 
1499  /*
1500  * Currently we make no effort to cache any of the stuff we look up here,
1501  * which is bad.
1502  */
1503  info = palloc0(sizeof(plperl_array_info));
1504 
1505  /* get element type information, including output conversion function */
1506  get_type_io_data(elementtype, IOFunc_output,
1507  &typlen, &typbyval, &typalign,
1508  &typdelim, &typioparam, &typoutputfunc);
1509 
1510  /* Check for a transform function */
1511  transform_funcid = get_transform_fromsql(elementtype,
1514 
1515  /* Look up transform or output function as appropriate */
1516  if (OidIsValid(transform_funcid))
1517  fmgr_info(transform_funcid, &info->transform_proc);
1518  else
1519  fmgr_info(typoutputfunc, &info->proc);
1520 
1521  info->elem_is_rowtype = type_is_rowtype(elementtype);
1522 
1523  /* Get the number and bounds of array dimensions */
1524  info->ndims = ARR_NDIM(ar);
1525  dims = ARR_DIMS(ar);
1526 
1527  /* No dimensions? Return an empty array */
1528  if (info->ndims == 0)
1529  {
1530  av = newRV_noinc((SV *) newAV());
1531  }
1532  else
1533  {
1534  deconstruct_array(ar, elementtype, typlen, typbyval,
1535  typalign, &info->elements, &info->nulls,
1536  &nitems);
1537 
1538  /* Get total number of elements in each dimension */
1539  info->nelems = palloc(sizeof(int) * info->ndims);
1540  info->nelems[0] = nitems;
1541  for (i = 1; i < info->ndims; i++)
1542  info->nelems[i] = info->nelems[i - 1] / dims[i - 1];
1543 
1544  av = split_array(info, 0, nitems, 0);
1545  }
1546 
1547  hv = newHV();
1548  (void) hv_store(hv, "array", 5, av, 0);
1549  (void) hv_store(hv, "typeoid", 7, newSVuv(typid), 0);
1550 
1551  return sv_bless(newRV_noinc((SV *) hv),
1552  gv_stashpv("PostgreSQL::InServer::ARRAY", 0));
1553 }
#define ARR_NDIM(a)
Definition: array.h:290
#define DatumGetArrayTypeP(X)
Definition: array.h:261
#define ARR_ELEMTYPE(a)
Definition: array.h:292
#define ARR_DIMS(a)
Definition: array.h:294
void deconstruct_array(ArrayType *array, Oid elmtype, int elmlen, bool elmbyval, char elmalign, Datum **elemsp, bool **nullsp, int *nelemsp)
Definition: arrayfuncs.c:3619
signed short int16
Definition: c.h:493
#define nitems(x)
Definition: indent.h:31
void get_type_io_data(Oid typid, IOFuncSelector which_func, int16 *typlen, bool *typbyval, char *typalign, char *typdelim, Oid *typioparam, Oid *func)
Definition: lsyscache.c:2325
@ IOFunc_output
Definition: lsyscache.h:36
char typalign
Definition: pg_type.h:176
static SV * split_array(plperl_array_info *info, int first, int last, int nest)
Definition: plperl.c:1559
#define newSVuv(uv)
Definition: ppport.h:14511

References arg, ARR_DIMS, ARR_ELEMTYPE, ARR_NDIM, av, current_call_data, DatumGetArrayTypeP, deconstruct_array(), dTHX, plperl_array_info::elem_is_rowtype, plperl_array_info::elements, fmgr_info(), get_transform_fromsql(), get_type_io_data(), i, IOFunc_output, plperl_proc_desc::lang_oid, plperl_array_info::ndims, plperl_array_info::nelems, newRV_noinc, newSVuv, nitems, plperl_array_info::nulls, OidIsValid, palloc(), palloc0(), plperl_array_info::proc, plperl_call_data::prodesc, split_array(), plperl_array_info::transform_proc, plperl_proc_desc::trftypes, typalign, and type_is_rowtype().

Referenced by plperl_call_perl_func(), and plperl_hash_from_tuple().

◆ plperl_return_next()

void plperl_return_next ( SV *  sv)

Definition at line 3241 of file plperl.c.

3242 {
3243  MemoryContext oldcontext = CurrentMemoryContext;
3244 
3246 
3247  PG_TRY();
3248  {
3250  }
3251  PG_CATCH();
3252  {
3253  ErrorData *edata;
3254 
3255  /* Must reset elog.c's state */
3256  MemoryContextSwitchTo(oldcontext);
3257  edata = CopyErrorData();
3258  FlushErrorState();
3259 
3260  /* Punt the error to Perl */
3261  croak_cstr(edata->message);
3262  }
3263  PG_END_TRY();
3264 }
void FlushErrorState(void)
Definition: elog.c:1867
ErrorData * CopyErrorData(void)
Definition: elog.c:1746
static void check_spi_usage_allowed(void)
Definition: plperl.c:3102
static void croak_cstr(const char *str)
Definition: plperl.h:175
char * message
Definition: elog.h:440

References check_spi_usage_allowed(), CopyErrorData(), croak_cstr(), CurrentMemoryContext, FlushErrorState(), MemoryContextSwitchTo(), ErrorData::message, PG_CATCH, PG_END_TRY, PG_TRY, and plperl_return_next_internal().

◆ plperl_return_next_internal()

static void plperl_return_next_internal ( SV *  sv)
static

Definition at line 3271 of file plperl.c.

3272 {
3273  plperl_proc_desc *prodesc;
3274  FunctionCallInfo fcinfo;
3275  ReturnSetInfo *rsi;
3276  MemoryContext old_cxt;
3277 
3278  if (!sv)
3279  return;
3280 
3281  prodesc = current_call_data->prodesc;
3282  fcinfo = current_call_data->fcinfo;
3283  rsi = (ReturnSetInfo *) fcinfo->resultinfo;
3284 
3285  if (!prodesc->fn_retisset)
3286  ereport(ERROR,
3287  (errcode(ERRCODE_SYNTAX_ERROR),
3288  errmsg("cannot use return_next in a non-SETOF function")));
3289 
3291  {
3292  TupleDesc tupdesc;
3293 
3295 
3296  /*
3297  * This is the first call to return_next in the current PL/Perl
3298  * function call, so identify the output tuple type and create a
3299  * tuplestore to hold the result rows.
3300  */
3301  if (prodesc->fn_retistuple)
3302  {
3303  TypeFuncClass funcclass;
3304  Oid typid;
3305 
3306  funcclass = get_call_result_type(fcinfo, &typid, &tupdesc);
3307  if (funcclass != TYPEFUNC_COMPOSITE &&
3308  funcclass != TYPEFUNC_COMPOSITE_DOMAIN)
3309  ereport(ERROR,
3310  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
3311  errmsg("function returning record called in context "
3312  "that cannot accept type record")));
3313  /* if domain-over-composite, remember the domain's type OID */
3314  if (funcclass == TYPEFUNC_COMPOSITE_DOMAIN)
3315  current_call_data->cdomain_oid = typid;
3316  }
3317  else
3318  {
3319  tupdesc = rsi->expectedDesc;
3320  /* Protect assumption below that we return exactly one column */
3321  if (tupdesc == NULL || tupdesc->natts != 1)
3322  elog(ERROR, "expected single-column result descriptor for non-composite SETOF result");
3323  }
3324 
3325  /*
3326  * Make sure the tuple_store and ret_tdesc are sufficiently
3327  * long-lived.
3328  */
3330 
3334  false, work_mem);
3335 
3336  MemoryContextSwitchTo(old_cxt);
3337  }
3338 
3339  /*
3340  * Producing the tuple we want to return requires making plenty of
3341  * palloc() allocations that are not cleaned up. Since this function can
3342  * be called many times before the current memory context is reset, we
3343  * need to do those allocations in a temporary context.
3344  */
3345  if (!current_call_data->tmp_cxt)
3346  {
3349  "PL/Perl return_next temporary cxt",
3351  }
3352 
3354 
3355  if (prodesc->fn_retistuple)
3356  {
3357  HeapTuple tuple;
3358 
3359  if (!(SvOK(sv) && SvROK(sv) && SvTYPE(SvRV(sv)) == SVt_PVHV))
3360  ereport(ERROR,
3361  (errcode(ERRCODE_DATATYPE_MISMATCH),
3362  errmsg("SETOF-composite-returning PL/Perl function "
3363  "must call return_next with reference to hash")));
3364 
3365  tuple = plperl_build_tuple_result((HV *) SvRV(sv),
3367 
3369  domain_check(HeapTupleGetDatum(tuple), false,
3373 
3375  }
3376  else if (prodesc->result_oid)
3377  {
3378  Datum ret[1];
3379  bool isNull[1];
3380 
3381  ret[0] = plperl_sv_to_datum(sv,
3382  prodesc->result_oid,
3383  -1,
3384  fcinfo,
3385  &prodesc->result_in_func,
3386  prodesc->result_typioparam,
3387  &isNull[0]);
3388 
3391  ret, isNull);
3392  }
3393 
3394  MemoryContextSwitchTo(old_cxt);
3396 }
void domain_check(Datum value, bool isnull, Oid domainType, void **extra, MemoryContext mcxt)
Definition: domains.c:346
@ SFRM_Materialize_Random
Definition: execnodes.h:320
TypeFuncClass get_call_result_type(FunctionCallInfo fcinfo, Oid *resultTypeId, TupleDesc *resultTupleDesc)
Definition: funcapi.c:276
TypeFuncClass
Definition: funcapi.h:147
@ TYPEFUNC_COMPOSITE
Definition: funcapi.h:149
@ TYPEFUNC_COMPOSITE_DOMAIN
Definition: funcapi.h:150
int work_mem
Definition: globals.c:130
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:383
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:160
MemoryContext ecxt_per_query_memory
Definition: execnodes.h:264
fmNodePtr resultinfo
Definition: fmgr.h:89
ExprContext * econtext
Definition: execnodes.h:334
TupleDesc expectedDesc
Definition: execnodes.h:335
void * cdomain_info
Definition: plperl.c:179
MemoryContext tmp_cxt
Definition: plperl.c:180
TupleDesc CreateTupleDescCopy(TupleDesc tupdesc)
Definition: tupdesc.c:133
Tuplestorestate * tuplestore_begin_heap(bool randomAccess, bool interXact, int maxKBytes)
Definition: tuplestore.c:330
void tuplestore_putvalues(Tuplestorestate *state, TupleDesc tdesc, const Datum *values, const bool *isnull)
Definition: tuplestore.c:784
void tuplestore_puttuple(Tuplestorestate *state, HeapTuple tuple)
Definition: tuplestore.c:764

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, ReturnSetInfo::allowedModes, Assert, plperl_call_data::cdomain_info, plperl_call_data::cdomain_oid, CreateTupleDescCopy(), current_call_data, CurrentMemoryContext, domain_check(), ReturnSetInfo::econtext, ExprContext::ecxt_per_query_memory, elog, ereport, errcode(), errmsg(), ERROR, ReturnSetInfo::expectedDesc, plperl_call_data::fcinfo, plperl_proc_desc::fn_retisset, plperl_proc_desc::fn_retistuple, get_call_result_type(), HeapTupleGetDatum(), if(), MemoryContextReset(), MemoryContextSwitchTo(), TupleDescData::natts, OidIsValid, plperl_build_tuple_result(), plperl_sv_to_datum(), plperl_call_data::prodesc, plperl_proc_desc::result_in_func, plperl_proc_desc::result_oid, plperl_proc_desc::result_typioparam, FunctionCallInfoBaseData::resultinfo, plperl_call_data::ret_tdesc, SFRM_Materialize_Random, plperl_call_data::tmp_cxt, plperl_call_data::tuple_store, tuplestore_begin_heap(), tuplestore_puttuple(), tuplestore_putvalues(), TYPEFUNC_COMPOSITE, TYPEFUNC_COMPOSITE_DOMAIN, and work_mem.

Referenced by plperl_func_handler(), and plperl_return_next().

◆ plperl_spi_commit()

void plperl_spi_commit ( void  )

Definition at line 3987 of file plperl.c.

3988 {
3989  MemoryContext oldcontext = CurrentMemoryContext;
3990 
3992 
3993  PG_TRY();
3994  {
3995  SPI_commit();
3996  }
3997  PG_CATCH();
3998  {
3999  ErrorData *edata;
4000 
4001  /* Save error info */
4002  MemoryContextSwitchTo(oldcontext);
4003  edata = CopyErrorData();
4004  FlushErrorState();
4005 
4006  /* Punt the error to Perl */
4007  croak_cstr(edata->message);
4008  }
4009  PG_END_TRY();
4010 }
void SPI_commit(void)
Definition: spi.c:320

References check_spi_usage_allowed(), CopyErrorData(), croak_cstr(), CurrentMemoryContext, FlushErrorState(), MemoryContextSwitchTo(), ErrorData::message, PG_CATCH, PG_END_TRY, PG_TRY, and SPI_commit().

◆ plperl_spi_cursor_close()

void plperl_spi_cursor_close ( char *  cursor)

Definition at line 3547 of file plperl.c.

3548 {
3549  Portal p;
3550 
3552 
3553  p = SPI_cursor_find(cursor);
3554 
3555  if (p)
3556  {
3557  UnpinPortal(p);
3558  SPI_cursor_close(p);
3559  }
3560 }
void UnpinPortal(Portal portal)
Definition: portalmem.c:380
Portal SPI_cursor_find(const char *name)
Definition: spi.c:1791
void SPI_cursor_close(Portal portal)
Definition: spi.c:1859
Definition: type.h:137

References check_spi_usage_allowed(), SPI_cursor_close(), SPI_cursor_find(), and UnpinPortal().

◆ plperl_spi_exec()

HV* plperl_spi_exec ( char *  query,
int  limit 
)

Definition at line 3129 of file plperl.c.

3130 {
3131  HV *ret_hv;
3132 
3133  /*
3134  * Execute the query inside a sub-transaction, so we can cope with errors
3135  * sanely
3136  */
3137  MemoryContext oldcontext = CurrentMemoryContext;
3139 
3141 
3143  /* Want to run inside function's memory context */
3144  MemoryContextSwitchTo(oldcontext);
3145 
3146  PG_TRY();
3147  {
3148  int spi_rv;
3149 
3150  pg_verifymbstr(query, strlen(query), false);
3151 
3153  limit);
3155  spi_rv);
3156 
3157  /* Commit the inner transaction, return to outer xact context */
3159  MemoryContextSwitchTo(oldcontext);
3160  CurrentResourceOwner = oldowner;
3161  }
3162  PG_CATCH();
3163  {
3164  ErrorData *edata;
3165 
3166  /* Save error info */
3167  MemoryContextSwitchTo(oldcontext);
3168  edata = CopyErrorData();
3169  FlushErrorState();
3170 
3171  /* Abort the inner transaction */
3173  MemoryContextSwitchTo(oldcontext);
3174  CurrentResourceOwner = oldowner;
3175 
3176  /* Punt the error to Perl */
3177  croak_cstr(edata->message);
3178 
3179  /* Can't get here, but keep compiler quiet */
3180  return NULL;
3181  }
3182  PG_END_TRY();
3183 
3184  return ret_hv;
3185 }
bool pg_verifymbstr(const char *mbstr, int len, bool noError)
Definition: mbutils.c:1556
static HV * plperl_spi_execute_fetch_result(SPITupleTable *, uint64, int)
Definition: plperl.c:3189
ResourceOwner CurrentResourceOwner
Definition: resowner.c:165
uint64 SPI_processed
Definition: spi.c:44
SPITupleTable * SPI_tuptable
Definition: spi.c:45
int SPI_execute(const char *src, bool read_only, long tcount)
Definition: spi.c:593
void BeginInternalSubTransaction(const char *name)
Definition: xact.c:4687
void RollbackAndReleaseCurrentSubTransaction(void)
Definition: xact.c:4789
void ReleaseCurrentSubTransaction(void)
Definition: xact.c:4761

References BeginInternalSubTransaction(), check_spi_usage_allowed(), CopyErrorData(), croak_cstr(), current_call_data, CurrentMemoryContext, CurrentResourceOwner, FlushErrorState(), plperl_proc_desc::fn_readonly, MemoryContextSwitchTo(), ErrorData::message, PG_CATCH, PG_END_TRY, PG_TRY, pg_verifymbstr(), plperl_spi_execute_fetch_result(), plperl_call_data::prodesc, ReleaseCurrentSubTransaction(), RollbackAndReleaseCurrentSubTransaction(), SPI_execute(), SPI_processed, and SPI_tuptable.

◆ plperl_spi_exec_prepared()

HV* plperl_spi_exec_prepared ( char *  query,
HV *  attr,
int  argc,
SV **  argv 
)

Definition at line 3711 of file plperl.c.

3712 {
3713  HV *ret_hv;
3714  SV **sv;
3715  int i,
3716  limit,
3717  spi_rv;
3718  char *nulls;
3719  Datum *argvalues;
3720  plperl_query_desc *qdesc;
3721  plperl_query_entry *hash_entry;
3722 
3723  /*
3724  * Execute the query inside a sub-transaction, so we can cope with errors
3725  * sanely
3726  */
3727  MemoryContext oldcontext = CurrentMemoryContext;
3729 
3731 
3733  /* Want to run inside function's memory context */
3734  MemoryContextSwitchTo(oldcontext);
3735 
3736  PG_TRY();
3737  {
3738  dTHX;
3739 
3740  /************************************************************
3741  * Fetch the saved plan descriptor, see if it's o.k.
3742  ************************************************************/
3743  hash_entry = hash_search(plperl_active_interp->query_hash, query,
3744  HASH_FIND, NULL);
3745  if (hash_entry == NULL)
3746  elog(ERROR, "spi_exec_prepared: Invalid prepared query passed");
3747 
3748  qdesc = hash_entry->query_data;
3749  if (qdesc == NULL)
3750  elog(ERROR, "spi_exec_prepared: plperl query_hash value vanished");
3751 
3752  if (qdesc->nargs != argc)
3753  elog(ERROR, "spi_exec_prepared: expected %d argument(s), %d passed",
3754  qdesc->nargs, argc);
3755 
3756  /************************************************************
3757  * Parse eventual attributes
3758  ************************************************************/
3759  limit = 0;
3760  if (attr != NULL)
3761  {
3762  sv = hv_fetch_string(attr, "limit");
3763  if (sv && *sv && SvIOK(*sv))
3764  limit = SvIV(*sv);
3765  }
3766  /************************************************************
3767  * Set up arguments
3768  ************************************************************/
3769  if (argc > 0)
3770  {
3771  nulls = (char *) palloc(argc);
3772  argvalues = (Datum *) palloc(argc * sizeof(Datum));
3773  }
3774  else
3775  {
3776  nulls = NULL;
3777  argvalues = NULL;
3778  }
3779 
3780  for (i = 0; i < argc; i++)
3781  {
3782  bool isnull;
3783 
3784  argvalues[i] = plperl_sv_to_datum(argv[i],
3785  qdesc->argtypes[i],
3786  -1,
3787  NULL,
3788  &qdesc->arginfuncs[i],
3789  qdesc->argtypioparams[i],
3790  &isnull);
3791  nulls[i] = isnull ? 'n' : ' ';
3792  }
3793 
3794  /************************************************************
3795  * go
3796  ************************************************************/
3797  spi_rv = SPI_execute_plan(qdesc->plan, argvalues, nulls,
3800  spi_rv);
3801  if (argc > 0)
3802  {
3803  pfree(argvalues);
3804  pfree(nulls);
3805  }
3806 
3807  /* Commit the inner transaction, return to outer xact context */
3809  MemoryContextSwitchTo(oldcontext);
3810  CurrentResourceOwner = oldowner;
3811  }
3812  PG_CATCH();
3813  {
3814  ErrorData *edata;
3815 
3816  /* Save error info */
3817  MemoryContextSwitchTo(oldcontext);
3818  edata = CopyErrorData();
3819  FlushErrorState();
3820 
3821  /* Abort the inner transaction */
3823  MemoryContextSwitchTo(oldcontext);
3824  CurrentResourceOwner = oldowner;
3825 
3826  /* Punt the error to Perl */
3827  croak_cstr(edata->message);
3828 
3829  /* Can't get here, but keep compiler quiet */
3830  return NULL;
3831  }
3832  PG_END_TRY();
3833 
3834  return ret_hv;
3835 }
int SPI_execute_plan(SPIPlanPtr plan, Datum *Values, const char *Nulls, bool read_only, long tcount)
Definition: spi.c:669
HTAB * query_hash
Definition: plperl.c:87
FmgrInfo * arginfuncs
Definition: plperl.c:193
Oid * argtypes
Definition: plperl.c:192
SPIPlanPtr plan
Definition: plperl.c:190
Oid * argtypioparams
Definition: plperl.c:194
Definition: plperl.c:200
plperl_query_desc * query_data
Definition: plperl.c:202

References plperl_query_desc::arginfuncs, plperl_query_desc::argtypes, plperl_query_desc::argtypioparams, BeginInternalSubTransaction(), check_spi_usage_allowed(), CopyErrorData(), croak_cstr(), current_call_data, CurrentMemoryContext, CurrentResourceOwner, dTHX, elog, ERROR, FlushErrorState(), plperl_proc_desc::fn_readonly, HASH_FIND, hash_search(), hv_fetch_string(), i, MemoryContextSwitchTo(), ErrorData::message, plperl_query_desc::nargs, palloc(), pfree(), PG_CATCH, PG_END_TRY, PG_TRY, plperl_query_desc::plan, plperl_active_interp, plperl_spi_execute_fetch_result(), plperl_sv_to_datum(), plperl_call_data::prodesc, plperl_query_entry::query_data, plperl_interp_desc::query_hash, ReleaseCurrentSubTransaction(), RollbackAndReleaseCurrentSubTransaction(), SPI_execute_plan(), SPI_processed, and SPI_tuptable.

◆ plperl_spi_execute_fetch_result()

static HV * plperl_spi_execute_fetch_result ( SPITupleTable tuptable,
uint64  processed,
int  status 
)
static

Definition at line 3189 of file plperl.c.

3191 {
3192  dTHX;
3193  HV *result;
3194 
3196 
3197  result = newHV();
3198 
3199  hv_store_string(result, "status",
3200  cstr2sv(SPI_result_code_string(status)));
3201  hv_store_string(result, "processed",
3202  (processed > (uint64) UV_MAX) ?
3203  newSVnv((NV) processed) :
3204  newSVuv((UV) processed));
3205 
3206  if (status > 0 && tuptable)
3207  {
3208  AV *rows;
3209  SV *row;
3210  uint64 i;
3211 
3212  /* Prevent overflow in call to av_extend() */
3213  if (processed > (uint64) AV_SIZE_MAX)
3214  ereport(ERROR,
3215  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
3216  errmsg("query result has too many rows to fit in a Perl array")));
3217 
3218  rows = newAV();
3219  av_extend(rows, processed);
3220  for (i = 0; i < processed; i++)
3221  {
3222  row = plperl_hash_from_tuple(tuptable->vals[i], tuptable->tupdesc, true);
3223  av_push(rows, row);
3224  }
3225  hv_store_string(result, "rows",
3226  newRV_noinc((SV *) rows));
3227  }
3228 
3229  SPI_freetuptable(tuptable);
3230 
3231  return result;
3232 }
#define AV_SIZE_MAX
NVTYPE NV
Definition: ppport.h:12325
#define UV_MAX
Definition: ppport.h:11685
const char * SPI_result_code_string(int code)
Definition: spi.c:1969
void SPI_freetuptable(SPITupleTable *tuptable)
Definition: spi.c:1383
TupleDesc tupdesc
Definition: spi.h:25
HeapTuple * vals
Definition: spi.h:26

References AV_SIZE_MAX, check_spi_usage_allowed(), cstr2sv(), dTHX, ereport, errcode(), errmsg(), ERROR, hv_store_string(), i, newRV_noinc, newSVuv, plperl_hash_from_tuple(), SPI_freetuptable(), SPI_result_code_string(), SPITupleTable::tupdesc, UV_MAX, and SPITupleTable::vals.

Referenced by plperl_spi_exec(), and plperl_spi_exec_prepared().

◆ plperl_spi_fetchrow()

SV* plperl_spi_fetchrow ( char *  cursor)

Definition at line 3472 of file plperl.c.

3473 {
3474  SV *row;
3475 
3476  /*
3477  * Execute the FETCH inside a sub-transaction, so we can cope with errors
3478  * sanely
3479  */
3480  MemoryContext oldcontext = CurrentMemoryContext;
3482 
3484 
3486  /* Want to run inside function's memory context */
3487  MemoryContextSwitchTo(oldcontext);
3488 
3489  PG_TRY();
3490  {
3491  dTHX;
3493 
3494  if (!p)
3495  {
3496  row = &PL_sv_undef;
3497  }
3498  else
3499  {
3500  SPI_cursor_fetch(p, true, 1);
3501  if (SPI_processed == 0)
3502  {
3503  UnpinPortal(p);
3504  SPI_cursor_close(p);
3505  row = &PL_sv_undef;
3506  }
3507  else
3508  {
3511  true);
3512  }
3514  }
3515 
3516  /* Commit the inner transaction, return to outer xact context */
3518  MemoryContextSwitchTo(oldcontext);
3519  CurrentResourceOwner = oldowner;
3520  }
3521  PG_CATCH();
3522  {
3523  ErrorData *edata;
3524 
3525  /* Save error info */
3526  MemoryContextSwitchTo(oldcontext);
3527  edata = CopyErrorData();
3528  FlushErrorState();
3529 
3530  /* Abort the inner transaction */
3532  MemoryContextSwitchTo(oldcontext);
3533  CurrentResourceOwner = oldowner;
3534 
3535  /* Punt the error to Perl */
3536  croak_cstr(edata->message);
3537 
3538  /* Can't get here, but keep compiler quiet */
3539  return NULL;
3540  }
3541  PG_END_TRY();
3542 
3543  return row;
3544 }
void SPI_cursor_fetch(Portal portal, bool forward, long count)
Definition: spi.c:1803

References BeginInternalSubTransaction(), check_spi_usage_allowed(), CopyErrorData(), croak_cstr(), CurrentMemoryContext, CurrentResourceOwner, dTHX, FlushErrorState(), MemoryContextSwitchTo(), ErrorData::message, PG_CATCH, PG_END_TRY, PG_TRY, PL_sv_undef, plperl_hash_from_tuple(), ReleaseCurrentSubTransaction(), RollbackAndReleaseCurrentSubTransaction(), SPI_cursor_close(), SPI_cursor_fetch(), SPI_cursor_find(), SPI_freetuptable(), SPI_processed, SPI_tuptable, SPITupleTable::tupdesc, UnpinPortal(), and SPITupleTable::vals.

◆ plperl_spi_freeplan()

void plperl_spi_freeplan ( char *  query)

Definition at line 3956 of file plperl.c.

3957 {
3958  SPIPlanPtr plan;
3959  plperl_query_desc *qdesc;
3960  plperl_query_entry *hash_entry;
3961 
3963 
3964  hash_entry = hash_search(plperl_active_interp->query_hash, query,
3965  HASH_FIND, NULL);
3966  if (hash_entry == NULL)
3967  elog(ERROR, "spi_freeplan: Invalid prepared query passed");
3968 
3969  qdesc = hash_entry->query_data;
3970  if (qdesc == NULL)
3971  elog(ERROR, "spi_freeplan: plperl query_hash value vanished");
3972  plan = qdesc->plan;
3973 
3974  /*
3975  * free all memory before SPI_freeplan, so if it dies, nothing will be
3976  * left over
3977  */
3979  HASH_REMOVE, NULL);
3980 
3981  MemoryContextDelete(qdesc->plan_cxt);
3982 
3983  SPI_freeplan(plan);
3984 }
@ HASH_REMOVE
Definition: hsearch.h:115
#define plan(x)
Definition: pg_regress.c:162
int SPI_freeplan(SPIPlanPtr plan)
Definition: spi.c:1022
MemoryContext plan_cxt
Definition: plperl.c:189

References check_spi_usage_allowed(), elog, ERROR, HASH_FIND, HASH_REMOVE, hash_search(), MemoryContextDelete(), plperl_query_desc::plan, plan, plperl_query_desc::plan_cxt, plperl_active_interp, plperl_query_entry::query_data, plperl_interp_desc::query_hash, and SPI_freeplan().

◆ plperl_spi_prepare()

SV* plperl_spi_prepare ( char *  query,
int  argc,
SV **  argv 
)

Definition at line 3563 of file plperl.c.

3564 {
3565  volatile SPIPlanPtr plan = NULL;
3566  volatile MemoryContext plan_cxt = NULL;
3567  plperl_query_desc *volatile qdesc = NULL;
3568  plperl_query_entry *volatile hash_entry = NULL;
3569  MemoryContext oldcontext = CurrentMemoryContext;
3571  MemoryContext work_cxt;
3572  bool found;
3573  int i;
3574 
3576 
3578  MemoryContextSwitchTo(oldcontext);
3579 
3580  PG_TRY();
3581  {
3583 
3584  /************************************************************
3585  * Allocate the new querydesc structure
3586  *
3587  * The qdesc struct, as well as all its subsidiary data, lives in its
3588  * plan_cxt. But note that the SPIPlan does not.
3589  ************************************************************/
3591  "PL/Perl spi_prepare query",
3593  MemoryContextSwitchTo(plan_cxt);
3594  qdesc = (plperl_query_desc *) palloc0(sizeof(plperl_query_desc));
3595  snprintf(qdesc->qname, sizeof(qdesc->qname), "%p", qdesc);
3596  qdesc->plan_cxt = plan_cxt;
3597  qdesc->nargs = argc;
3598  qdesc->argtypes = (Oid *) palloc(argc * sizeof(Oid));
3599  qdesc->arginfuncs = (FmgrInfo *) palloc(argc * sizeof(FmgrInfo));
3600  qdesc->argtypioparams = (Oid *) palloc(argc * sizeof(Oid));
3601  MemoryContextSwitchTo(oldcontext);
3602 
3603  /************************************************************
3604  * Do the following work in a short-lived context so that we don't
3605  * leak a lot of memory in the PL/Perl function's SPI Proc context.
3606  ************************************************************/
3608  "PL/Perl spi_prepare workspace",
3610  MemoryContextSwitchTo(work_cxt);
3611 
3612  /************************************************************
3613  * Resolve argument type names and then look them up by oid
3614  * in the system cache, and remember the required information
3615  * for input conversion.
3616  ************************************************************/
3617  for (i = 0; i < argc; i++)
3618  {
3619  Oid typId,
3620  typInput,
3621  typIOParam;
3622  int32 typmod;
3623  char *typstr;
3624 
3625  typstr = sv2cstr(argv[i]);
3626  (void) parseTypeString(typstr, &typId, &typmod, NULL);
3627  pfree(typstr);
3628 
3629  getTypeInputInfo(typId, &typInput, &typIOParam);
3630 
3631  qdesc->argtypes[i] = typId;
3632  fmgr_info_cxt(typInput, &(qdesc->arginfuncs[i]), plan_cxt);
3633  qdesc->argtypioparams[i] = typIOParam;
3634  }
3635 
3636  /* Make sure the query is validly encoded */
3637  pg_verifymbstr(query, strlen(query), false);
3638 
3639  /************************************************************
3640  * Prepare the plan and check for errors
3641  ************************************************************/
3642  plan = SPI_prepare(query, argc, qdesc->argtypes);
3643 
3644  if (plan == NULL)
3645  elog(ERROR, "SPI_prepare() failed:%s",
3647 
3648  /************************************************************
3649  * Save the plan into permanent memory (right now it's in the
3650  * SPI procCxt, which will go away at function end).
3651  ************************************************************/
3652  if (SPI_keepplan(plan))
3653  elog(ERROR, "SPI_keepplan() failed");
3654  qdesc->plan = plan;
3655 
3656  /************************************************************
3657  * Insert a hashtable entry for the plan.
3658  ************************************************************/
3660  qdesc->qname,
3661  HASH_ENTER, &found);
3662  hash_entry->query_data = qdesc;
3663 
3664  /* Get rid of workspace */
3665  MemoryContextDelete(work_cxt);
3666 
3667  /* Commit the inner transaction, return to outer xact context */
3669  MemoryContextSwitchTo(oldcontext);
3670  CurrentResourceOwner = oldowner;
3671  }
3672  PG_CATCH();
3673  {
3674  ErrorData *edata;
3675 
3676  /* Save error info */
3677  MemoryContextSwitchTo(oldcontext);
3678  edata = CopyErrorData();
3679  FlushErrorState();
3680 
3681  /* Drop anything we managed to allocate */
3682  if (hash_entry)
3684  qdesc->qname,
3685  HASH_REMOVE, NULL);
3686  if (plan_cxt)
3687  MemoryContextDelete(plan_cxt);
3688  if (plan)
3689  SPI_freeplan(plan);
3690 
3691  /* Abort the inner transaction */
3693  MemoryContextSwitchTo(oldcontext);
3694  CurrentResourceOwner = oldowner;
3695 
3696  /* Punt the error to Perl */
3697  croak_cstr(edata->message);
3698 
3699  /* Can't get here, but keep compiler quiet */
3700  return NULL;
3701  }
3702  PG_END_TRY();
3703 
3704  /************************************************************
3705  * Return the query's hash key to the caller.
3706  ************************************************************/
3707  return cstr2sv(qdesc->qname);
3708 }
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:122
bool parseTypeString(const char *str, Oid *typeid_p, int32 *typmod_p, Node *escontext)
Definition: parse_type.c:785
#define snprintf
Definition: port.h:238
int SPI_result
Definition: spi.c:46
SPIPlanPtr SPI_prepare(const char *src, int nargs, Oid *argtypes)
Definition: spi.c:857
int SPI_keepplan(SPIPlanPtr plan)
Definition: spi.c:973
char qname[24]
Definition: plperl.c:188

References ALLOCSET_DEFAULT_SIZES, ALLOCSET_SMALL_SIZES, AllocSetContextCreate, plperl_query_desc::arginfuncs, plperl_query_desc::argtypes, plperl_query_desc::argtypioparams, BeginInternalSubTransaction(), CHECK_FOR_INTERRUPTS, check_spi_usage_allowed(), CopyErrorData(), croak_cstr(), cstr2sv(), CurrentMemoryContext, CurrentResourceOwner, elog, ERROR, FlushErrorState(), fmgr_info_cxt(), getTypeInputInfo(), HASH_ENTER, HASH_REMOVE, hash_search(), i, MemoryContextDelete(), MemoryContextSwitchTo(), ErrorData::message, plperl_query_desc::nargs, palloc(), palloc0(), parseTypeString(), pfree(), PG_CATCH, PG_END_TRY, PG_TRY, pg_verifymbstr(), plperl_query_desc::plan, plan, plperl_query_desc::plan_cxt, plperl_active_interp, plperl_query_desc::qname, plperl_query_entry::query_data, plperl_interp_desc::query_hash, ReleaseCurrentSubTransaction(), RollbackAndReleaseCurrentSubTransaction(), snprintf, SPI_freeplan(), SPI_keepplan(), SPI_prepare(), SPI_result, SPI_result_code_string(), sv2cstr(), and TopMemoryContext.

◆ plperl_spi_query()

SV* plperl_spi_query ( char *  query)

Definition at line 3400 of file plperl.c.

3401 {
3402  SV *cursor;
3403 
3404  /*
3405  * Execute the query inside a sub-transaction, so we can cope with errors
3406  * sanely
3407  */
3408  MemoryContext oldcontext = CurrentMemoryContext;
3410 
3412 
3414  /* Want to run inside function's memory context */
3415  MemoryContextSwitchTo(oldcontext);
3416 
3417  PG_TRY();
3418  {
3419  SPIPlanPtr plan;
3420  Portal portal;
3421 
3422  /* Make sure the query is validly encoded */
3423  pg_verifymbstr(query, strlen(query), false);
3424 
3425  /* Create a cursor for the query */
3426  plan = SPI_prepare(query, 0, NULL);
3427  if (plan == NULL)
3428  elog(ERROR, "SPI_prepare() failed:%s",
3430 
3431  portal = SPI_cursor_open(NULL, plan, NULL, NULL, false);
3432  SPI_freeplan(plan);
3433  if (portal == NULL)
3434  elog(ERROR, "SPI_cursor_open() failed:%s",
3436  cursor = cstr2sv(portal->name);
3437 
3438  PinPortal(portal);
3439 
3440  /* Commit the inner transaction, return to outer xact context */
3442  MemoryContextSwitchTo(oldcontext);
3443  CurrentResourceOwner = oldowner;
3444  }
3445  PG_CATCH();
3446  {
3447  ErrorData *edata;
3448 
3449  /* Save error info */
3450  MemoryContextSwitchTo(oldcontext);
3451  edata = CopyErrorData();
3452  FlushErrorState();
3453 
3454  /* Abort the inner transaction */
3456  MemoryContextSwitchTo(oldcontext);
3457  CurrentResourceOwner = oldowner;
3458 
3459  /* Punt the error to Perl */
3460  croak_cstr(edata->message);
3461 
3462  /* Can't get here, but keep compiler quiet */
3463  return NULL;
3464  }
3465  PG_END_TRY();
3466 
3467  return cursor;
3468 }
void PinPortal(Portal portal)
Definition: portalmem.c:371
Portal SPI_cursor_open(const char *name, SPIPlanPtr plan, Datum *Values, const char *Nulls, bool read_only)
Definition: spi.c:1442
const char * name
Definition: portal.h:118

References BeginInternalSubTransaction(), check_spi_usage_allowed(), CopyErrorData(), croak_cstr(), cstr2sv(), CurrentMemoryContext, CurrentResourceOwner, elog, ERROR, FlushErrorState(), MemoryContextSwitchTo(), ErrorData::message, PortalData::name, PG_CATCH, PG_END_TRY, PG_TRY, pg_verifymbstr(), PinPortal(), plan, ReleaseCurrentSubTransaction(), RollbackAndReleaseCurrentSubTransaction(), SPI_cursor_open(), SPI_freeplan(), SPI_prepare(), SPI_result, and SPI_result_code_string().

◆ plperl_spi_query_prepared()

SV* plperl_spi_query_prepared ( char *  query,
int  argc,
SV **  argv 
)

Definition at line 3838 of file plperl.c.

3839 {
3840  int i;
3841  char *nulls;
3842  Datum *argvalues;
3843  plperl_query_desc *qdesc;
3844  plperl_query_entry *hash_entry;
3845  SV *cursor;
3846  Portal portal = NULL;
3847 
3848  /*
3849  * Execute the query inside a sub-transaction, so we can cope with errors
3850  * sanely
3851  */
3852  MemoryContext oldcontext = CurrentMemoryContext;
3854 
3856 
3858  /* Want to run inside function's memory context */
3859  MemoryContextSwitchTo(oldcontext);
3860 
3861  PG_TRY();
3862  {
3863  /************************************************************
3864  * Fetch the saved plan descriptor, see if it's o.k.
3865  ************************************************************/
3866  hash_entry = hash_search(plperl_active_interp->query_hash, query,
3867  HASH_FIND, NULL);
3868  if (hash_entry == NULL)
3869  elog(ERROR, "spi_query_prepared: Invalid prepared query passed");
3870 
3871  qdesc = hash_entry->query_data;
3872  if (qdesc == NULL)
3873  elog(ERROR, "spi_query_prepared: plperl query_hash value vanished");
3874 
3875  if (qdesc->nargs != argc)
3876  elog(ERROR, "spi_query_prepared: expected %d argument(s), %d passed",
3877  qdesc->nargs, argc);
3878 
3879  /************************************************************
3880  * Set up arguments
3881  ************************************************************/
3882  if (argc > 0)
3883  {
3884  nulls = (char *) palloc(argc);
3885  argvalues = (Datum *) palloc(argc * sizeof(Datum));
3886  }
3887  else
3888  {
3889  nulls = NULL;
3890  argvalues = NULL;
3891  }
3892 
3893  for (i = 0; i < argc; i++)
3894  {
3895  bool isnull;
3896 
3897  argvalues[i] = plperl_sv_to_datum(argv[i],
3898  qdesc->argtypes[i],
3899  -1,
3900  NULL,
3901  &qdesc->arginfuncs[i],
3902  qdesc->argtypioparams[i],
3903  &isnull);
3904  nulls[i] = isnull ? 'n' : ' ';
3905  }
3906 
3907  /************************************************************
3908  * go
3909  ************************************************************/
3910  portal = SPI_cursor_open(NULL, qdesc->plan, argvalues, nulls,
3912  if (argc > 0)
3913  {
3914  pfree(argvalues);
3915  pfree(nulls);
3916  }
3917  if (portal == NULL)
3918  elog(ERROR, "SPI_cursor_open() failed:%s",
3920 
3921  cursor = cstr2sv(portal->name);
3922 
3923  PinPortal(portal);
3924 
3925  /* Commit the inner transaction, return to outer xact context */
3927  MemoryContextSwitchTo(oldcontext);
3928  CurrentResourceOwner = oldowner;
3929  }
3930  PG_CATCH();
3931  {
3932  ErrorData *edata;
3933 
3934  /* Save error info */
3935  MemoryContextSwitchTo(oldcontext);
3936  edata = CopyErrorData();
3937  FlushErrorState();
3938 
3939  /* Abort the inner transaction */
3941  MemoryContextSwitchTo(oldcontext);
3942  CurrentResourceOwner = oldowner;
3943 
3944  /* Punt the error to Perl */
3945  croak_cstr(edata->message);
3946 
3947  /* Can't get here, but keep compiler quiet */
3948  return NULL;
3949  }
3950  PG_END_TRY();
3951 
3952  return cursor;
3953 }

References plperl_query_desc::arginfuncs, plperl_query_desc::argtypes, plperl_query_desc::argtypioparams, BeginInternalSubTransaction(), check_spi_usage_allowed(), CopyErrorData(), croak_cstr(), cstr2sv(), current_call_data, CurrentMemoryContext, CurrentResourceOwner, elog, ERROR, FlushErrorState(), plperl_proc_desc::fn_readonly, HASH_FIND, hash_search(), i, MemoryContextSwitchTo(), ErrorData::message, PortalData::name, plperl_query_desc::nargs, palloc(), pfree(), PG_CATCH, PG_END_TRY, PG_TRY, PinPortal(), plperl_query_desc::plan, plperl_active_interp, plperl_sv_to_datum(), plperl_call_data::prodesc, plperl_query_entry::query_data, plperl_interp_desc::query_hash, ReleaseCurrentSubTransaction(), RollbackAndReleaseCurrentSubTransaction(), SPI_cursor_open(), SPI_result, and SPI_result_code_string().

◆ plperl_spi_rollback()

void plperl_spi_rollback ( void  )

Definition at line 4013 of file plperl.c.

4014 {
4015  MemoryContext oldcontext = CurrentMemoryContext;
4016 
4018 
4019  PG_TRY();
4020  {
4021  SPI_rollback();
4022  }
4023  PG_CATCH();
4024  {
4025  ErrorData *edata;
4026 
4027  /* Save error info */
4028  MemoryContextSwitchTo(oldcontext);
4029  edata = CopyErrorData();
4030  FlushErrorState();
4031 
4032  /* Punt the error to Perl */
4033  croak_cstr(edata->message);
4034  }
4035  PG_END_TRY();
4036 }
void SPI_rollback(void)
Definition: spi.c:413

References check_spi_usage_allowed(), CopyErrorData(), croak_cstr(), CurrentMemoryContext, FlushErrorState(), MemoryContextSwitchTo(), ErrorData::message, PG_CATCH, PG_END_TRY, PG_TRY, and SPI_rollback().

◆ plperl_sv_to_datum()

static Datum plperl_sv_to_datum ( SV *  sv,
Oid  typid,
int32  typmod,
FunctionCallInfo  fcinfo,
FmgrInfo finfo,
Oid  typioparam,
bool isnull 
)
static

Definition at line 1323 of file plperl.c.

1327 {
1328  FmgrInfo tmp;
1329  Oid funcid;
1330 
1331  /* we might recurse */
1333 
1334  *isnull = false;
1335 
1336  /*
1337  * Return NULL if result is undef, or if we're in a function returning
1338  * VOID. In the latter case, we should pay no attention to the last Perl
1339  * statement's result, and this is a convenient means to ensure that.
1340  */
1341  if (!sv || !SvOK(sv) || typid == VOIDOID)
1342  {
1343  /* look up type info if they did not pass it */
1344  if (!finfo)
1345  {
1346  _sv_to_datum_finfo(typid, &tmp, &typioparam);
1347  finfo = &tmp;
1348  }
1349  *isnull = true;
1350  /* must call typinput in case it wants to reject NULL */
1351  return InputFunctionCall(finfo, NULL, typioparam, typmod);
1352  }
1354  return OidFunctionCall1(funcid, PointerGetDatum(sv));
1355  else if (SvROK(sv))
1356  {
1357  /* handle references */
1358  SV *sav = get_perl_array_ref(sv);
1359 
1360  if (sav)
1361  {
1362  /* handle an arrayref */
1363  return plperl_array_to_datum(sav, typid, typmod);
1364  }
1365  else if (SvTYPE(SvRV(sv)) == SVt_PVHV)
1366  {
1367  /* handle a hashref */
1368  Datum ret;
1369  TupleDesc td;
1370  bool isdomain;
1371 
1372  if (!type_is_rowtype(typid))
1373  ereport(ERROR,
1374  (errcode(ERRCODE_DATATYPE_MISMATCH),
1375  errmsg("cannot convert Perl hash to non-composite type %s",
1376  format_type_be(typid))));
1377 
1378  td = lookup_rowtype_tupdesc_domain(typid, typmod, true);
1379  if (td != NULL)
1380  {
1381  /* Did we look through a domain? */
1382  isdomain = (typid != td->tdtypeid);
1383  }
1384  else
1385  {
1386  /* Must be RECORD, try to resolve based on call info */
1387  TypeFuncClass funcclass;
1388 
1389  if (fcinfo)
1390  funcclass = get_call_result_type(fcinfo, &typid, &td);
1391  else
1392  funcclass = TYPEFUNC_OTHER;
1393  if (funcclass != TYPEFUNC_COMPOSITE &&
1394  funcclass != TYPEFUNC_COMPOSITE_DOMAIN)
1395  ereport(ERROR,
1396  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1397  errmsg("function returning record called in context "
1398  "that cannot accept type record")));
1399  Assert(td);
1400  isdomain = (funcclass == TYPEFUNC_COMPOSITE_DOMAIN);
1401  }
1402 
1403  ret = plperl_hash_to_datum(sv, td);
1404 
1405  if (isdomain)
1406  domain_check(ret, false, typid, NULL, NULL);
1407 
1408  /* Release on the result of get_call_result_type is harmless */
1409  ReleaseTupleDesc(td);
1410 
1411  return ret;
1412  }
1413 
1414  /*
1415  * If it's a reference to something else, such as a scalar, just
1416  * recursively look through the reference.
1417  */
1418  return plperl_sv_to_datum(SvRV(sv), typid, typmod,
1419  fcinfo, finfo, typioparam,
1420  isnull);
1421  }
1422  else
1423  {
1424  /* handle a string/number */
1425  Datum ret;
1426  char *str = sv2cstr(sv);
1427 
1428  /* did not pass in any typeinfo? look it up */
1429  if (!finfo)
1430  {
1431  _sv_to_datum_finfo(typid, &tmp, &typioparam);
1432  finfo = &tmp;
1433  }
1434 
1435  ret = InputFunctionCall(finfo, str, typioparam, typmod);
1436  pfree(str);
1437 
1438  return ret;
1439  }
1440 }
Datum InputFunctionCall(FmgrInfo *flinfo, char *str, Oid typioparam, int32 typmod)
Definition: fmgr.c:1530
@ TYPEFUNC_OTHER
Definition: funcapi.h:152
const char * str
Oid get_transform_tosql(Oid typid, Oid langid, List *trftypes)
Definition: lsyscache.c:2142
static Datum plperl_array_to_datum(SV *src, Oid typid, int32 typmod)
Definition: plperl.c:1257
static Datum plperl_hash_to_datum(SV *src, TupleDesc td)
Definition: plperl.c:1126
Oid tdtypeid
Definition: tupdesc.h:82
TupleDesc lookup_rowtype_tupdesc_domain(Oid type_id, int32 typmod, bool noError)
Definition: typcache.c:1906

References _sv_to_datum_finfo(), Assert, check_stack_depth(), current_call_data, domain_check(), ereport, errcode(), errmsg(), ERROR, format_type_be(), get_call_result_type(), get_perl_array_ref(), get_transform_tosql(), InputFunctionCall(), plperl_proc_desc::lang_oid, lookup_rowtype_tupdesc_domain(), OidFunctionCall1, pfree(), plperl_array_to_datum(), plperl_hash_to_datum(), PointerGetDatum(), plperl_call_data::prodesc, ReleaseTupleDesc, str, sv2cstr(), TupleDescData::tdtypeid, plperl_proc_desc::trftypes, type_is_rowtype(), TYPEFUNC_COMPOSITE, TYPEFUNC_COMPOSITE_DOMAIN, and TYPEFUNC_OTHER.

Referenced by array_to_datum_internal(), plperl_build_tuple_result(), plperl_func_handler(), plperl_modify_tuple(), plperl_return_next_internal(), plperl_spi_exec_prepared(), plperl_spi_query_prepared(), and plperl_sv_to_literal().

◆ plperl_sv_to_literal()

char* plperl_sv_to_literal ( SV *  sv,
char *  fqtypename 
)

Definition at line 1444 of file plperl.c.

1445 {
1446  Oid typid;
1447  Oid typoutput;
1448  Datum datum;
1449  bool typisvarlena,
1450  isnull;
1451 
1453 
1454  typid = DirectFunctionCall1(regtypein, CStringGetDatum(fqtypename));
1455  if (!OidIsValid(typid))
1456  ereport(ERROR,
1457  (errcode(ERRCODE_UNDEFINED_OBJECT),
1458  errmsg("lookup failed for type %s", fqtypename)));
1459 
1460  datum = plperl_sv_to_datum(sv,
1461  typid, -1,
1462  NULL, NULL, InvalidOid,
1463  &isnull);
1464 
1465  if (isnull)
1466  return NULL;
1467 
1468  getTypeOutputInfo(typid,
1469  &typoutput, &typisvarlena);
1470 
1471  return OidOutputFunctionCall(typoutput, datum);
1472 }
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:641
static Datum CStringGetDatum(const char *X)
Definition: postgres.h:350
Datum regtypein(PG_FUNCTION_ARGS)
Definition: regproc.c:1176

References check_spi_usage_allowed(), CStringGetDatum(), DirectFunctionCall1, ereport, errcode(), errmsg(), ERROR, getTypeOutputInfo(), InvalidOid, OidIsValid, OidOutputFunctionCall(), plperl_sv_to_datum(), and regtypein().

◆ plperl_trigger_build_args()

static SV* plperl_trigger_build_args ( FunctionCallInfo  fcinfo)
static

Definition at line 1631 of file plperl.c.

1632 {
1633  dTHX;
1634  TriggerData *tdata;
1635  TupleDesc tupdesc;
1636  int i;
1637  char *level;
1638  char *event;
1639  char *relid;
1640  char *when;
1641  HV *hv;
1642 
1643  hv = newHV();
1644  hv_ksplit(hv, 12); /* pre-grow the hash */
1645 
1646  tdata = (TriggerData *) fcinfo->context;
1647  tupdesc = tdata->tg_relation->rd_att;
1648 
1650  ObjectIdGetDatum(tdata->tg_relation->rd_id)));
1651 
1652  hv_store_string(hv, "name", cstr2sv(tdata->tg_trigger->tgname));
1653  hv_store_string(hv, "relid", cstr2sv(relid));
1654 
1655  /*
1656  * Note: In BEFORE trigger, stored generated columns are not computed yet,
1657  * so don't make them accessible in NEW row.
1658  */
1659 
1660  if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
1661  {
1662  event = "INSERT";
1663  if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
1664  hv_store_string(hv, "new",
1666  tupdesc,
1667  !TRIGGER_FIRED_BEFORE(tdata->tg_event)));
1668  }
1669  else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
1670  {
1671  event = "DELETE";
1672  if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
1673  hv_store_string(hv, "old",
1675  tupdesc,
1676  true));
1677  }
1678  else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
1679  {
1680  event = "UPDATE";
1681  if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
1682  {
1683  hv_store_string(hv, "old",
1685  tupdesc,
1686  true));
1687  hv_store_string(hv, "new",
1689  tupdesc,
1690  !TRIGGER_FIRED_BEFORE(tdata->tg_event)));
1691  }
1692  }
1693  else if (TRIGGER_FIRED_BY_TRUNCATE(tdata->tg_event))
1694  event = "TRUNCATE";
1695  else
1696  event = "UNKNOWN";
1697 
1698  hv_store_string(hv, "event", cstr2sv(event));
1699  hv_store_string(hv, "argc", newSViv(tdata->tg_trigger->tgnargs));
1700 
1701  if (tdata->tg_trigger->tgnargs > 0)
1702  {
1703  AV *av = newAV();
1704 
1705  av_extend(av, tdata->tg_trigger->tgnargs);
1706  for (i = 0; i < tdata->tg_trigger->tgnargs; i++)
1707  av_push(av, cstr2sv(tdata->tg_trigger->tgargs[i]));
1708  hv_store_string(hv, "args", newRV_noinc((SV *) av));
1709  }
1710 
1711  hv_store_string(hv, "relname",
1713 
1714  hv_store_string(hv, "table_name",
1716 
1717  hv_store_string(hv, "table_schema",
1719 
1720  if (TRIGGER_FIRED_BEFORE(tdata->tg_event))
1721  when = "BEFORE";
1722  else if (TRIGGER_FIRED_AFTER(tdata->tg_event))
1723  when = "AFTER";
1724  else if (TRIGGER_FIRED_INSTEAD(tdata->tg_event))
1725  when = "INSTEAD OF";
1726  else
1727  when = "UNKNOWN";
1728  hv_store_string(hv, "when", cstr2sv(when));
1729 
1730  if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
1731  level = "ROW";
1732  else if (TRIGGER_FIRED_FOR_STATEMENT(tdata->tg_event))
1733  level = "STATEMENT";
1734  else
1735  level = "UNKNOWN";
1736  hv_store_string(hv, "level", cstr2sv(level));
1737 
1738  return newRV_noinc((SV *) hv);
1739 }
Datum oidout(PG_FUNCTION_ARGS)
Definition: oid.c:47
static char * DatumGetCString(Datum X)
Definition: postgres.h:335
char * SPI_getrelname(Relation rel)
Definition: spi.c:1323
char * SPI_getnspname(Relation rel)
Definition: spi.c:1329
Oid rd_id
Definition: rel.h:113
TriggerEvent tg_event
Definition: trigger.h:34
HeapTuple tg_newtuple
Definition: trigger.h:37
Trigger * tg_trigger
Definition: trigger.h:38
HeapTuple tg_trigtuple
Definition: trigger.h:36
char * tgname
Definition: reltrigger.h:27
Definition: type.h:88
#define TRIGGER_FIRED_FOR_STATEMENT(event)
Definition: trigger.h:125
#define TRIGGER_FIRED_BY_DELETE(event)
Definition: trigger.h:113
#define TRIGGER_FIRED_BEFORE(event)
Definition: trigger.h:128
#define TRIGGER_FIRED_FOR_ROW(event)
Definition: trigger.h:122
#define TRIGGER_FIRED_AFTER(event)
Definition: trigger.h:131
#define TRIGGER_FIRED_BY_TRUNCATE(event)
Definition: trigger.h:119
#define TRIGGER_FIRED_BY_INSERT(event)
Definition: trigger.h:110
#define TRIGGER_FIRED_BY_UPDATE(event)
Definition: trigger.h:116
#define TRIGGER_FIRED_INSTEAD(event)
Definition: trigger.h:134

References av, FunctionCallInfoBaseData::context, cstr2sv(), DatumGetCString(), DirectFunctionCall1, dTHX, hv_store_string(), i, newRV_noinc, ObjectIdGetDatum(), oidout(), plperl_hash_from_tuple(), RelationData::rd_att, RelationData::rd_id, SPI_getnspname(), SPI_getrelname(), TriggerData::tg_event, TriggerData::tg_newtuple, TriggerData::tg_relation, TriggerData::tg_trigger, TriggerData::tg_trigtuple, Trigger::tgargs, Trigger::tgname, Trigger::tgnargs, TRIGGER_FIRED_AFTER, TRIGGER_FIRED_BEFORE, TRIGGER_FIRED_BY_DELETE, TRIGGER_FIRED_BY_INSERT, TRIGGER_FIRED_BY_TRUNCATE, TRIGGER_FIRED_BY_UPDATE, TRIGGER_FIRED_FOR_ROW, TRIGGER_FIRED_FOR_STATEMENT, and TRIGGER_FIRED_INSTEAD.

Referenced by plperl_trigger_handler().

◆ plperl_trigger_handler()

static Datum plperl_trigger_handler ( PG_FUNCTION_ARGS  )
static

Definition at line 2519 of file plperl.c.

2520 {
2521  plperl_proc_desc *prodesc;
2522  SV *perlret;
2523  Datum retval;
2524  SV *svTD;
2525  HV *hvTD;
2526  ErrorContextCallback pl_error_context;
2527  TriggerData *tdata;
2528  int rc PG_USED_FOR_ASSERTS_ONLY;
2529 
2530  /* Connect to SPI manager */
2531  SPI_connect();
2532 
2533  /* Make transition tables visible to this SPI connection */
2534  tdata = (TriggerData *) fcinfo->context;
2535  rc = SPI_register_trigger_data(tdata);
2536  Assert(rc >= 0);
2537 
2538  /* Find or compile the function */
2539  prodesc = compile_plperl_function(fcinfo->flinfo->fn_oid, true, false);
2540  current_call_data->prodesc = prodesc;
2541  increment_prodesc_refcount(prodesc);
2542 
2543  /* Set a callback for error reporting */
2544  pl_error_context.callback = plperl_exec_callback;
2545  pl_error_context.previous = error_context_stack;
2546  pl_error_context.arg = prodesc->proname;
2547  error_context_stack = &pl_error_context;
2548 
2549  activate_interpreter(prodesc->interp);
2550 
2551  svTD = plperl_trigger_build_args(fcinfo);
2552  perlret = plperl_call_perl_trigger_func(prodesc, fcinfo, svTD);
2553  hvTD = (HV *) SvRV(svTD);
2554 
2555  /************************************************************
2556  * Disconnect from SPI manager and then create the return
2557  * values datum (if the input function does a palloc for it
2558  * this must not be allocated in the SPI memory context
2559  * because SPI_finish would free it).
2560  ************************************************************/
2561  if (SPI_finish() != SPI_OK_FINISH)
2562  elog(ERROR, "SPI_finish() failed");
2563 
2564  if (perlret == NULL || !SvOK(perlret))
2565  {
2566  /* undef result means go ahead with original tuple */
2567  TriggerData *trigdata = ((TriggerData *) fcinfo->context);
2568 
2569  if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
2570  retval = (Datum) trigdata->tg_trigtuple;
2571  else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
2572  retval = (Datum) trigdata->tg_newtuple;
2573  else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
2574  retval = (Datum) trigdata->tg_trigtuple;
2575  else if (TRIGGER_FIRED_BY_TRUNCATE(trigdata->tg_event))
2576  retval = (Datum) trigdata->tg_trigtuple;
2577  else
2578  retval = (Datum) 0; /* can this happen? */
2579  }
2580  else
2581  {
2582  HeapTuple trv;
2583  char *tmp;
2584 
2585  tmp = sv2cstr(perlret);
2586 
2587  if (pg_strcasecmp(tmp, "SKIP") == 0)
2588  trv = NULL;
2589  else if (pg_strcasecmp(tmp, "MODIFY") == 0)
2590  {
2591  TriggerData *trigdata = (TriggerData *) fcinfo->context;
2592 
2593  if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
2594  trv = plperl_modify_tuple(hvTD, trigdata,
2595  trigdata->tg_trigtuple);
2596  else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
2597  trv = plperl_modify_tuple(hvTD, trigdata,
2598  trigdata->tg_newtuple);
2599  else
2600  {
2601  ereport(WARNING,
2602  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2603  errmsg("ignoring modified row in DELETE trigger")));
2604  trv = NULL;
2605  }
2606  }
2607  else
2608  {
2609  ereport(ERROR,
2610  (errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
2611  errmsg("result of PL/Perl trigger function must be undef, "
2612  "\"SKIP\", or \"MODIFY\"")));
2613  trv = NULL;
2614  }
2615  retval = PointerGetDatum(trv);
2616  pfree(tmp);
2617  }
2618 
2619  /* Restore the previous error callback */
2620  error_context_stack = pl_error_context.previous;
2621 
2622  SvREFCNT_dec_current(svTD);
2623  if (perlret)
2624  SvREFCNT_dec_current(perlret);
2625 
2626  return retval;
2627 }
#define PG_USED_FOR_ASSERTS_ONLY
Definition: c.h:182
#define WARNING
Definition: elog.h:36
static SV * plperl_trigger_build_args(FunctionCallInfo fcinfo)
Definition: plperl.c:1631
static SV * plperl_call_perl_trigger_func(plperl_proc_desc *desc, FunctionCallInfo fcinfo, SV *td)
Definition: plperl.c:2272
static HeapTuple plperl_modify_tuple(HV *hvTD, TriggerData *tdata, HeapTuple otup)
Definition: plperl.c:1762
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
int SPI_register_trigger_data(TriggerData *tdata)
Definition: spi.c:3358

References activate_interpreter(), ErrorContextCallback::arg, Assert, ErrorContextCallback::callback, compile_plperl_function(), current_call_data, elog, ereport, errcode(), errmsg(), ERROR, error_context_stack, if(), increment_prodesc_refcount, plperl_proc_desc::interp, pfree(), pg_strcasecmp(), PG_USED_FOR_ASSERTS_ONLY, plperl_call_perl_trigger_func(), plperl_exec_callback(), plperl_modify_tuple(), plperl_trigger_build_args(), PointerGetDatum(), ErrorContextCallback::previous, plperl_call_data::prodesc, plperl_proc_desc::proname, SPI_connect(), SPI_finish(), SPI_OK_FINISH, SPI_register_trigger_data(), sv2cstr(), SvREFCNT_dec_current(), TriggerData::tg_event, TriggerData::tg_newtuple, TriggerData::tg_trigtuple, TRIGGER_FIRED_BY_DELETE, TRIGGER_FIRED_BY_INSERT, TRIGGER_FIRED_BY_TRUNCATE, TRIGGER_FIRED_BY_UPDATE, and WARNING.

Referenced by plperl_call_handler().

◆ plperl_trusted_init()

static void plperl_trusted_init ( void  )
static

Definition at line 957 of file plperl.c.

958 {
959  dTHX;
960  HV *stash;
961  SV *sv;
962  char *key;
963  I32 klen;
964 
965  /* use original require while we set up */
966  PL_ppaddr[OP_REQUIRE] = pp_require_orig;
967  PL_ppaddr[OP_DOFILE] = pp_require_orig;
968 
969  eval_pv(PLC_TRUSTED, FALSE);
970  if (SvTRUE(ERRSV))
971  ereport(ERROR,
972  (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
974  errcontext("while executing PLC_TRUSTED")));
975 
976  /*
977  * Force loading of utf8 module now to prevent errors that can arise from
978  * the regex code later trying to load utf8 modules. See
979  * http://rt.perl.org/rt3/Ticket/Display.html?id=47576
980  */
981  eval_pv("my $a=chr(0x100); return $a =~ /\\xa9/i", FALSE);
982  if (SvTRUE(ERRSV))
983  ereport(ERROR,
984  (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
986  errcontext("while executing utf8fix")));
987 
988  /*
989  * Lock down the interpreter
990  */
991 
992  /* switch to the safe require/dofile opcode for future code */
993  PL_ppaddr[OP_REQUIRE] = pp_require_safe;
994  PL_ppaddr[OP_DOFILE] = pp_require_safe;
995 
996  /*
997  * prevent (any more) unsafe opcodes being compiled PL_op_mask is per
998  * interpreter, so this only needs to be set once
999  */
1000  PL_op_mask = plperl_opmask;
1001 
1002  /* delete the DynaLoader:: namespace so extensions can't be loaded */
1003  stash = gv_stashpv("DynaLoader", GV_ADDWARN);
1004  hv_iterinit(stash);
1005  while ((sv = hv_iternextsv(stash, &key, &klen)))
1006  {
1007  if (!isGV_with_GP(sv) || !GvCV(sv))
1008  continue;
1009  SvREFCNT_dec(GvCV(sv)); /* free the CV */
1010  GvCV_set(sv, NULL); /* prevent call via GV */
1011  }
1012  hv_clear(stash);
1013 
1014  /* invalidate assorted caches */
1015  ++PL_sub_generation;
1016  hv_clear(PL_stashcache);
1017 
1018  /*
1019  * Execute plperl.on_plperl_init in the locked-down interpreter
1020  */
1022  {
1023  eval_pv(plperl_on_plperl_init, FALSE);
1024  /* XXX need to find a way to determine a better errcode here */
1025  if (SvTRUE(ERRSV))
1026  ereport(ERROR,
1027  (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
1029  errcontext("while executing plperl.on_plperl_init")));
1030  }
1031 }
static OP * pp_require_safe(pTHX)
Definition: plperl.c:880
#define GvCV_set(gv, cv)
#define isGV_with_GP(gv)
Definition: ppport.h:15703

References dTHX, ereport, errcode(), errcontext, errmsg(), ERROR, ERRSV, GvCV_set, isGV_with_GP, sort-test::key, PL_ppaddr, plperl_on_plperl_init, plperl_opmask, pp_require_orig, pp_require_safe(), strip_trailing_ws(), and sv2cstr().

Referenced by select_perl_context().

◆ plperl_untrusted_init()

static void plperl_untrusted_init ( void  )
static

Definition at line 1038 of file plperl.c.

1039 {
1040  dTHX;
1041 
1042  /*
1043  * Nothing to do except execute plperl.on_plperlu_init
1044  */
1046  {
1047  eval_pv(plperl_on_plperlu_init, FALSE);
1048  if (SvTRUE(ERRSV))
1049  ereport(ERROR,
1050  (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
1052  errcontext("while executing plperl.on_plperlu_init")));
1053  }
1054 }

References dTHX, ereport, errcode(), errcontext, errmsg(), ERROR, ERRSV, plperl_on_plperlu_init, strip_trailing_ws(), and sv2cstr().

Referenced by select_perl_context().

◆ plperl_util_elog()

void plperl_util_elog ( int  level,
SV *  msg 
)

Definition at line 4050 of file plperl.c.

4051 {
4052  MemoryContext oldcontext = CurrentMemoryContext;
4053  char *volatile cmsg = NULL;
4054 
4055  /*
4056  * We intentionally omit check_spi_usage_allowed() here, as this seems
4057  * safe to allow even in the contexts that that function rejects.
4058  */
4059 
4060  PG_TRY();
4061  {
4062  cmsg = sv2cstr(msg);
4063  elog(level, "%s", cmsg);
4064  pfree(cmsg);
4065  }
4066  PG_CATCH();
4067  {
4068  ErrorData *edata;
4069 
4070  /* Must reset elog.c's state */
4071  MemoryContextSwitchTo(oldcontext);
4072  edata = CopyErrorData();
4073  FlushErrorState();
4074 
4075  if (cmsg)
4076  pfree(cmsg);
4077 
4078  /* Punt the error to Perl */
4079  croak_cstr(edata->message);
4080  }
4081  PG_END_TRY();
4082 }

References CopyErrorData(), croak_cstr(), CurrentMemoryContext, elog, FlushErrorState(), MemoryContextSwitchTo(), ErrorData::message, pfree(), PG_CATCH, PG_END_TRY, PG_TRY, and sv2cstr().

◆ plperl_validator()

Datum plperl_validator ( PG_FUNCTION_ARGS  )

Definition at line 1988 of file plperl.c.

1989 {
1990  Oid funcoid = PG_GETARG_OID(0);
1991  HeapTuple tuple;
1992  Form_pg_proc proc;
1993  char functyptype;
1994  int numargs;
1995  Oid *argtypes;
1996  char **argnames;
1997  char *argmodes;
1998  bool is_trigger = false;
1999  bool is_event_trigger = false;
2000  int i;
2001 
2002  if (!CheckFunctionValidatorAccess(fcinfo->flinfo->fn_oid, funcoid))
2003  PG_RETURN_VOID();
2004 
2005  /* Get the new function's pg_proc entry */
2006  tuple = SearchSysCache1(PROCOID, ObjectIdGetDatum(funcoid));
2007  if (!HeapTupleIsValid(tuple))
2008  elog(ERROR, "cache lookup failed for function %u", funcoid);
2009  proc = (Form_pg_proc) GETSTRUCT(tuple);
2010 
2011  functyptype = get_typtype(proc->prorettype);
2012 
2013  /* Disallow pseudotype result */
2014  /* except for TRIGGER, EVTTRIGGER, RECORD, or VOID */
2015  if (functyptype == TYPTYPE_PSEUDO)
2016  {
2017  if (proc->prorettype == TRIGGEROID)
2018  is_trigger = true;
2019  else if (proc->prorettype == EVENT_TRIGGEROID)
2020  is_event_trigger = true;
2021  else if (proc->prorettype != RECORDOID &&
2022  proc->prorettype != VOIDOID)
2023  ereport(ERROR,
2024  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2025  errmsg("PL/Perl functions cannot return type %s",
2026  format_type_be(proc->prorettype))));
2027  }
2028 
2029  /* Disallow pseudotypes in arguments (either IN or OUT) */
2030  numargs = get_func_arg_info(tuple,
2031  &argtypes, &argnames, &argmodes);
2032  for (i = 0; i < numargs; i++)
2033  {
2034  if (get_typtype(argtypes[i]) == TYPTYPE_PSEUDO &&
2035  argtypes[i] != RECORDOID)
2036  ereport(ERROR,
2037  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2038  errmsg("PL/Perl functions cannot accept type %s",
2039  format_type_be(argtypes[i]))));
2040  }
2041 
2042  ReleaseSysCache(tuple);
2043 
2044  /* Postpone body checks if !check_function_bodies */
2046  {
2047  (void) compile_plperl_function(funcoid, is_trigger, is_event_trigger);
2048  }
2049 
2050  /* the result of a validator is ignored */
2051  PG_RETURN_VOID();
2052 }
bool CheckFunctionValidatorAccess(Oid validatorOid, Oid functionOid)
Definition: fmgr.c:2145
#define PG_GETARG_OID(n)
Definition: fmgr.h:275
int get_func_arg_info(HeapTuple procTup, Oid **p_argtypes, char ***p_argnames, char **p_argmodes)
Definition: funcapi.c:1379
bool check_function_bodies
Definition: guc_tables.c:511
char get_typtype(Oid typid)
Definition: lsyscache.c:2629

References check_function_bodies, CheckFunctionValidatorAccess(), compile_plperl_function(), elog, ereport, errcode(), errmsg(), ERROR, format_type_be(), get_func_arg_info(), get_typtype(), GETSTRUCT, HeapTupleIsValid, i, ObjectIdGetDatum(), PG_GETARG_OID, PG_RETURN_VOID, ReleaseSysCache(), and SearchSysCache1().

Referenced by plperlu_validator().

◆ plperlu_call_handler()

Datum plperlu_call_handler ( PG_FUNCTION_ARGS  )

Definition at line 2066 of file plperl.c.

2067 {
2068  return plperl_call_handler(fcinfo);
2069 }
Datum plperl_call_handler(PG_FUNCTION_ARGS)
Definition: plperl.c:1852

References plperl_call_handler().

◆ plperlu_inline_handler()

Datum plperlu_inline_handler ( PG_FUNCTION_ARGS  )

Definition at line 2074 of file plperl.c.

2075 {
2076  return plperl_inline_handler(fcinfo);
2077 }
Datum plperl_inline_handler(PG_FUNCTION_ARGS)
Definition: plperl.c:1894

References plperl_inline_handler().

◆ plperlu_validator()

Datum plperlu_validator ( PG_FUNCTION_ARGS  )

Definition at line 2082 of file plperl.c.

2083 {
2084  /* call plperl validator with our fcinfo so it gets our oid */
2085  return plperl_validator(fcinfo);
2086 }
Datum plperl_validator(PG_FUNCTION_ARGS)
Definition: plperl.c:1988

References plperl_validator().

◆ pp_require_safe()

static OP * pp_require_safe ( pTHX  )
static

Definition at line 880 of file plperl.c.

881 {
882  dVAR;
883  dSP;
884  SV *sv,
885  **svp;
886  char *name;
887  STRLEN len;
888 
889  sv = POPs;
890  name = SvPV(sv, len);
891  if (!(name && len > 0 && *name))
892  RETPUSHNO;
893 
894  svp = hv_fetch(GvHVn(PL_incgv), name, len, 0);
895  if (svp && *svp != &PL_sv_undef)
896  RETPUSHYES;
897 
898  DIE(aTHX_ "Unable to load %s into plperl", name);
899 
900  /*
901  * In most Perl versions, DIE() expands to a return statement, so the next
902  * line is not necessary. But in versions between but not including
903  * 5.11.1 and 5.13.3 it does not, so the next line is necessary to avoid a
904  * "control reaches end of non-void function" warning from gcc. Other
905  * compilers such as Solaris Studio will, however, issue a "statement not
906  * reached" warning instead.
907  */
908  return NULL;
909 }
#define aTHX_
Definition: ppport.h:11333
#define dVAR
Definition: ppport.h:12519
const char * name

References aTHX_, dVAR, len, name, and PL_sv_undef.

Referenced by plperl_trusted_init(), and set_interp_require().

◆ select_perl_context()

static void select_perl_context ( bool  trusted)
static

Definition at line 553 of file plperl.c.

554 {
555  Oid user_id;
556  plperl_interp_desc *interp_desc;
557  bool found;
558  PerlInterpreter *interp = NULL;
559 
560  /* Find or create the interpreter hashtable entry for this userid */
561  if (trusted)
562  user_id = GetUserId();
563  else
564  user_id = InvalidOid;
565 
566  interp_desc = hash_search(plperl_interp_hash, &user_id,
567  HASH_ENTER,
568  &found);
569  if (!found)
570  {
571  /* Initialize newly-created hashtable entry */
572  interp_desc->interp = NULL;
573  interp_desc->query_hash = NULL;
574  }
575 
576  /* Make sure we have a query_hash for this interpreter */
577  if (interp_desc->query_hash == NULL)
578  {
579  HASHCTL hash_ctl;
580 
581  hash_ctl.keysize = NAMEDATALEN;
582  hash_ctl.entrysize = sizeof(plperl_query_entry);
583  interp_desc->query_hash = hash_create("PL/Perl queries",
584  32,
585  &hash_ctl,
587  }
588 
589  /*
590  * Quick exit if already have an interpreter
591  */
592  if (interp_desc->interp)
593  {
594  activate_interpreter(interp_desc);
595  return;
596  }
597 
598  /*
599  * adopt held interp if free, else create new one if possible
600  */
601  if (plperl_held_interp != NULL)
602  {
603  /* first actual use of a perl interpreter */
604  interp = plperl_held_interp;
605 
606  /*
607  * Reset the plperl_held_interp pointer first; if we fail during init
608  * we don't want to try again with the partially-initialized interp.
609  */
610  plperl_held_interp = NULL;
611 
612  if (trusted)
614  else
616 
617  /* successfully initialized, so arrange for cleanup */
619  }
620  else
621  {
622 #ifdef MULTIPLICITY
623 
624  /*
625  * plperl_init_interp will change Perl's idea of the active
626  * interpreter. Reset plperl_active_interp temporarily, so that if we
627  * hit an error partway through here, we'll make sure to switch back
628  * to a non-broken interpreter before running any other Perl
629  * functions.
630  */
631  plperl_active_interp = NULL;
632 
633  /* Now build the new interpreter */
634  interp = plperl_init_interp();
635 
636  if (trusted)
638  else
640 #else
641  ereport(ERROR,
642  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
643  errmsg("cannot allocate multiple Perl interpreters on this platform")));
644 #endif
645  }
646 
647  set_interp_require(trusted);
648 
649  /*
650  * Since the timing of first use of PL/Perl can't be predicted, any
651  * database interaction during initialization is problematic. Including,
652  * but not limited to, security definer issues. So we only enable access
653  * to the database AFTER on_*_init code has run. See
654  * http://archives.postgresql.org/pgsql-hackers/2010-01/msg02669.php
655  */
656  {
657  dTHX;
658 
659  newXS("PostgreSQL::InServer::SPI::bootstrap",
661 
662  eval_pv("PostgreSQL::InServer::SPI::bootstrap()", FALSE);
663  if (SvTRUE(ERRSV))
664  ereport(ERROR,
665  (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
667  errcontext("while executing PostgreSQL::InServer::SPI::bootstrap")));
668  }
669 
670  /* Fully initialized, so mark the hashtable entry valid */
671  interp_desc->interp = interp;
672 
673  /* And mark this as the active interpreter */
674  plperl_active_interp = interp_desc;
675 }
#define HASH_STRINGS
Definition: hsearch.h:96
void on_proc_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:309
static void plperl_trusted_init(void)
Definition: plperl.c:957
static void plperl_untrusted_init(void)
Definition: plperl.c:1038
struct plperl_query_entry plperl_query_entry
static void plperl_fini(int code, Datum arg)
Definition: plperl.c:509
EXTERN_C void boot_PostgreSQL__InServer__SPI(pTHX_ CV *cv)

References activate_interpreter(), boot_PostgreSQL__InServer__SPI(), dTHX, HASHCTL::entrysize, ereport, errcode(), errcontext, errmsg(), ERROR, ERRSV, GetUserId(), hash_create(), HASH_ELEM, HASH_ENTER, hash_search(), HASH_STRINGS, plperl_interp_desc::interp, InvalidOid, HASHCTL::keysize, NAMEDATALEN, on_proc_exit(), plperl_active_interp, plperl_fini(), plperl_held_interp, plperl_init_interp(), plperl_interp_hash, plperl_trusted_init(), plperl_untrusted_init(), plperl_interp_desc::query_hash, set_interp_require(), strip_trailing_ws(), and sv2cstr().

Referenced by compile_plperl_function(), and plperl_inline_handler().

◆ set_interp_require()

static void set_interp_require ( bool  trusted)
static

Definition at line 490 of file plperl.c.

491 {
492  if (trusted)
493  {
494  PL_ppaddr[OP_REQUIRE] = pp_require_safe;
495  PL_ppaddr[OP_DOFILE] = pp_require_safe;
496  }
497  else
498  {
499  PL_ppaddr[OP_REQUIRE] = pp_require_orig;
500  PL_ppaddr[OP_DOFILE] = pp_require_orig;
501  }
502 }

References PL_ppaddr, pp_require_orig, and pp_require_safe().

Referenced by activate_interpreter(), and select_perl_context().

◆ split_array()

static SV * split_array ( plperl_array_info info,
int  first,
int  last,
int  nest 
)
static

Definition at line 1559 of file plperl.c.

1560 {
1561  dTHX;
1562  int i;
1563  AV *result;
1564 
1565  /* we should only be called when we have something to split */
1566  Assert(info->ndims > 0);
1567 
1568  /* since this function recurses, it could be driven to stack overflow */
1570 
1571  /*
1572  * Base case, return a reference to a single-dimensional array
1573  */
1574  if (nest >= info->ndims - 1)
1575  return make_array_ref(info, first, last);
1576 
1577  result = newAV();
1578  for (i = first; i < last; i += info->nelems[nest + 1])
1579  {
1580  /* Recursively form references to arrays of lower dimensions */
1581  SV *ref = split_array(info, i, i + info->nelems[nest + 1], nest + 1);
1582 
1583  av_push(result, ref);
1584  }
1585  return newRV_noinc((SV *) result);
1586 }
static SV * make_array_ref(plperl_array_info *info, int first, int last)
Definition: plperl.c:1593

References Assert, check_stack_depth(), dTHX, i, make_array_ref(), plperl_array_info::ndims, plperl_array_info::nelems, and newRV_noinc.

Referenced by plperl_ref_from_pg_array().

◆ strip_trailing_ws()

static char * strip_trailing_ws ( const char *  msg)
static

Definition at line 1061 of file plperl.c.

1062 {
1063  char *res = pstrdup(msg);
1064  int len = strlen(res);
1065 
1066  while (len > 0 && isspace((unsigned char) res[len - 1]))
1067  res[--len] = '\0';
1068  return res;
1069 }

References len, pstrdup(), and res.

Referenced by plperl_call_perl_event_trigger_func(), plperl_call_perl_func(), plperl_call_perl_trigger_func(), plperl_create_sub(), plperl_init_interp(), plperl_trusted_init(), plperl_untrusted_init(), and select_perl_context().

◆ SvREFCNT_dec_current()

static void SvREFCNT_dec_current ( SV *  sv)
inlinestatic

Definition at line 312 of file plperl.c.

313 {
314  dTHX;
315 
316  SvREFCNT_dec(sv);
317 }

References dTHX.

Referenced by free_plperl_function(), plperl_event_trigger_handler(), plperl_func_handler(), plperl_inline_handler(), and plperl_trigger_handler().

◆ validate_plperl_function()

static bool validate_plperl_function ( plperl_proc_ptr proc_ptr,
HeapTuple  procTup 
)
static

Definition at line 2667 of file plperl.c.

2668 {
2669  if (proc_ptr && proc_ptr->proc_ptr)
2670  {
2671  plperl_proc_desc *prodesc = proc_ptr->proc_ptr;
2672  bool uptodate;
2673 
2674  /************************************************************
2675  * If it's present, must check whether it's still up to date.
2676  * This is needed because CREATE OR REPLACE FUNCTION can modify the
2677  * function's pg_proc entry without changing its OID.
2678  ************************************************************/
2679  uptodate = (prodesc->fn_xmin == HeapTupleHeaderGetRawXmin(procTup->t_data) &&
2680  ItemPointerEquals(&prodesc->fn_tid, &procTup->t_self));
2681 
2682  if (uptodate)
2683  return true;
2684 
2685  /* Otherwise, unlink the obsoleted entry from the hashtable ... */
2686  proc_ptr->proc_ptr = NULL;
2687  /* ... and release the corresponding refcount, probably deleting it */
2688  decrement_prodesc_refcount(prodesc);
2689  }
2690 
2691  return false;
2692 }
bool ItemPointerEquals(ItemPointer pointer1, ItemPointer pointer2)
Definition: itemptr.c:35

References decrement_prodesc_refcount, plperl_proc_desc::fn_tid, plperl_proc_desc::fn_xmin, HeapTupleHeaderGetRawXmin, ItemPointerEquals(), plperl_proc_ptr::proc_ptr, HeapTupleData::t_data, and HeapTupleData::t_self.

Referenced by compile_plperl_function().

Variable Documentation

◆ current_call_data

◆ PG_MODULE_MAGIC

PG_MODULE_MAGIC

Definition at line 56 of file plperl.c.

◆ plperl_active_interp

◆ plperl_ending

bool plperl_ending = false
static

Definition at line 236 of file plperl.c.

Referenced by check_spi_usage_allowed(), and plperl_fini().

◆ plperl_held_interp

PerlInterpreter* plperl_held_interp = NULL
static

Definition at line 228 of file plperl.c.

Referenced by _PG_init(), plperl_fini(), and select_perl_context().

◆ plperl_interp_hash

HTAB* plperl_interp_hash = NULL
static

Definition at line 223 of file plperl.c.

Referenced by _PG_init(), plperl_fini(), and select_perl_context().

◆ plperl_on_init

char* plperl_on_init = NULL
static

Definition at line 232 of file plperl.c.

Referenced by _PG_init(), and plperl_init_interp().

◆ plperl_on_plperl_init

char* plperl_on_plperl_init = NULL
static

Definition at line 233 of file plperl.c.

Referenced by _PG_init(), and plperl_trusted_init().

◆ plperl_on_plperlu_init

char* plperl_on_plperlu_init = NULL
static

Definition at line 234 of file plperl.c.

Referenced by _PG_init(), and plperl_untrusted_init().

◆ plperl_opmask

char plperl_opmask[MAXO]
static

Definition at line 238 of file plperl.c.

Referenced by _PG_init(), plperl_init_interp(), and plperl_trusted_init().

◆ plperl_proc_hash

HTAB* plperl_proc_hash = NULL
static

Definition at line 224 of file plperl.c.

Referenced by _PG_init(), and compile_plperl_function().

◆ plperl_use_strict

bool plperl_use_strict = false
static

Definition at line 231 of file plperl.c.

Referenced by _PG_init(), and plperl_create_sub().

◆ pp_require_orig

OP*(* pp_require_orig) (pTHX) ( pTHX  ) = NULL
static

Definition at line 237 of file plperl.c.

Referenced by plperl_init_interp(), plperl_trusted_init(), and set_interp_require().