PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
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_proc_fn.h"
#include "catalog/pg_type.h"
#include "commands/event_trigger.h"
#include "commands/trigger.h"
#include "executor/spi.h"
#include "funcapi.h"
#include "mb/pg_wchar.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 "plperl.h"
#include "plperl_helpers.h"
#include "perlchunks.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)
 

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)
 
void _PG_init (void)
 
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)
 
static SV * plperl_hash_from_datum (Datum attr)
 
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 *astate, int *ndims, int *dims, int cur_depth, Oid arraytypid, 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, 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)
 
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)
 
static void check_spi_usage_allowed (void)
 
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_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

#define decrement_prodesc_refcount (   prodesc)
Value:
do { \
Assert((prodesc)->fn_refcount > 0); \
if (--((prodesc)->fn_refcount) == 0) \
} while(0)
static void free_plperl_function(plperl_proc_desc *prodesc)
Definition: plperl.c:2668
#define Assert(condition)
Definition: c.h:664

Definition at line 136 of file plperl.c.

Referenced by plperl_call_handler(), and validate_plperl_function().

#define increment_prodesc_refcount (   prodesc)    ((prodesc)->fn_refcount++)
#define TEXTDOMAIN   PG_TEXTDOMAIN("plperl")

Definition at line 48 of file plperl.c.

Referenced by _PG_init().

Typedef Documentation

Function Documentation

void _PG_init ( void  )

Definition at line 382 of file plperl.c.

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

383 {
384  /*
385  * Be sure we do initialization only once.
386  *
387  * If initialization fails due to, e.g., plperl_init_interp() throwing an
388  * exception, then we'll return here on the next usage and the user will
389  * get a rather cryptic: ERROR: attempt to redefine parameter
390  * "plperl.use_strict"
391  */
392  static bool inited = false;
393  HASHCTL hash_ctl;
394 
395  if (inited)
396  return;
397 
398  /*
399  * Support localized messages.
400  */
402 
403  /*
404  * Initialize plperl's GUCs.
405  */
406  DefineCustomBoolVariable("plperl.use_strict",
407  gettext_noop("If true, trusted and untrusted Perl code will be compiled in strict mode."),
408  NULL,
410  false,
411  PGC_USERSET, 0,
412  NULL, NULL, NULL);
413 
414  /*
415  * plperl.on_init is marked PGC_SIGHUP to support the idea that it might
416  * be executed in the postmaster (if plperl is loaded into the postmaster
417  * via shared_preload_libraries). This isn't really right either way,
418  * though.
419  */
420  DefineCustomStringVariable("plperl.on_init",
421  gettext_noop("Perl initialization code to execute when a Perl interpreter is initialized."),
422  NULL,
424  NULL,
425  PGC_SIGHUP, 0,
426  NULL, NULL, NULL);
427 
428  /*
429  * plperl.on_plperl_init is marked PGC_SUSET to avoid issues whereby a
430  * user who might not even have USAGE privilege on the plperl language
431  * could nonetheless use SET plperl.on_plperl_init='...' to influence the
432  * behaviour of any existing plperl function that they can execute (which
433  * might be SECURITY DEFINER, leading to a privilege escalation). See
434  * http://archives.postgresql.org/pgsql-hackers/2010-02/msg00281.php and
435  * the overall thread.
436  *
437  * Note that because plperl.use_strict is USERSET, a nefarious user could
438  * set it to be applied against other people's functions. This is judged
439  * OK since the worst result would be an error. Your code oughta pass
440  * use_strict anyway ;-)
441  */
442  DefineCustomStringVariable("plperl.on_plperl_init",
443  gettext_noop("Perl initialization code to execute once when plperl is first used."),
444  NULL,
446  NULL,
447  PGC_SUSET, 0,
448  NULL, NULL, NULL);
449 
450  DefineCustomStringVariable("plperl.on_plperlu_init",
451  gettext_noop("Perl initialization code to execute once when plperlu is first used."),
452  NULL,
454  NULL,
455  PGC_SUSET, 0,
456  NULL, NULL, NULL);
457 
458  EmitWarningsOnPlaceholders("plperl");
459 
460  /*
461  * Create hash tables.
462  */
463  memset(&hash_ctl, 0, sizeof(hash_ctl));
464  hash_ctl.keysize = sizeof(Oid);
465  hash_ctl.entrysize = sizeof(plperl_interp_desc);
466  plperl_interp_hash = hash_create("PL/Perl interpreters",
467  8,
468  &hash_ctl,
470 
471  memset(&hash_ctl, 0, sizeof(hash_ctl));
472  hash_ctl.keysize = sizeof(plperl_proc_key);
473  hash_ctl.entrysize = sizeof(plperl_proc_ptr);
474  plperl_proc_hash = hash_create("PL/Perl procedures",
475  32,
476  &hash_ctl,
478 
479  /*
480  * Save the default opmask.
481  */
482  PLPERL_SET_OPMASK(plperl_opmask);
483 
484  /*
485  * Create the first Perl interpreter, but only partially initialize it.
486  */
488 
489  inited = true;
490 }
static char plperl_opmask[MAXO]
Definition: plperl.c:242
static PerlInterpreter * plperl_init_interp(void)
Definition: plperl.c:710
static HTAB * plperl_proc_hash
Definition: plperl.c:228
#define TEXTDOMAIN
Definition: plperl.c:48
#define HASH_ELEM
Definition: hsearch.h:87
static char * plperl_on_init
Definition: plperl.c:236
struct plperl_interp_desc plperl_interp_desc
Size entrysize
Definition: hsearch.h:73
#define gettext_noop(x)
Definition: c.h:139
unsigned int Oid
Definition: postgres_ext.h:31
Definition: guc.h:75
void EmitWarningsOnPlaceholders(const char *className)
Definition: guc.c:7877
Definition: guc.h:72
#define HASH_BLOBS
Definition: hsearch.h:88
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:7824
HTAB * hash_create(const char *tabname, long nelem, HASHCTL *info, int flags)
Definition: dynahash.c:316
Size keysize
Definition: hsearch.h:72
static char * plperl_on_plperl_init
Definition: plperl.c:237
static bool plperl_use_strict
Definition: plperl.c:235
static char * plperl_on_plperlu_init
Definition: plperl.c:238
struct plperl_proc_key plperl_proc_key
static PerlInterpreter * plperl_held_interp
Definition: plperl.c:232
static HTAB * plperl_interp_hash
Definition: plperl.c:227
void pg_bindtextdomain(const char *domain)
Definition: miscinit.c:1511
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:7738
struct plperl_proc_ptr plperl_proc_ptr
static void _sv_to_datum_finfo ( Oid  typid,
FmgrInfo finfo,
Oid typioparam 
)
static

Definition at line 1289 of file plperl.c.

References fmgr_info(), and getTypeInputInfo().

Referenced by plperl_array_to_datum(), and plperl_sv_to_datum().

1290 {
1291  Oid typinput;
1292 
1293  /* XXX would be better to cache these lookups */
1294  getTypeInputInfo(typid,
1295  &typinput, typioparam);
1296  fmgr_info(typinput, finfo);
1297 }
unsigned int Oid
Definition: postgres_ext.h:31
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:127
void getTypeInputInfo(Oid type, Oid *typInput, Oid *typIOParam)
Definition: lsyscache.c:2599
static void activate_interpreter ( plperl_interp_desc interp_desc)
static

Definition at line 689 of file plperl.c.

References Assert, plperl_interp_desc::interp, OidIsValid, 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().

690 {
691  if (interp_desc && plperl_active_interp != interp_desc)
692  {
693  Assert(interp_desc->interp);
694  PERL_SET_CONTEXT(interp_desc->interp);
695  /* trusted iff user_id isn't InvalidOid */
696  set_interp_require(OidIsValid(interp_desc->user_id));
697  plperl_active_interp = interp_desc;
698  }
699 }
static void set_interp_require(bool trusted)
Definition: plperl.c:494
static plperl_interp_desc * plperl_active_interp
Definition: plperl.c:229
PerlInterpreter * interp
Definition: plperl.c:93
#define OidIsValid(objectId)
Definition: c.h:532
#define Assert(condition)
Definition: c.h:664
static void array_to_datum_internal ( AV *  av,
ArrayBuildState astate,
int *  ndims,
int *  dims,
int  cur_depth,
Oid  arraytypid,
Oid  elemtypid,
int32  typmod,
FmgrInfo finfo,
Oid  typioparam 
)
static

Definition at line 1170 of file plperl.c.

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

Referenced by plperl_array_to_datum().

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  /* dimensionality checks */
1193  if (cur_depth + 1 > MAXDIM)
1194  ereport(ERROR,
1195  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1196  errmsg("number of array dimensions (%d) exceeds the maximum allowed (%d)",
1197  cur_depth + 1, MAXDIM)));
1198 
1199  /* set size when at first element in this level, else compare */
1200  if (i == 0 && *ndims == cur_depth)
1201  {
1202  dims[*ndims] = av_len(nav) + 1;
1203  (*ndims)++;
1204  }
1205  else if (av_len(nav) + 1 != dims[cur_depth])
1206  ereport(ERROR,
1207  (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1208  errmsg("multidimensional arrays must have array expressions with matching dimensions")));
1209 
1210  /* recurse to fetch elements of this sub-array */
1211  array_to_datum_internal(nav, astate,
1212  ndims, dims, cur_depth + 1,
1213  arraytypid, elemtypid, typmod,
1214  finfo, typioparam);
1215  }
1216  else
1217  {
1218  Datum dat;
1219  bool isnull;
1220 
1221  /* scalar after some sub-arrays at same level? */
1222  if (*ndims != cur_depth)
1223  ereport(ERROR,
1224  (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1225  errmsg("multidimensional arrays must have array expressions with matching dimensions")));
1226 
1227  dat = plperl_sv_to_datum(svp ? *svp : NULL,
1228  elemtypid,
1229  typmod,
1230  NULL,
1231  finfo,
1232  typioparam,
1233  &isnull);
1234 
1235  (void) accumArrayResult(astate, dat, isnull,
1236  elemtypid, CurrentMemoryContext);
1237  }
1238  }
1239 }
static SV * get_perl_array_ref(SV *sv)
Definition: plperl.c:1143
static Datum plperl_sv_to_datum(SV *sv, Oid typid, int32 typmod, FunctionCallInfo fcinfo, FmgrInfo *finfo, Oid typioparam, bool *isnull)
Definition: plperl.c:1312
#define dTHX
Definition: ppport.h:3208
#define MAXDIM
Definition: c.h:413
int errcode(int sqlerrcode)
Definition: elog.c:575
#define ERROR
Definition: elog.h:43
#define FALSE
Definition: c.h:219
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
#define ereport(elevel, rest)
Definition: elog.h:122
struct @18::@19 av[32]
uintptr_t Datum
Definition: postgres.h:372
ArrayBuildState * accumArrayResult(ArrayBuildState *astate, Datum dvalue, bool disnull, Oid element_type, MemoryContext rcontext)
Definition: arrayfuncs.c:5069
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
static void array_to_datum_internal(AV *av, ArrayBuildState *astate, int *ndims, int *dims, int cur_depth, Oid arraytypid, Oid elemtypid, int32 typmod, FmgrInfo *finfo, Oid typioparam)
Definition: plperl.c:1170
EXTERN_C void boot_DynaLoader ( pTHX_ CV *  cv)

Referenced by plperl_init_shared_libs().

EXTERN_C void boot_PostgreSQL__InServer__SPI ( pTHX_ CV *  cv)

Referenced by select_perl_context().

EXTERN_C void boot_PostgreSQL__InServer__Util ( pTHX_ CV *  cv)

Referenced by plperl_init_shared_libs().

static void check_spi_usage_allowed ( void  )
static

Definition at line 3073 of file plperl.c.

References plperl_ending.

Referenced by 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(), and plperl_spi_query_prepared().

3074 {
3075  /* see comment in plperl_fini() */
3076  if (plperl_ending)
3077  {
3078  /* simple croak as we don't want to involve PostgreSQL code */
3079  croak("SPI functions can not be used in END blocks");
3080  }
3081 }
static bool plperl_ending
Definition: plperl.c:240
static plperl_proc_desc * compile_plperl_function ( Oid  fn_oid,
bool  is_trigger,
bool  is_event_trigger 
)
static

Definition at line 2686 of file plperl.c.

References activate_interpreter(), ALLOCSET_SMALL_SIZES, AllocSetContextCreate(), Anum_pg_proc_prosrc, Anum_pg_proc_protrftypes, 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, EVTTRIGGEROID, 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(), HeapTupleGetOid, HeapTupleHeaderGetRawXmin, HeapTupleIsValid, i, increment_prodesc_refcount, plperl_proc_desc::interp, InvalidOid, plperl_proc_key::is_trigger, plperl_proc_desc::lang_oid, LANGOID, plperl_proc_desc::lanpltrusted, MemoryContextDelete(), 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(), ErrorContextCallback::previous, plperl_proc_key::proc_id, plperl_proc_ptr::proc_ptr, PROCOID, plperl_proc_desc::proname, PROVOLATILE_VOLATILE, pstrdup(), RECORDOID, 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(), HeapTupleData::t_data, HeapTupleData::t_self, TextDatumGetCString, TopMemoryContext, plperl_proc_desc::trftypes, TRIGGEROID, TYPEOID, TYPTYPE_COMPOSITE, TYPTYPE_PSEUDO, plperl_proc_key::user_id, validate_plperl_function(), and VOIDOID.

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

2687 {
2688  HeapTuple procTup;
2689  Form_pg_proc procStruct;
2690  plperl_proc_key proc_key;
2691  plperl_proc_ptr *proc_ptr;
2692  plperl_proc_desc *volatile prodesc = NULL;
2693  volatile MemoryContext proc_cxt = NULL;
2695  ErrorContextCallback plperl_error_context;
2696 
2697  /* We'll need the pg_proc tuple in any case... */
2698  procTup = SearchSysCache1(PROCOID, ObjectIdGetDatum(fn_oid));
2699  if (!HeapTupleIsValid(procTup))
2700  elog(ERROR, "cache lookup failed for function %u", fn_oid);
2701  procStruct = (Form_pg_proc) GETSTRUCT(procTup);
2702 
2703  /*
2704  * Try to find function in plperl_proc_hash. The reason for this
2705  * overcomplicated-seeming lookup procedure is that we don't know whether
2706  * it's plperl or plperlu, and don't want to spend a lookup in pg_language
2707  * to find out.
2708  */
2709  proc_key.proc_id = fn_oid;
2710  proc_key.is_trigger = is_trigger;
2711  proc_key.user_id = GetUserId();
2712  proc_ptr = hash_search(plperl_proc_hash, &proc_key,
2713  HASH_FIND, NULL);
2714  if (validate_plperl_function(proc_ptr, procTup))
2715  {
2716  /* Found valid plperl entry */
2717  ReleaseSysCache(procTup);
2718  return proc_ptr->proc_ptr;
2719  }
2720 
2721  /* If not found or obsolete, maybe it's plperlu */
2722  proc_key.user_id = InvalidOid;
2723  proc_ptr = hash_search(plperl_proc_hash, &proc_key,
2724  HASH_FIND, NULL);
2725  if (validate_plperl_function(proc_ptr, procTup))
2726  {
2727  /* Found valid plperlu entry */
2728  ReleaseSysCache(procTup);
2729  return proc_ptr->proc_ptr;
2730  }
2731 
2732  /************************************************************
2733  * If we haven't found it in the hashtable, we analyze
2734  * the function's arguments and return type and store
2735  * the in-/out-functions in the prodesc block,
2736  * then we load the procedure into the Perl interpreter,
2737  * and last we create a new hashtable entry for it.
2738  ************************************************************/
2739 
2740  /* Set a callback for reporting compilation errors */
2741  plperl_error_context.callback = plperl_compile_callback;
2742  plperl_error_context.previous = error_context_stack;
2743  plperl_error_context.arg = NameStr(procStruct->proname);
2744  error_context_stack = &plperl_error_context;
2745 
2746  PG_TRY();
2747  {
2748  HeapTuple langTup;
2749  HeapTuple typeTup;
2750  Form_pg_language langStruct;
2751  Form_pg_type typeStruct;
2752  Datum protrftypes_datum;
2753  Datum prosrcdatum;
2754  bool isnull;
2755  char *proc_source;
2756  MemoryContext oldcontext;
2757 
2758  /************************************************************
2759  * Allocate a context that will hold all PG data for the procedure.
2760  ************************************************************/
2762  NameStr(procStruct->proname),
2764 
2765  /************************************************************
2766  * Allocate and fill a new procedure description block.
2767  * struct prodesc and subsidiary data must all live in proc_cxt.
2768  ************************************************************/
2769  oldcontext = MemoryContextSwitchTo(proc_cxt);
2770  prodesc = (plperl_proc_desc *) palloc0(sizeof(plperl_proc_desc));
2771  prodesc->proname = pstrdup(NameStr(procStruct->proname));
2772  prodesc->fn_cxt = proc_cxt;
2773  prodesc->fn_refcount = 0;
2774  prodesc->fn_xmin = HeapTupleHeaderGetRawXmin(procTup->t_data);
2775  prodesc->fn_tid = procTup->t_self;
2776  prodesc->nargs = procStruct->pronargs;
2777  prodesc->arg_out_func = (FmgrInfo *) palloc0(prodesc->nargs * sizeof(FmgrInfo));
2778  prodesc->arg_is_rowtype = (bool *) palloc0(prodesc->nargs * sizeof(bool));
2779  prodesc->arg_arraytype = (Oid *) palloc0(prodesc->nargs * sizeof(Oid));
2780  MemoryContextSwitchTo(oldcontext);
2781 
2782  /* Remember if function is STABLE/IMMUTABLE */
2783  prodesc->fn_readonly =
2784  (procStruct->provolatile != PROVOLATILE_VOLATILE);
2785 
2786  /* Fetch protrftypes */
2787  protrftypes_datum = SysCacheGetAttr(PROCOID, procTup,
2788  Anum_pg_proc_protrftypes, &isnull);
2789  MemoryContextSwitchTo(proc_cxt);
2790  prodesc->trftypes = isnull ? NIL : oid_array_to_list(protrftypes_datum);
2791  MemoryContextSwitchTo(oldcontext);
2792 
2793  /************************************************************
2794  * Lookup the pg_language tuple by Oid
2795  ************************************************************/
2796  langTup = SearchSysCache1(LANGOID,
2797  ObjectIdGetDatum(procStruct->prolang));
2798  if (!HeapTupleIsValid(langTup))
2799  elog(ERROR, "cache lookup failed for language %u",
2800  procStruct->prolang);
2801  langStruct = (Form_pg_language) GETSTRUCT(langTup);
2802  prodesc->lang_oid = HeapTupleGetOid(langTup);
2803  prodesc->lanpltrusted = langStruct->lanpltrusted;
2804  ReleaseSysCache(langTup);
2805 
2806  /************************************************************
2807  * Get the required information for input conversion of the
2808  * return value.
2809  ************************************************************/
2810  if (!is_trigger && !is_event_trigger)
2811  {
2812  typeTup =
2814  ObjectIdGetDatum(procStruct->prorettype));
2815  if (!HeapTupleIsValid(typeTup))
2816  elog(ERROR, "cache lookup failed for type %u",
2817  procStruct->prorettype);
2818  typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
2819 
2820  /* Disallow pseudotype result, except VOID or RECORD */
2821  if (typeStruct->typtype == TYPTYPE_PSEUDO)
2822  {
2823  if (procStruct->prorettype == VOIDOID ||
2824  procStruct->prorettype == RECORDOID)
2825  /* okay */ ;
2826  else if (procStruct->prorettype == TRIGGEROID ||
2827  procStruct->prorettype == EVTTRIGGEROID)
2828  ereport(ERROR,
2829  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2830  errmsg("trigger functions can only be called "
2831  "as triggers")));
2832  else
2833  ereport(ERROR,
2834  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2835  errmsg("PL/Perl functions cannot return type %s",
2836  format_type_be(procStruct->prorettype))));
2837  }
2838 
2839  prodesc->result_oid = procStruct->prorettype;
2840  prodesc->fn_retisset = procStruct->proretset;
2841  prodesc->fn_retistuple = (procStruct->prorettype == RECORDOID ||
2842  typeStruct->typtype == TYPTYPE_COMPOSITE);
2843 
2844  prodesc->fn_retisarray =
2845  (typeStruct->typlen == -1 && typeStruct->typelem);
2846 
2847  fmgr_info_cxt(typeStruct->typinput,
2848  &(prodesc->result_in_func),
2849  proc_cxt);
2850  prodesc->result_typioparam = getTypeIOParam(typeTup);
2851 
2852  ReleaseSysCache(typeTup);
2853  }
2854 
2855  /************************************************************
2856  * Get the required information for output conversion
2857  * of all procedure arguments
2858  ************************************************************/
2859  if (!is_trigger && !is_event_trigger)
2860  {
2861  int i;
2862 
2863  for (i = 0; i < prodesc->nargs; i++)
2864  {
2865  typeTup = SearchSysCache1(TYPEOID,
2866  ObjectIdGetDatum(procStruct->proargtypes.values[i]));
2867  if (!HeapTupleIsValid(typeTup))
2868  elog(ERROR, "cache lookup failed for type %u",
2869  procStruct->proargtypes.values[i]);
2870  typeStruct = (Form_pg_type) GETSTRUCT(typeTup);
2871 
2872  /* Disallow pseudotype argument */
2873  if (typeStruct->typtype == TYPTYPE_PSEUDO &&
2874  procStruct->proargtypes.values[i] != RECORDOID)
2875  ereport(ERROR,
2876  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2877  errmsg("PL/Perl functions cannot accept type %s",
2878  format_type_be(procStruct->proargtypes.values[i]))));
2879 
2880  if (typeStruct->typtype == TYPTYPE_COMPOSITE ||
2881  procStruct->proargtypes.values[i] == RECORDOID)
2882  prodesc->arg_is_rowtype[i] = true;
2883  else
2884  {
2885  prodesc->arg_is_rowtype[i] = false;
2886  fmgr_info_cxt(typeStruct->typoutput,
2887  &(prodesc->arg_out_func[i]),
2888  proc_cxt);
2889  }
2890 
2891  /* Identify array attributes */
2892  if (typeStruct->typelem != 0 && typeStruct->typlen == -1)
2893  prodesc->arg_arraytype[i] = procStruct->proargtypes.values[i];
2894  else
2895  prodesc->arg_arraytype[i] = InvalidOid;
2896 
2897  ReleaseSysCache(typeTup);
2898  }
2899  }
2900 
2901  /************************************************************
2902  * create the text of the anonymous subroutine.
2903  * we do not use a named subroutine so that we can call directly
2904  * through the reference.
2905  ************************************************************/
2906  prosrcdatum = SysCacheGetAttr(PROCOID, procTup,
2907  Anum_pg_proc_prosrc, &isnull);
2908  if (isnull)
2909  elog(ERROR, "null prosrc");
2910  proc_source = TextDatumGetCString(prosrcdatum);
2911 
2912  /************************************************************
2913  * Create the procedure in the appropriate interpreter
2914  ************************************************************/
2915 
2917 
2918  prodesc->interp = plperl_active_interp;
2919 
2920  plperl_create_sub(prodesc, proc_source, fn_oid);
2921 
2922  activate_interpreter(oldinterp);
2923 
2924  pfree(proc_source);
2925 
2926  if (!prodesc->reference) /* can this happen? */
2927  elog(ERROR, "could not create PL/Perl internal procedure");
2928 
2929  /************************************************************
2930  * OK, link the procedure into the correct hashtable entry.
2931  * Note we assume that the hashtable entry either doesn't exist yet,
2932  * or we already cleared its proc_ptr during the validation attempts
2933  * above. So no need to decrement an old refcount here.
2934  ************************************************************/
2935  proc_key.user_id = prodesc->lanpltrusted ? GetUserId() : InvalidOid;
2936 
2937  proc_ptr = hash_search(plperl_proc_hash, &proc_key,
2938  HASH_ENTER, NULL);
2939  /* We assume these two steps can't throw an error: */
2940  proc_ptr->proc_ptr = prodesc;
2941  increment_prodesc_refcount(prodesc);
2942  }
2943  PG_CATCH();
2944  {
2945  /*
2946  * If we got as far as creating a reference, we should be able to use
2947  * free_plperl_function() to clean up. If not, then at most we have
2948  * some PG memory resources in proc_cxt, which we can just delete.
2949  */
2950  if (prodesc && prodesc->reference)
2951  free_plperl_function(prodesc);
2952  else if (proc_cxt)
2953  MemoryContextDelete(proc_cxt);
2954 
2955  /* Be sure to restore the previous interpreter, too, for luck */
2956  activate_interpreter(oldinterp);
2957 
2958  PG_RE_THROW();
2959  }
2960  PG_END_TRY();
2961 
2962  /* restore previous error callback */
2963  error_context_stack = plperl_error_context.previous;
2964 
2965  ReleaseSysCache(procTup);
2966 
2967  return prodesc;
2968 }
#define NIL
Definition: pg_list.h:69
Definition: fmgr.h:56
static bool validate_plperl_function(plperl_proc_ptr *proc_ptr, HeapTuple procTup)
Definition: plperl.c:2639
List * trftypes
Definition: plperl.c:118
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:200
static HTAB * plperl_proc_hash
Definition: plperl.c:228
bool * arg_is_rowtype
Definition: plperl.c:130
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
static void select_perl_context(bool trusted)
Definition: plperl.c:557
Oid GetUserId(void)
Definition: miscinit.c:284
#define TYPTYPE_COMPOSITE
Definition: pg_type.h:721
char * pstrdup(const char *in)
Definition: mcxt.c:1076
#define ALLOCSET_SMALL_SIZES
Definition: memutils.h:175
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define Anum_pg_proc_prosrc
Definition: pg_proc.h:115
int errcode(int sqlerrcode)
Definition: elog.c:575
MemoryContext fn_cxt
Definition: plperl.c:110
char * format_type_be(Oid type_oid)
Definition: format_type.c:94
#define Anum_pg_proc_protrftypes
Definition: pg_proc.h:114
static plperl_interp_desc * plperl_active_interp
Definition: plperl.c:229
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:902
FormData_pg_type * Form_pg_type
Definition: pg_type.h:233
unsigned int Oid
Definition: postgres_ext.h:31
FmgrInfo * arg_out_func
Definition: plperl.c:129
struct ErrorContextCallback * previous
Definition: elog.h:238
#define SearchSysCache1(cacheId, key1)
Definition: syscache.h:159
HeapTupleHeader t_data
Definition: htup.h:67
ErrorContextCallback * error_context_stack
Definition: elog.c:88
List * oid_array_to_list(Datum datum)
Definition: pg_proc.c:1156
void pfree(void *pointer)
Definition: mcxt.c:949
bool fn_retisset
Definition: plperl.c:121
#define VOIDOID
Definition: pg_type.h:690
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
plperl_proc_desc * proc_ptr
Definition: plperl.c:171
ItemPointerData fn_tid
Definition: plperl.c:113
#define TRIGGEROID
Definition: pg_type.h:692
ItemPointerData t_self
Definition: htup.h:65
FmgrInfo result_in_func
Definition: plperl.c:125
static void activate_interpreter(plperl_interp_desc *interp_desc)
Definition: plperl.c:689
#define RECORDOID
Definition: pg_type.h:680
void fmgr_info_cxt(Oid functionId, FmgrInfo *finfo, MemoryContext mcxt)
Definition: fmgr.c:137
#define increment_prodesc_refcount(prodesc)
Definition: plperl.c:134
Oid result_typioparam
Definition: plperl.c:126
#define ereport(elevel, rest)
Definition: elog.h:122
Oid * arg_arraytype
Definition: plperl.c:131
MemoryContext TopMemoryContext
Definition: mcxt.c:43
unsigned long fn_refcount
Definition: plperl.c:111
#define PROVOLATILE_VOLATILE
Definition: pg_proc.h:5535
#define TextDatumGetCString(d)
Definition: builtins.h:92
MemoryContext AllocSetContextCreate(MemoryContext parent, const char *name, Size minContextSize, Size initBlockSize, Size maxBlockSize)
Definition: aset.c:322
Oid is_trigger
Definition: plperl.c:164
void * palloc0(Size size)
Definition: mcxt.c:877
uintptr_t Datum
Definition: postgres.h:372
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1117
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1325
static void free_plperl_function(plperl_proc_desc *prodesc)
Definition: plperl.c:2668
FormData_pg_proc * Form_pg_proc
Definition: pg_proc.h:83
#define InvalidOid
Definition: postgres_ext.h:36
static void plperl_create_sub(plperl_proc_desc *desc, char *s, Oid fn_oid)
Definition: plperl.c:2066
bool fn_readonly
Definition: plperl.c:116
#define PG_CATCH()
Definition: elog.h:293
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define EVTTRIGGEROID
Definition: pg_type.h:694
SV * reference
Definition: plperl.c:114
#define HeapTupleHeaderGetRawXmin(tup)
Definition: htup_details.h:302
#define PG_RE_THROW()
Definition: elog.h:314
#define TYPTYPE_PSEUDO
Definition: pg_type.h:724
static void plperl_compile_callback(void *arg)
Definition: plperl.c:4018
void(* callback)(void *arg)
Definition: elog.h:239
FormData_pg_language * Form_pg_language
Definition: pg_language.h:51
int errmsg(const char *fmt,...)
Definition: elog.c:797
bool fn_retistuple
Definition: plperl.c:120
int i
Oid getTypeIOParam(HeapTuple typeTuple)
Definition: lsyscache.c:2053
#define NameStr(name)
Definition: c.h:493
char * proname
Definition: plperl.c:109
TransactionId fn_xmin
Definition: plperl.c:112
#define elog
Definition: elog.h:219
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:695
#define PG_TRY()
Definition: elog.h:284
plperl_interp_desc * interp
Definition: plperl.c:115
#define PG_END_TRY()
Definition: elog.h:300
bool lanpltrusted
Definition: plperl.c:119
bool fn_retisarray
Definition: plperl.c:122
static void free_plperl_function ( plperl_proc_desc prodesc)
static

Definition at line 2668 of file plperl.c.

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

2669 {
2670  Assert(prodesc->fn_refcount == 0);
2671  /* Release CODE reference, if we have one, from the appropriate interp */
2672  if (prodesc->reference)
2673  {
2675 
2676  activate_interpreter(prodesc->interp);
2677  SvREFCNT_dec_current(prodesc->reference);
2678  activate_interpreter(oldinterp);
2679  }
2680  /* Release all PG-owned data for this proc */
2681  MemoryContextDelete(prodesc->fn_cxt);
2682 }
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:200
MemoryContext fn_cxt
Definition: plperl.c:110
static plperl_interp_desc * plperl_active_interp
Definition: plperl.c:229
static void activate_interpreter(plperl_interp_desc *interp_desc)
Definition: plperl.c:689
unsigned long fn_refcount
Definition: plperl.c:111
static void SvREFCNT_dec_current(SV *sv)
Definition: plperl.c:314
#define Assert(condition)
Definition: c.h:664
SV * reference
Definition: plperl.c:114
plperl_interp_desc * interp
Definition: plperl.c:115
static SV * get_perl_array_ref ( SV *  sv)
static

Definition at line 1143 of file plperl.c.

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

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

1144 {
1145  dTHX;
1146 
1147  if (SvOK(sv) && SvROK(sv))
1148  {
1149  if (SvTYPE(SvRV(sv)) == SVt_PVAV)
1150  return sv;
1151  else if (sv_isa(sv, "PostgreSQL::InServer::ARRAY"))
1152  {
1153  HV *hv = (HV *) SvRV(sv);
1154  SV **sav = hv_fetch_string(hv, "array");
1155 
1156  if (*sav && SvOK(*sav) && SvROK(*sav) &&
1157  SvTYPE(SvRV(*sav)) == SVt_PVAV)
1158  return *sav;
1159 
1160  elog(ERROR, "could not get array reference from PostgreSQL::InServer::ARRAY object");
1161  }
1162  }
1163  return NULL;
1164 }
#define dTHX
Definition: ppport.h:3208
static SV ** hv_fetch_string(HV *hv, const char *key)
Definition: plperl.c:3983
#define ERROR
Definition: elog.h:43
#define elog
Definition: elog.h:219
static char * hek2cstr ( HE *  he)
static

Definition at line 325 of file plperl.c.

References dTHX, HeUTF8, and sv2cstr().

Referenced by plperl_build_tuple_result(), and plperl_modify_tuple().

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

Definition at line 3983 of file plperl.c.

References dTHX, pfree(), pg_server_to_any(), and PG_UTF8.

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

3984 {
3985  dTHX;
3986  int32 hlen;
3987  char *hkey;
3988  SV **ret;
3989 
3990  hkey = pg_server_to_any(key, strlen(key), PG_UTF8);
3991 
3992  /* See notes in hv_store_string */
3993  hlen = -(int) strlen(hkey);
3994  ret = hv_fetch(hv, hkey, hlen, 0);
3995 
3996  if (hkey != key)
3997  pfree(hkey);
3998 
3999  return ret;
4000 }
#define dTHX
Definition: ppport.h:3208
char * pg_server_to_any(const char *s, int len, int encoding)
Definition: mbutils.c:645
signed int int32
Definition: c.h:246
void pfree(void *pointer)
Definition: mcxt.c:949
static SV ** hv_store_string ( HV *  hv,
const char *  key,
SV *  val 
)
static

Definition at line 3956 of file plperl.c.

References dTHX, pfree(), pg_server_to_any(), and PG_UTF8.

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

3957 {
3958  dTHX;
3959  int32 hlen;
3960  char *hkey;
3961  SV **ret;
3962 
3963  hkey = pg_server_to_any(key, strlen(key), PG_UTF8);
3964 
3965  /*
3966  * hv_store() recognizes a negative klen parameter as meaning a UTF-8
3967  * encoded key.
3968  */
3969  hlen = -(int) strlen(hkey);
3970  ret = hv_store(hv, hkey, hlen, val, 0);
3971 
3972  if (hkey != key)
3973  pfree(hkey);
3974 
3975  return ret;
3976 }
#define dTHX
Definition: ppport.h:3208
char * pg_server_to_any(const char *s, int len, int encoding)
Definition: mbutils.c:645
signed int int32
Definition: c.h:246
void pfree(void *pointer)
Definition: mcxt.c:949
long val
Definition: informix.c:689
static SV * make_array_ref ( plperl_array_info info,
int  first,
int  last 
)
static

Definition at line 1561 of file plperl.c.

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

1562 {
1563  dTHX;
1564  int i;
1565  AV *result = newAV();
1566 
1567  for (i = first; i < last; i++)
1568  {
1569  if (info->nulls[i])
1570  {
1571  /*
1572  * We can't use &PL_sv_undef here. See "AVs, HVs and undefined
1573  * values" in perlguts.
1574  */
1575  av_push(result, newSV(0));
1576  }
1577  else
1578  {
1579  Datum itemvalue = info->elements[i];
1580 
1581  if (info->transform_proc.fn_oid)
1582  av_push(result, (SV *) DatumGetPointer(FunctionCall1(&info->transform_proc, itemvalue)));
1583  else if (info->elem_is_rowtype)
1584  /* Handle composite type elements */
1585  av_push(result, plperl_hash_from_datum(itemvalue));
1586  else
1587  {
1588  char *val = OutputFunctionCall(&info->proc, itemvalue);
1589 
1590  av_push(result, cstr2sv(val));
1591  }
1592  }
1593  }
1594  return newRV_noinc((SV *) result);
1595 }
FmgrInfo transform_proc
Definition: plperl.c:220
#define dTHX
Definition: ppport.h:3208
static SV * plperl_hash_from_datum(Datum attr)
Definition: plperl.c:2972
char * OutputFunctionCall(FmgrInfo *flinfo, Datum val)
Definition: fmgr.c:1667
#define newRV_noinc(a)
Definition: ppport.h:4456
uintptr_t Datum
Definition: postgres.h:372
bool elem_is_rowtype
Definition: plperl.c:215
static SV * cstr2sv(const char *str)
Oid fn_oid
Definition: fmgr.h:59
FmgrInfo proc
Definition: plperl.c:219
#define DatumGetPointer(X)
Definition: postgres.h:555
bool * nulls
Definition: plperl.c:217
int i
Datum * elements
Definition: plperl.c:216
#define FunctionCall1(flinfo, arg1)
Definition: fmgr.h:603
long val
Definition: informix.c:689
PG_FUNCTION_INFO_V1 ( plperl_call_handler  )
PG_FUNCTION_INFO_V1 ( plperl_inline_handler  )
PG_FUNCTION_INFO_V1 ( plperl_validator  )
PG_FUNCTION_INFO_V1 ( plperlu_call_handler  )
PG_FUNCTION_INFO_V1 ( plperlu_inline_handler  )
PG_FUNCTION_INFO_V1 ( plperlu_validator  )
static Datum plperl_array_to_datum ( SV *  src,
Oid  typid,
int32  typmod 
)
static

Definition at line 1245 of file plperl.c.

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

Referenced by plperl_sv_to_datum().

1246 {
1247  dTHX;
1248  ArrayBuildState *astate;
1249  Oid elemtypid;
1250  FmgrInfo finfo;
1251  Oid typioparam;
1252  int dims[MAXDIM];
1253  int lbs[MAXDIM];
1254  int ndims = 1;
1255  int i;
1256 
1257  elemtypid = get_element_type(typid);
1258  if (!elemtypid)
1259  ereport(ERROR,
1260  (errcode(ERRCODE_DATATYPE_MISMATCH),
1261  errmsg("cannot convert Perl array to non-array type %s",
1262  format_type_be(typid))));
1263 
1264  astate = initArrayResult(elemtypid, CurrentMemoryContext, true);
1265 
1266  _sv_to_datum_finfo(elemtypid, &finfo, &typioparam);
1267 
1268  memset(dims, 0, sizeof(dims));
1269  dims[0] = av_len((AV *) SvRV(src)) + 1;
1270 
1271  array_to_datum_internal((AV *) SvRV(src), astate,
1272  &ndims, dims, 1,
1273  typid, elemtypid, typmod,
1274  &finfo, typioparam);
1275 
1276  /* ensure we get zero-D array for no inputs, as per PG convention */
1277  if (dims[0] <= 0)
1278  ndims = 0;
1279 
1280  for (i = 0; i < ndims; i++)
1281  lbs[i] = 1;
1282 
1283  return makeMdArrayResult(astate, ndims, dims, lbs,
1284  CurrentMemoryContext, true);
1285 }
Datum makeMdArrayResult(ArrayBuildState *astate, int ndims, int *dims, int *lbs, MemoryContext rcontext, bool release)
Definition: arrayfuncs.c:5165
Definition: fmgr.h:56
ArrayBuildState * initArrayResult(Oid element_type, MemoryContext rcontext, bool subcontext)
Definition: arrayfuncs.c:5030
#define dTHX
Definition: ppport.h:3208
#define MAXDIM
Definition: c.h:413
Oid get_element_type(Oid typid)
Definition: lsyscache.c:2484
int errcode(int sqlerrcode)
Definition: elog.c:575
char * format_type_be(Oid type_oid)
Definition: format_type.c:94
unsigned int Oid
Definition: postgres_ext.h:31
#define ERROR
Definition: elog.h:43
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
#define ereport(elevel, rest)
Definition: elog.h:122
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
static void _sv_to_datum_finfo(Oid typid, FmgrInfo *finfo, Oid *typioparam)
Definition: plperl.c:1289
static void array_to_datum_internal(AV *av, ArrayBuildState *astate, int *ndims, int *dims, int cur_depth, Oid arraytypid, Oid elemtypid, int32 typmod, FmgrInfo *finfo, Oid typioparam)
Definition: plperl.c:1170
static HeapTuple plperl_build_tuple_result ( HV *  perlhash,
TupleDesc  td 
)
static

Definition at line 1080 of file plperl.c.

References dTHX, ereport, errcode(), errmsg(), ERROR, heap_form_tuple(), hek2cstr(), InvalidOid, tupleDesc::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().

1081 {
1082  dTHX;
1083  Datum *values;
1084  bool *nulls;
1085  HE *he;
1086  HeapTuple tup;
1087 
1088  values = palloc0(sizeof(Datum) * td->natts);
1089  nulls = palloc(sizeof(bool) * td->natts);
1090  memset(nulls, true, sizeof(bool) * td->natts);
1091 
1092  hv_iterinit(perlhash);
1093  while ((he = hv_iternext(perlhash)))
1094  {
1095  SV *val = HeVAL(he);
1096  char *key = hek2cstr(he);
1097  int attn = SPI_fnumber(td, key);
1098  Form_pg_attribute attr = TupleDescAttr(td, attn - 1);
1099 
1100  if (attn == SPI_ERROR_NOATTRIBUTE)
1101  ereport(ERROR,
1102  (errcode(ERRCODE_UNDEFINED_COLUMN),
1103  errmsg("Perl hash contains nonexistent column \"%s\"",
1104  key)));
1105  if (attn <= 0)
1106  ereport(ERROR,
1107  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1108  errmsg("cannot set system attribute \"%s\"",
1109  key)));
1110 
1111  values[attn - 1] = plperl_sv_to_datum(val,
1112  attr->atttypid,
1113  attr->atttypmod,
1114  NULL,
1115  NULL,
1116  InvalidOid,
1117  &nulls[attn - 1]);
1118 
1119  pfree(key);
1120  }
1121  hv_iterinit(perlhash);
1122 
1123  tup = heap_form_tuple(td, values, nulls);
1124  pfree(values);
1125  pfree(nulls);
1126  return tup;
1127 }
int SPI_fnumber(TupleDesc tupdesc, const char *fname)
Definition: spi.c:761
static char * hek2cstr(HE *he)
Definition: plperl.c:325
static Datum plperl_sv_to_datum(SV *sv, Oid typid, int32 typmod, FunctionCallInfo fcinfo, FmgrInfo *finfo, Oid typioparam, bool *isnull)
Definition: plperl.c:1312
#define dTHX
Definition: ppport.h:3208
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:84
int errcode(int sqlerrcode)
Definition: elog.c:575
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:695
int natts
Definition: tupdesc.h:73
void pfree(void *pointer)
Definition: mcxt.c:949
#define ERROR
Definition: elog.h:43
#define SPI_ERROR_NOATTRIBUTE
Definition: spi.h:44
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:187
#define ereport(elevel, rest)
Definition: elog.h:122
void * palloc0(Size size)
Definition: mcxt.c:877
uintptr_t Datum
Definition: postgres.h:372
#define InvalidOid
Definition: postgres_ext.h:36
static Datum values[MAXATTR]
Definition: bootstrap.c:164
void * palloc(Size size)
Definition: mcxt.c:848
int errmsg(const char *fmt,...)
Definition: elog.c:797
long val
Definition: informix.c:689
Datum plperl_call_handler ( PG_FUNCTION_ARGS  )

Definition at line 1809 of file plperl.c.

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

Referenced by plperlu_call_handler().

1810 {
1811  Datum retval;
1812  plperl_call_data *volatile save_call_data = current_call_data;
1813  plperl_interp_desc *volatile oldinterp = plperl_active_interp;
1814  plperl_call_data this_call_data;
1815 
1816  /* Initialize current-call status record */
1817  MemSet(&this_call_data, 0, sizeof(this_call_data));
1818  this_call_data.fcinfo = fcinfo;
1819 
1820  PG_TRY();
1821  {
1822  current_call_data = &this_call_data;
1823  if (CALLED_AS_TRIGGER(fcinfo))
1824  retval = PointerGetDatum(plperl_trigger_handler(fcinfo));
1825  else if (CALLED_AS_EVENT_TRIGGER(fcinfo))
1826  {
1828  retval = (Datum) 0;
1829  }
1830  else
1831  retval = plperl_func_handler(fcinfo);
1832  }
1833  PG_CATCH();
1834  {
1835  current_call_data = save_call_data;
1836  activate_interpreter(oldinterp);
1837  if (this_call_data.prodesc)
1838  decrement_prodesc_refcount(this_call_data.prodesc);
1839  PG_RE_THROW();
1840  }
1841  PG_END_TRY();
1842 
1843  current_call_data = save_call_data;
1844  activate_interpreter(oldinterp);
1845  if (this_call_data.prodesc)
1846  decrement_prodesc_refcount(this_call_data.prodesc);
1847  return retval;
1848 }
#define CALLED_AS_EVENT_TRIGGER(fcinfo)
Definition: event_trigger.h:40
static Datum plperl_func_handler(PG_FUNCTION_ARGS)
Definition: plperl.c:2377
#define decrement_prodesc_refcount(prodesc)
Definition: plperl.c:136
FunctionCallInfo fcinfo
Definition: plperl.c:181
#define PointerGetDatum(X)
Definition: postgres.h:562
#define MemSet(start, val, len)
Definition: c.h:846
static plperl_interp_desc * plperl_active_interp
Definition: plperl.c:229
static void plperl_event_trigger_handler(PG_FUNCTION_ARGS)
Definition: plperl.c:2602
static Datum plperl_trigger_handler(PG_FUNCTION_ARGS)
Definition: plperl.c:2489
static void activate_interpreter(plperl_interp_desc *interp_desc)
Definition: plperl.c:689
uintptr_t Datum
Definition: postgres.h:372
#define PG_CATCH()
Definition: elog.h:293
#define CALLED_AS_TRIGGER(fcinfo)
Definition: trigger.h:25
#define PG_RE_THROW()
Definition: elog.h:314
plperl_proc_desc * prodesc
Definition: plperl.c:180
#define PG_TRY()
Definition: elog.h:284
static plperl_call_data * current_call_data
Definition: plperl.c:245
#define PG_END_TRY()
Definition: elog.h:300
static void plperl_call_perl_event_trigger_func ( plperl_proc_desc desc,
FunctionCallInfo  fcinfo,
SV *  td 
)
static

Definition at line 2314 of file plperl.c.

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

Referenced by plperl_event_trigger_handler().

2317 {
2318  dTHX;
2319  dSP;
2320  SV *retval,
2321  *TDsv;
2322  int count;
2323 
2324  ENTER;
2325  SAVETMPS;
2326 
2327  TDsv = get_sv("main::_TD", 0);
2328  if (!TDsv)
2329  ereport(ERROR,
2330  (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
2331  errmsg("couldn't fetch $_TD")));
2332 
2333  save_item(TDsv); /* local $_TD */
2334  sv_setsv(TDsv, td);
2335 
2336  PUSHMARK(sp);
2337  PUTBACK;
2338 
2339  /* Do NOT use G_KEEPERR here */
2340  count = perl_call_sv(desc->reference, G_SCALAR | G_EVAL);
2341 
2342  SPAGAIN;
2343 
2344  if (count != 1)
2345  {
2346  PUTBACK;
2347  FREETMPS;
2348  LEAVE;
2349  ereport(ERROR,
2350  (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
2351  errmsg("didn't get a return item from trigger function")));
2352  }
2353 
2354  if (SvTRUE(ERRSV))
2355  {
2356  (void) POPs;
2357  PUTBACK;
2358  FREETMPS;
2359  LEAVE;
2360  /* XXX need to find a way to determine a better errcode here */
2361  ereport(ERROR,
2362  (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
2364  }
2365 
2366  retval = newSVsv(POPs);
2367  (void) retval; /* silence compiler warning */
2368 
2369  PUTBACK;
2370  FREETMPS;
2371  LEAVE;
2372 
2373  return;
2374 }
#define dTHX
Definition: ppport.h:3208
int errcode(int sqlerrcode)
Definition: elog.c:575
#define ERRSV
Definition: ppport.h:3859
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
SV * reference
Definition: plperl.c:114
static char * strip_trailing_ws(const char *msg)
Definition: plperl.c:1066
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define get_sv
Definition: ppport.h:3878
static char * sv2cstr(SV *sv)
static SV * plperl_call_perl_func ( plperl_proc_desc desc,
FunctionCallInfo  fcinfo 
)
static

Definition at line 2153 of file plperl.c.

References FunctionCallInfoData::arg, plperl_proc_desc::arg_arraytype, plperl_proc_desc::arg_is_rowtype, plperl_proc_desc::arg_out_func, FunctionCallInfoData::argnull, Assert, cstr2sv(), DatumGetPointer, dTHX, ereport, errcode(), errmsg(), ERROR, ERRSV, FunctionCallInfoData::flinfo, FmgrInfo::fn_oid, get_func_signature(), get_transform_fromsql(), i, 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(), and plperl_proc_desc::trftypes.

Referenced by plperl_func_handler(), and plperl_inline_handler().

2154 {
2155  dTHX;
2156  dSP;
2157  SV *retval;
2158  int i;
2159  int count;
2160  Oid *argtypes = NULL;
2161  int nargs = 0;
2162 
2163  ENTER;
2164  SAVETMPS;
2165 
2166  PUSHMARK(SP);
2167  EXTEND(sp, desc->nargs);
2168 
2169  /* Get signature for true functions; inline blocks have no args. */
2170  if (fcinfo->flinfo->fn_oid)
2171  get_func_signature(fcinfo->flinfo->fn_oid, &argtypes, &nargs);
2172  Assert(nargs == desc->nargs);
2173 
2174  for (i = 0; i < desc->nargs; i++)
2175  {
2176  if (fcinfo->argnull[i])
2177  PUSHs(&PL_sv_undef);
2178  else if (desc->arg_is_rowtype[i])
2179  {
2180  SV *sv = plperl_hash_from_datum(fcinfo->arg[i]);
2181 
2182  PUSHs(sv_2mortal(sv));
2183  }
2184  else
2185  {
2186  SV *sv;
2187  Oid funcid;
2188 
2189  if (OidIsValid(desc->arg_arraytype[i]))
2190  sv = plperl_ref_from_pg_array(fcinfo->arg[i], desc->arg_arraytype[i]);
2192  sv = (SV *) DatumGetPointer(OidFunctionCall1(funcid, fcinfo->arg[i]));
2193  else
2194  {
2195  char *tmp;
2196 
2197  tmp = OutputFunctionCall(&(desc->arg_out_func[i]),
2198  fcinfo->arg[i]);
2199  sv = cstr2sv(tmp);
2200  pfree(tmp);
2201  }
2202 
2203  PUSHs(sv_2mortal(sv));
2204  }
2205  }
2206  PUTBACK;
2207 
2208  /* Do NOT use G_KEEPERR here */
2209  count = perl_call_sv(desc->reference, G_SCALAR | G_EVAL);
2210 
2211  SPAGAIN;
2212 
2213  if (count != 1)
2214  {
2215  PUTBACK;
2216  FREETMPS;
2217  LEAVE;
2218  ereport(ERROR,
2219  (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
2220  errmsg("didn't get a return item from function")));
2221  }
2222 
2223  if (SvTRUE(ERRSV))
2224  {
2225  (void) POPs;
2226  PUTBACK;
2227  FREETMPS;
2228  LEAVE;
2229  /* XXX need to find a way to determine a better errcode here */
2230  ereport(ERROR,
2231  (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
2233  }
2234 
2235  retval = newSVsv(POPs);
2236 
2237  PUTBACK;
2238  FREETMPS;
2239  LEAVE;
2240 
2241  return retval;
2242 }
static SV * plperl_ref_from_pg_array(Datum arg, Oid typid)
Definition: plperl.c:1448
Oid get_transform_fromsql(Oid typid, Oid langid, List *trftypes)
Definition: lsyscache.c:1872
List * trftypes
Definition: plperl.c:118
bool * arg_is_rowtype
Definition: plperl.c:130
#define dTHX
Definition: ppport.h:3208
Oid get_func_signature(Oid funcid, Oid **argtypes, int *nargs)
Definition: lsyscache.c:1500
#define PL_sv_undef
Definition: ppport.h:4129
int errcode(int sqlerrcode)
Definition: elog.c:575
#define ERRSV
Definition: ppport.h:3859
static SV * plperl_hash_from_datum(Datum attr)
Definition: plperl.c:2972
unsigned int Oid
Definition: postgres_ext.h:31
FmgrInfo * arg_out_func
Definition: plperl.c:129
#define OidIsValid(objectId)
Definition: c.h:532
char * OutputFunctionCall(FmgrInfo *flinfo, Datum val)
Definition: fmgr.c:1667
FmgrInfo * flinfo
Definition: fmgr.h:79
void pfree(void *pointer)
Definition: mcxt.c:949
#define ERROR
Definition: elog.h:43
#define OidFunctionCall1(functionId, arg1)
Definition: fmgr.h:623
bool argnull[FUNC_MAX_ARGS]
Definition: fmgr.h:86
#define ereport(elevel, rest)
Definition: elog.h:122
Oid * arg_arraytype
Definition: plperl.c:131
static SV * cstr2sv(const char *str)
Oid fn_oid
Definition: fmgr.h:59
Datum arg[FUNC_MAX_ARGS]
Definition: fmgr.h:85
#define Assert(condition)
Definition: c.h:664
SV * reference
Definition: plperl.c:114
static char * strip_trailing_ws(const char *msg)
Definition: plperl.c:1066
#define DatumGetPointer(X)
Definition: postgres.h:555
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
plperl_proc_desc * prodesc
Definition: plperl.c:180
static plperl_call_data * current_call_data
Definition: plperl.c:245
static char * sv2cstr(SV *sv)
static SV* plperl_call_perl_trigger_func ( plperl_proc_desc desc,
FunctionCallInfo  fcinfo,
SV *  td 
)
static

Definition at line 2246 of file plperl.c.

References FunctionCallInfoData::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().

2248 {
2249  dTHX;
2250  dSP;
2251  SV *retval,
2252  *TDsv;
2253  int i,
2254  count;
2255  Trigger *tg_trigger = ((TriggerData *) fcinfo->context)->tg_trigger;
2256 
2257  ENTER;
2258  SAVETMPS;
2259 
2260  TDsv = get_sv("main::_TD", 0);
2261  if (!TDsv)
2262  ereport(ERROR,
2263  (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
2264  errmsg("couldn't fetch $_TD")));
2265 
2266  save_item(TDsv); /* local $_TD */
2267  sv_setsv(TDsv, td);
2268 
2269  PUSHMARK(sp);
2270  EXTEND(sp, tg_trigger->tgnargs);
2271 
2272  for (i = 0; i < tg_trigger->tgnargs; i++)
2273  PUSHs(sv_2mortal(cstr2sv(tg_trigger->tgargs[i])));
2274  PUTBACK;
2275 
2276  /* Do NOT use G_KEEPERR here */
2277  count = perl_call_sv(desc->reference, G_SCALAR | G_EVAL);
2278 
2279  SPAGAIN;
2280 
2281  if (count != 1)
2282  {
2283  PUTBACK;
2284  FREETMPS;
2285  LEAVE;
2286  ereport(ERROR,
2287  (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
2288  errmsg("didn't get a return item from trigger function")));
2289  }
2290 
2291  if (SvTRUE(ERRSV))
2292  {
2293  (void) POPs;
2294  PUTBACK;
2295  FREETMPS;
2296  LEAVE;
2297  /* XXX need to find a way to determine a better errcode here */
2298  ereport(ERROR,
2299  (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
2301  }
2302 
2303  retval = newSVsv(POPs);
2304 
2305  PUTBACK;
2306  FREETMPS;
2307  LEAVE;
2308 
2309  return retval;
2310 }
#define dTHX
Definition: ppport.h:3208
fmNodePtr context
Definition: fmgr.h:80
int errcode(int sqlerrcode)
Definition: elog.c:575
#define ERRSV
Definition: ppport.h:3859
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
char ** tgargs
Definition: reltrigger.h:40
static SV * cstr2sv(const char *str)
SV * reference
Definition: plperl.c:114
static char * strip_trailing_ws(const char *msg)
Definition: plperl.c:1066
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define get_sv
Definition: ppport.h:3878
int i
int16 tgnargs
Definition: reltrigger.h:37
static char * sv2cstr(SV *sv)
static void plperl_compile_callback ( void *  arg)
static

Definition at line 4018 of file plperl.c.

References errcontext.

Referenced by compile_plperl_function().

4019 {
4020  char *procname = (char *) arg;
4021 
4022  if (procname)
4023  errcontext("compilation of PL/Perl function \"%s\"", procname);
4024 }
#define errcontext
Definition: elog.h:164
void * arg
static void plperl_create_sub ( plperl_proc_desc desc,
char *  s,
Oid  fn_oid 
)
static

Definition at line 2066 of file plperl.c.

References 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, strip_trailing_ws(), and sv2cstr().

Referenced by compile_plperl_function(), and plperl_inline_handler().

2067 {
2068  dTHX;
2069  dSP;
2070  char subname[NAMEDATALEN + 40];
2071  HV *pragma_hv = newHV();
2072  SV *subref = NULL;
2073  int count;
2074 
2075  sprintf(subname, "%s__%u", prodesc->proname, fn_oid);
2076 
2077  if (plperl_use_strict)
2078  hv_store_string(pragma_hv, "strict", (SV *) newAV());
2079 
2080  ENTER;
2081  SAVETMPS;
2082  PUSHMARK(SP);
2083  EXTEND(SP, 4);
2084  PUSHs(sv_2mortal(cstr2sv(subname)));
2085  PUSHs(sv_2mortal(newRV_noinc((SV *) pragma_hv)));
2086 
2087  /*
2088  * Use 'false' for $prolog in mkfunc, which is kept for compatibility in
2089  * case a module such as PostgreSQL::PLPerl::NYTprof replaces the function
2090  * compiler.
2091  */
2092  PUSHs(&PL_sv_no);
2093  PUSHs(sv_2mortal(cstr2sv(s)));
2094  PUTBACK;
2095 
2096  /*
2097  * G_KEEPERR seems to be needed here, else we don't recognize compile
2098  * errors properly. Perhaps it's because there's another level of eval
2099  * inside mksafefunc?
2100  */
2101  count = perl_call_pv("PostgreSQL::InServer::mkfunc",
2102  G_SCALAR | G_EVAL | G_KEEPERR);
2103  SPAGAIN;
2104 
2105  if (count == 1)
2106  {
2107  SV *sub_rv = (SV *) POPs;
2108 
2109  if (sub_rv && SvROK(sub_rv) && SvTYPE(SvRV(sub_rv)) == SVt_PVCV)
2110  {
2111  subref = newRV_inc(SvRV(sub_rv));
2112  }
2113  }
2114 
2115  PUTBACK;
2116  FREETMPS;
2117  LEAVE;
2118 
2119  if (SvTRUE(ERRSV))
2120  ereport(ERROR,
2121  (errcode(ERRCODE_SYNTAX_ERROR),
2123 
2124  if (!subref)
2125  ereport(ERROR,
2126  (errcode(ERRCODE_SYNTAX_ERROR),
2127  errmsg("didn't get a CODE reference from compiling function \"%s\"",
2128  prodesc->proname)));
2129 
2130  prodesc->reference = subref;
2131 
2132  return;
2133 }
#define dTHX
Definition: ppport.h:3208
int errcode(int sqlerrcode)
Definition: elog.c:575
#define ERRSV
Definition: ppport.h:3859
static SV ** hv_store_string(HV *hv, const char *key, SV *val)
Definition: plperl.c:3956
#define NAMEDATALEN
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
#define newRV_noinc(a)
Definition: ppport.h:4456
#define newRV_inc(sv)
Definition: ppport.h:4442
static SV * cstr2sv(const char *str)
static bool plperl_use_strict
Definition: plperl.c:235
static char * strip_trailing_ws(const char *msg)
Definition: plperl.c:1066
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define PL_sv_no
Definition: ppport.h:4128
static char * sv2cstr(SV *sv)
static void plperl_destroy_interp ( PerlInterpreter **  interp)
static

Definition at line 923 of file plperl.c.

References dTHX, and PERL_UNUSED_VAR.

Referenced by plperl_fini().

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

Definition at line 1706 of file plperl.c.

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

Referenced by plperl_event_trigger_handler().

1707 {
1708  dTHX;
1709  EventTriggerData *tdata;
1710  HV *hv;
1711 
1712  hv = newHV();
1713 
1714  tdata = (EventTriggerData *) fcinfo->context;
1715 
1716  hv_store_string(hv, "event", cstr2sv(tdata->event));
1717  hv_store_string(hv, "tag", cstr2sv(tdata->tag));
1718 
1719  return newRV_noinc((SV *) hv);
1720 }
#define dTHX
Definition: ppport.h:3208
fmNodePtr context
Definition: fmgr.h:80
const char * tag
Definition: event_trigger.h:28
static SV ** hv_store_string(HV *hv, const char *key, SV *val)
Definition: plperl.c:3956
const char * event
Definition: event_trigger.h:26
#define newRV_noinc(a)
Definition: ppport.h:4456
static SV * cstr2sv(const char *str)
static void plperl_event_trigger_handler ( PG_FUNCTION_ARGS  )
static

Definition at line 2602 of file plperl.c.

References activate_interpreter(), ErrorContextCallback::arg, ErrorContextCallback::callback, compile_plperl_function(), 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_CONNECT, SPI_OK_FINISH, and SvREFCNT_dec_current().

Referenced by plperl_call_handler().

2603 {
2604  plperl_proc_desc *prodesc;
2605  SV *svTD;
2606  ErrorContextCallback pl_error_context;
2607 
2608  /* Connect to SPI manager */
2609  if (SPI_connect() != SPI_OK_CONNECT)
2610  elog(ERROR, "could not connect to SPI manager");
2611 
2612  /* Find or compile the function */
2613  prodesc = compile_plperl_function(fcinfo->flinfo->fn_oid, false, true);
2614  current_call_data->prodesc = prodesc;
2615  increment_prodesc_refcount(prodesc);
2616 
2617  /* Set a callback for error reporting */
2618  pl_error_context.callback = plperl_exec_callback;
2619  pl_error_context.previous = error_context_stack;
2620  pl_error_context.arg = prodesc->proname;
2621  error_context_stack = &pl_error_context;
2622 
2623  activate_interpreter(prodesc->interp);
2624 
2625  svTD = plperl_event_trigger_build_args(fcinfo);
2626  plperl_call_perl_event_trigger_func(prodesc, fcinfo, svTD);
2627 
2628  if (SPI_finish() != SPI_OK_FINISH)
2629  elog(ERROR, "SPI_finish() failed");
2630 
2631  /* Restore the previous error callback */
2632  error_context_stack = pl_error_context.previous;
2633 
2634  SvREFCNT_dec_current(svTD);
2635 }
#define SPI_OK_CONNECT
Definition: spi.h:50
int SPI_connect(void)
Definition: spi.c:84
int SPI_finish(void)
Definition: spi.c:148
struct ErrorContextCallback * previous
Definition: elog.h:238
static void plperl_call_perl_event_trigger_func(plperl_proc_desc *desc, FunctionCallInfo fcinfo, SV *td)
Definition: plperl.c:2314
ErrorContextCallback * error_context_stack
Definition: elog.c:88
#define ERROR
Definition: elog.h:43
static plperl_proc_desc * compile_plperl_function(Oid fn_oid, bool is_trigger, bool is_event_trigger)
Definition: plperl.c:2686
static void activate_interpreter(plperl_interp_desc *interp_desc)
Definition: plperl.c:689
static void plperl_exec_callback(void *arg)
Definition: plperl.c:4006
#define increment_prodesc_refcount(prodesc)
Definition: plperl.c:134
static void SvREFCNT_dec_current(SV *sv)
Definition: plperl.c:314
#define SPI_OK_FINISH
Definition: spi.h:51
static SV * plperl_event_trigger_build_args(FunctionCallInfo fcinfo)
Definition: plperl.c:1706
void(* callback)(void *arg)
Definition: elog.h:239
char * proname
Definition: plperl.c:109
plperl_proc_desc * prodesc
Definition: plperl.c:180
#define elog
Definition: elog.h:219
plperl_interp_desc * interp
Definition: plperl.c:115
static plperl_call_data * current_call_data
Definition: plperl.c:245
static void plperl_exec_callback ( void *  arg)
static

Definition at line 4006 of file plperl.c.

References errcontext.

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

4007 {
4008  char *procname = (char *) arg;
4009 
4010  if (procname)
4011  errcontext("PL/Perl function \"%s\"", procname);
4012 }
#define errcontext
Definition: elog.h:164
void * arg
static void plperl_fini ( int  code,
Datum  arg 
)
static

Definition at line 513 of file plperl.c.

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

Referenced by select_perl_context().

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

Definition at line 2377 of file plperl.c.

References activate_interpreter(), ReturnSetInfo::allowedModes, ErrorContextCallback::arg, ErrorContextCallback::callback, compile_plperl_function(), dTHX, elog, ereport, errcode(), errmsg(), ERROR, error_context_stack, ReturnSetInfo::expectedDesc, ExprEndResult, FALSE, plperl_proc_desc::fn_retisset, get_perl_array_ref(), i, 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(), SPI_finish(), SPI_OK_CONNECT, SPI_OK_FINISH, SvREFCNT_dec_current(), and plperl_call_data::tuple_store.

Referenced by plperl_call_handler().

2378 {
2379  plperl_proc_desc *prodesc;
2380  SV *perlret;
2381  Datum retval = 0;
2382  ReturnSetInfo *rsi;
2383  ErrorContextCallback pl_error_context;
2384 
2385  if (SPI_connect() != SPI_OK_CONNECT)
2386  elog(ERROR, "could not connect to SPI manager");
2387 
2388  prodesc = compile_plperl_function(fcinfo->flinfo->fn_oid, false, false);
2389  current_call_data->prodesc = prodesc;
2390  increment_prodesc_refcount(prodesc);
2391 
2392  /* Set a callback for error reporting */
2393  pl_error_context.callback = plperl_exec_callback;
2394  pl_error_context.previous = error_context_stack;
2395  pl_error_context.arg = prodesc->proname;
2396  error_context_stack = &pl_error_context;
2397 
2398  rsi = (ReturnSetInfo *) fcinfo->resultinfo;
2399 
2400  if (prodesc->fn_retisset)
2401  {
2402  /* Check context before allowing the call to go through */
2403  if (!rsi || !IsA(rsi, ReturnSetInfo) ||
2404  (rsi->allowedModes & SFRM_Materialize) == 0 ||
2405  rsi->expectedDesc == NULL)
2406  ereport(ERROR,
2407  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2408  errmsg("set-valued function called in context that "
2409  "cannot accept a set")));
2410  }
2411 
2412  activate_interpreter(prodesc->interp);
2413 
2414  perlret = plperl_call_perl_func(prodesc, fcinfo);
2415 
2416  /************************************************************
2417  * Disconnect from SPI manager and then create the return
2418  * values datum (if the input function does a palloc for it
2419  * this must not be allocated in the SPI memory context
2420  * because SPI_finish would free it).
2421  ************************************************************/
2422  if (SPI_finish() != SPI_OK_FINISH)
2423  elog(ERROR, "SPI_finish() failed");
2424 
2425  if (prodesc->fn_retisset)
2426  {
2427  SV *sav;
2428 
2429  /*
2430  * If the Perl function returned an arrayref, we pretend that it
2431  * called return_next() for each element of the array, to handle old
2432  * SRFs that didn't know about return_next(). Any other sort of return
2433  * value is an error, except undef which means return an empty set.
2434  */
2435  sav = get_perl_array_ref(perlret);
2436  if (sav)
2437  {
2438  dTHX;
2439  int i = 0;
2440  SV **svp = 0;
2441  AV *rav = (AV *) SvRV(sav);
2442 
2443  while ((svp = av_fetch(rav, i, FALSE)) != NULL)
2444  {
2446  i++;
2447  }
2448  }
2449  else if (SvOK(perlret))
2450  {
2451  ereport(ERROR,
2452  (errcode(ERRCODE_DATATYPE_MISMATCH),
2453  errmsg("set-returning PL/Perl function must return "
2454  "reference to array or use return_next")));
2455  }
2456 
2459  {
2462  }
2463  retval = (Datum) 0;
2464  }
2465  else
2466  {
2467  retval = plperl_sv_to_datum(perlret,
2468  prodesc->result_oid,
2469  -1,
2470  fcinfo,
2471  &prodesc->result_in_func,
2472  prodesc->result_typioparam,
2473  &fcinfo->isnull);
2474 
2475  if (fcinfo->isnull && rsi && IsA(rsi, ReturnSetInfo))
2476  rsi->isDone = ExprEndResult;
2477  }
2478 
2479  /* Restore the previous error callback */
2480  error_context_stack = pl_error_context.previous;
2481 
2482  SvREFCNT_dec_current(perlret);
2483 
2484  return retval;
2485 }
#define SPI_OK_CONNECT
Definition: spi.h:50
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
static SV * get_perl_array_ref(SV *sv)
Definition: plperl.c:1143
static Datum plperl_sv_to_datum(SV *sv, Oid typid, int32 typmod, FunctionCallInfo fcinfo, FmgrInfo *finfo, Oid typioparam, bool *isnull)
Definition: plperl.c:1312
#define dTHX
Definition: ppport.h:3208
int SPI_connect(void)
Definition: spi.c:84
int SPI_finish(void)
Definition: spi.c:148
int errcode(int sqlerrcode)
Definition: elog.c:575
struct ErrorContextCallback * previous
Definition: elog.h:238
ErrorContextCallback * error_context_stack
Definition: elog.c:88
TupleDesc expectedDesc
Definition: execnodes.h:267
bool fn_retisset
Definition: plperl.c:121
#define ERROR
Definition: elog.h:43
#define FALSE
Definition: c.h:219
FmgrInfo result_in_func
Definition: plperl.c:125
static plperl_proc_desc * compile_plperl_function(Oid fn_oid, bool is_trigger, bool is_event_trigger)
Definition: plperl.c:2686
static void activate_interpreter(plperl_interp_desc *interp_desc)
Definition: plperl.c:689
static void plperl_exec_callback(void *arg)
Definition: plperl.c:4006
#define increment_prodesc_refcount(prodesc)
Definition: plperl.c:134
Oid result_typioparam
Definition: plperl.c:126
#define ereport(elevel, rest)
Definition: elog.h:122
static void plperl_return_next_internal(SV *sv)
Definition: plperl.c:3225
uintptr_t Datum
Definition: postgres.h:372
Tuplestorestate * tuple_store
Definition: plperl.c:182
static void SvREFCNT_dec_current(SV *sv)
Definition: plperl.c:314
int allowedModes
Definition: execnodes.h:268
TupleDesc ret_tdesc
Definition: plperl.c:183
SetFunctionReturnMode returnMode
Definition: execnodes.h:270
#define SPI_OK_FINISH
Definition: spi.h:51
Tuplestorestate * setResult
Definition: execnodes.h:273
TupleDesc setDesc
Definition: execnodes.h:274
void(* callback)(void *arg)
Definition: elog.h:239
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
char * proname
Definition: plperl.c:109
plperl_proc_desc * prodesc
Definition: plperl.c:180
#define elog
Definition: elog.h:219
ExprDoneCond isDone
Definition: execnodes.h:271
plperl_interp_desc * interp
Definition: plperl.c:115
static plperl_call_data * current_call_data
Definition: plperl.c:245
static SV * plperl_call_perl_func(plperl_proc_desc *desc, FunctionCallInfo fcinfo)
Definition: plperl.c:2153
static SV * plperl_hash_from_datum ( Datum  attr)
static

Definition at line 2972 of file plperl.c.

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

2973 {
2974  HeapTupleHeader td;
2975  Oid tupType;
2976  int32 tupTypmod;
2977  TupleDesc tupdesc;
2978  HeapTupleData tmptup;
2979  SV *sv;
2980 
2981  td = DatumGetHeapTupleHeader(attr);
2982 
2983  /* Extract rowtype info and find a tupdesc */
2984  tupType = HeapTupleHeaderGetTypeId(td);
2985  tupTypmod = HeapTupleHeaderGetTypMod(td);
2986  tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
2987 
2988  /* Build a temporary HeapTuple control structure */
2989  tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
2990  tmptup.t_data = td;
2991 
2992  sv = plperl_hash_from_tuple(&tmptup, tupdesc);
2993  ReleaseTupleDesc(tupdesc);
2994 
2995  return sv;
2996 }
TupleDesc lookup_rowtype_tupdesc(Oid type_id, int32 typmod)
Definition: typcache.c:1486
unsigned int Oid
Definition: postgres_ext.h:31
#define DatumGetHeapTupleHeader(X)
Definition: fmgr.h:259
signed int int32
Definition: c.h:246
HeapTupleHeader t_data
Definition: htup.h:67
#define HeapTupleHeaderGetTypMod(tup)
Definition: htup_details.h:455
uint32 t_len
Definition: htup.h:64
static SV * plperl_hash_from_tuple(HeapTuple tuple, TupleDesc tupdesc)
Definition: plperl.c:3000
#define HeapTupleHeaderGetTypeId(tup)
Definition: htup_details.h:445
#define ReleaseTupleDesc(tupdesc)
Definition: tupdesc.h:115
#define HeapTupleHeaderGetDatumLength(tup)
Definition: htup_details.h:439
static SV * plperl_hash_from_tuple ( HeapTuple  tuple,
TupleDesc  tupdesc 
)
static

Definition at line 3000 of file plperl.c.

References check_stack_depth(), cstr2sv(), DatumGetPointer, dTHX, get_base_element_type(), get_transform_fromsql(), getTypeOutputInfo(), heap_getattr, hv_store_string(), i, plperl_proc_desc::lang_oid, NameStr, tupleDesc::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().

3001 {
3002  dTHX;
3003  HV *hv;
3004  int i;
3005 
3006  /* since this function recurses, it could be driven to stack overflow */
3008 
3009  hv = newHV();
3010  hv_ksplit(hv, tupdesc->natts); /* pre-grow the hash */
3011 
3012  for (i = 0; i < tupdesc->natts; i++)
3013  {
3014  Datum attr;
3015  bool isnull,
3016  typisvarlena;
3017  char *attname;
3018  Oid typoutput;
3019  Form_pg_attribute att = TupleDescAttr(tupdesc, i);
3020 
3021  if (att->attisdropped)
3022  continue;
3023 
3024  attname = NameStr(att->attname);
3025  attr = heap_getattr(tuple, i + 1, tupdesc, &isnull);
3026 
3027  if (isnull)
3028  {
3029  /*
3030  * Store (attname => undef) and move on. Note we can't use
3031  * &PL_sv_undef here; see "AVs, HVs and undefined values" in
3032  * perlguts for an explanation.
3033  */
3034  hv_store_string(hv, attname, newSV(0));
3035  continue;
3036  }
3037 
3038  if (type_is_rowtype(att->atttypid))
3039  {
3040  SV *sv = plperl_hash_from_datum(attr);
3041 
3042  hv_store_string(hv, attname, sv);
3043  }
3044  else
3045  {
3046  SV *sv;
3047  Oid funcid;
3048 
3049  if (OidIsValid(get_base_element_type(att->atttypid)))
3050  sv = plperl_ref_from_pg_array(attr, att->atttypid);
3052  sv = (SV *) DatumGetPointer(OidFunctionCall1(funcid, attr));
3053  else
3054  {
3055  char *outputstr;
3056 
3057  /* XXX should have a way to cache these lookups */
3058  getTypeOutputInfo(att->atttypid, &typoutput, &typisvarlena);
3059 
3060  outputstr = OidOutputFunctionCall(typoutput, attr);
3061  sv = cstr2sv(outputstr);
3062  pfree(outputstr);
3063  }
3064 
3065  hv_store_string(hv, attname, sv);
3066  }
3067  }
3068  return newRV_noinc((SV *) hv);
3069 }
static SV * plperl_ref_from_pg_array(Datum arg, Oid typid)
Definition: plperl.c:1448
Oid get_transform_fromsql(Oid typid, Oid langid, List *trftypes)
Definition: lsyscache.c:1872
List * trftypes
Definition: plperl.c:118
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:2632
#define dTHX
Definition: ppport.h:3208
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:84
static SV * plperl_hash_from_datum(Datum attr)
Definition: plperl.c:2972
static SV ** hv_store_string(HV *hv, const char *key, SV *val)
Definition: plperl.c:3956
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:532
int natts
Definition: tupdesc.h:73
void pfree(void *pointer)
Definition: mcxt.c:949
#define OidFunctionCall1(functionId, arg1)
Definition: fmgr.h:623
void check_stack_depth(void)
Definition: postgres.c:3144
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:187
bool type_is_rowtype(Oid typid)
Definition: lsyscache.c:2404
#define heap_getattr(tup, attnum, tupleDesc, isnull)
Definition: htup_details.h:769
#define newRV_noinc(a)
Definition: ppport.h:4456
uintptr_t Datum
Definition: postgres.h:372
static SV * cstr2sv(const char *str)
#define DatumGetPointer(X)
Definition: postgres.h:555
Oid get_base_element_type(Oid typid)
Definition: lsyscache.c:2557
char * OidOutputFunctionCall(Oid functionId, Datum val)
Definition: fmgr.c:1747
int i
#define NameStr(name)
Definition: c.h:493
plperl_proc_desc * prodesc
Definition: plperl.c:180
static plperl_call_data * current_call_data
Definition: plperl.c:245
static Datum plperl_hash_to_datum ( SV *  src,
TupleDesc  td 
)
static

Definition at line 1131 of file plperl.c.

References HeapTupleGetDatum, and plperl_build_tuple_result().

Referenced by plperl_sv_to_datum().

1132 {
1133  HeapTuple tup = plperl_build_tuple_result((HV *) SvRV(src), td);
1134 
1135  return HeapTupleGetDatum(tup);
1136 }
#define HeapTupleGetDatum(tuple)
Definition: funcapi.h:222
static HeapTuple plperl_build_tuple_result(HV *perlhash, TupleDesc td)
Definition: plperl.c:1080
static PerlInterpreter * plperl_init_interp ( void  )
static

Definition at line 710 of file plperl.c.

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(), strip_trailing_ws(), and sv2cstr().

Referenced by _PG_init(), and select_perl_context().

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

Definition at line 2141 of file plperl.c.

References boot_DynaLoader(), and boot_PostgreSQL__InServer__Util().

Referenced by plperl_init_interp().

2142 {
2143  char *file = __FILE__;
2144 
2145  newXS("DynaLoader::boot_DynaLoader", boot_DynaLoader, file);
2146  newXS("PostgreSQL::InServer::Util::bootstrap",
2148  /* newXS for...::SPI::bootstrap is in select_perl_context() */
2149 }
EXTERN_C void boot_DynaLoader(pTHX_ CV *cv)
EXTERN_C void boot_PostgreSQL__InServer__Util(pTHX_ CV *cv)
static void plperl_inline_callback ( void *  arg)
static

Definition at line 4030 of file plperl.c.

References errcontext.

Referenced by plperl_inline_handler().

4031 {
4032  errcontext("PL/Perl anonymous code block");
4033 }
#define errcontext
Definition: elog.h:164
Datum plperl_inline_handler ( PG_FUNCTION_ARGS  )

Definition at line 1856 of file plperl.c.

References activate_interpreter(), ErrorContextCallback::arg, ErrorContextCallback::callback, current_call_data, CurrentMemoryContext, elog, ERROR, error_context_stack, plperl_call_data::fcinfo, FunctionCallInfoData::flinfo, 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, MemSet, plperl_proc_desc::nargs, NIL, PG_CATCH, PG_END_TRY, PG_GETARG_POINTER, PG_RE_THROW, 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(), InlineCodeBlock::source_text, SPI_connect(), SPI_finish(), SPI_OK_CONNECT, SPI_OK_FINISH, SvREFCNT_dec_current(), plperl_proc_desc::trftypes, and VOIDOID.

Referenced by plperlu_inline_handler().

1857 {
1859  FunctionCallInfoData fake_fcinfo;
1860  FmgrInfo flinfo;
1861  plperl_proc_desc desc;
1862  plperl_call_data *volatile save_call_data = current_call_data;
1863  plperl_interp_desc *volatile oldinterp = plperl_active_interp;
1864  plperl_call_data this_call_data;
1865  ErrorContextCallback pl_error_context;
1866 
1867  /* Initialize current-call status record */
1868  MemSet(&this_call_data, 0, sizeof(this_call_data));
1869 
1870  /* Set up a callback for error reporting */
1871  pl_error_context.callback = plperl_inline_callback;
1872  pl_error_context.previous = error_context_stack;
1873  pl_error_context.arg = NULL;
1874  error_context_stack = &pl_error_context;
1875 
1876  /*
1877  * Set up a fake fcinfo and descriptor with just enough info to satisfy
1878  * plperl_call_perl_func(). In particular note that this sets things up
1879  * with no arguments passed, and a result type of VOID.
1880  */
1881  MemSet(&fake_fcinfo, 0, sizeof(fake_fcinfo));
1882  MemSet(&flinfo, 0, sizeof(flinfo));
1883  MemSet(&desc, 0, sizeof(desc));
1884  fake_fcinfo.flinfo = &flinfo;
1885  flinfo.fn_oid = InvalidOid;
1886  flinfo.fn_mcxt = CurrentMemoryContext;
1887 
1888  desc.proname = "inline_code_block";
1889  desc.fn_readonly = false;
1890 
1891  desc.lang_oid = codeblock->langOid;
1892  desc.trftypes = NIL;
1893  desc.lanpltrusted = codeblock->langIsTrusted;
1894 
1895  desc.fn_retistuple = false;
1896  desc.fn_retisset = false;
1897  desc.fn_retisarray = false;
1898  desc.result_oid = VOIDOID;
1899  desc.nargs = 0;
1900  desc.reference = NULL;
1901 
1902  this_call_data.fcinfo = &fake_fcinfo;
1903  this_call_data.prodesc = &desc;
1904  /* we do not bother with refcounting the fake prodesc */
1905 
1906  PG_TRY();
1907  {
1908  SV *perlret;
1909 
1910  current_call_data = &this_call_data;
1911 
1912  if (SPI_connect() != SPI_OK_CONNECT)
1913  elog(ERROR, "could not connect to SPI manager");
1914 
1916 
1917  plperl_create_sub(&desc, codeblock->source_text, 0);
1918 
1919  if (!desc.reference) /* can this happen? */
1920  elog(ERROR, "could not create internal procedure for anonymous code block");
1921 
1922  perlret = plperl_call_perl_func(&desc, &fake_fcinfo);
1923 
1924  SvREFCNT_dec_current(perlret);
1925 
1926  if (SPI_finish() != SPI_OK_FINISH)
1927  elog(ERROR, "SPI_finish() failed");
1928  }
1929  PG_CATCH();
1930  {
1931  if (desc.reference)
1933  current_call_data = save_call_data;
1934  activate_interpreter(oldinterp);
1935  PG_RE_THROW();
1936  }
1937  PG_END_TRY();
1938 
1939  if (desc.reference)
1941 
1942  current_call_data = save_call_data;
1943  activate_interpreter(oldinterp);
1944 
1945  error_context_stack = pl_error_context.previous;
1946 
1947  PG_RETURN_VOID();
1948 }
#define NIL
Definition: pg_list.h:69
#define SPI_OK_CONNECT
Definition: spi.h:50
Definition: fmgr.h:56
List * trftypes
Definition: plperl.c:118
MemoryContext fn_mcxt
Definition: fmgr.h:65
FunctionCallInfo fcinfo
Definition: plperl.c:181
static void select_perl_context(bool trusted)
Definition: plperl.c:557
int SPI_connect(void)
Definition: spi.c:84
int SPI_finish(void)
Definition: spi.c:148
#define MemSet(start, val, len)
Definition: c.h:846
static plperl_interp_desc * plperl_active_interp
Definition: plperl.c:229
#define PG_GETARG_POINTER(n)
Definition: fmgr.h:241
struct ErrorContextCallback * previous
Definition: elog.h:238
ErrorContextCallback * error_context_stack
Definition: elog.c:88
FmgrInfo * flinfo
Definition: fmgr.h:79
bool fn_retisset
Definition: plperl.c:121
#define VOIDOID
Definition: pg_type.h:690
#define ERROR
Definition: elog.h:43
static void activate_interpreter(plperl_interp_desc *interp_desc)
Definition: plperl.c:689
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
static void SvREFCNT_dec_current(SV *sv)
Definition: plperl.c:314
#define InvalidOid
Definition: postgres_ext.h:36
Oid fn_oid
Definition: fmgr.h:59
static void plperl_create_sub(plperl_proc_desc *desc, char *s, Oid fn_oid)
Definition: plperl.c:2066
bool fn_readonly
Definition: plperl.c:116
static void plperl_inline_callback(void *arg)
Definition: plperl.c:4030
#define PG_RETURN_VOID()
Definition: fmgr.h:309
#define PG_CATCH()
Definition: elog.h:293
SV * reference
Definition: plperl.c:114
#define SPI_OK_FINISH
Definition: spi.h:51
#define PG_RE_THROW()
Definition: elog.h:314
void(* callback)(void *arg)
Definition: elog.h:239
bool fn_retistuple
Definition: plperl.c:120
char * proname
Definition: plperl.c:109
char * source_text
Definition: parsenodes.h:2790
plperl_proc_desc * prodesc
Definition: plperl.c:180
#define elog
Definition: elog.h:219
#define PG_TRY()
Definition: elog.h:284
static plperl_call_data * current_call_data
Definition: plperl.c:245
#define PG_END_TRY()
Definition: elog.h:300
bool lanpltrusted
Definition: plperl.c:119
static SV * plperl_call_perl_func(plperl_proc_desc *desc, FunctionCallInfo fcinfo)
Definition: plperl.c:2153
bool fn_retisarray
Definition: plperl.c:122
static HeapTuple plperl_modify_tuple ( HV *  hvTD,
TriggerData tdata,
HeapTuple  otup 
)
static

Definition at line 1724 of file plperl.c.

References dTHX, ereport, errcode(), errmsg(), ERROR, heap_modify_tuple(), hek2cstr(), hv_fetch_string(), InvalidOid, tupleDesc::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().

1725 {
1726  dTHX;
1727  SV **svp;
1728  HV *hvNew;
1729  HE *he;
1730  HeapTuple rtup;
1731  TupleDesc tupdesc;
1732  int natts;
1733  Datum *modvalues;
1734  bool *modnulls;
1735  bool *modrepls;
1736 
1737  svp = hv_fetch_string(hvTD, "new");
1738  if (!svp)
1739  ereport(ERROR,
1740  (errcode(ERRCODE_UNDEFINED_COLUMN),
1741  errmsg("$_TD->{new} does not exist")));
1742  if (!SvOK(*svp) || !SvROK(*svp) || SvTYPE(SvRV(*svp)) != SVt_PVHV)
1743  ereport(ERROR,
1744  (errcode(ERRCODE_DATATYPE_MISMATCH),
1745  errmsg("$_TD->{new} is not a hash reference")));
1746  hvNew = (HV *) SvRV(*svp);
1747 
1748  tupdesc = tdata->tg_relation->rd_att;
1749  natts = tupdesc->natts;
1750 
1751  modvalues = (Datum *) palloc0(natts * sizeof(Datum));
1752  modnulls = (bool *) palloc0(natts * sizeof(bool));
1753  modrepls = (bool *) palloc0(natts * sizeof(bool));
1754 
1755  hv_iterinit(hvNew);
1756  while ((he = hv_iternext(hvNew)))
1757  {
1758  char *key = hek2cstr(he);
1759  SV *val = HeVAL(he);
1760  int attn = SPI_fnumber(tupdesc, key);
1761  Form_pg_attribute attr = TupleDescAttr(tupdesc, attn - 1);
1762 
1763  if (attn == SPI_ERROR_NOATTRIBUTE)
1764  ereport(ERROR,
1765  (errcode(ERRCODE_UNDEFINED_COLUMN),
1766  errmsg("Perl hash contains nonexistent column \"%s\"",
1767  key)));
1768  if (attn <= 0)
1769  ereport(ERROR,
1770  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1771  errmsg("cannot set system attribute \"%s\"",
1772  key)));
1773 
1774  modvalues[attn - 1] = plperl_sv_to_datum(val,
1775  attr->atttypid,
1776  attr->atttypmod,
1777  NULL,
1778  NULL,
1779  InvalidOid,
1780  &modnulls[attn - 1]);
1781  modrepls[attn - 1] = true;
1782 
1783  pfree(key);
1784  }
1785  hv_iterinit(hvNew);
1786 
1787  rtup = heap_modify_tuple(otup, tupdesc, modvalues, modnulls, modrepls);
1788 
1789  pfree(modvalues);
1790  pfree(modnulls);
1791  pfree(modrepls);
1792 
1793  return rtup;
1794 }
int SPI_fnumber(TupleDesc tupdesc, const char *fname)
Definition: spi.c:761
static char * hek2cstr(HE *he)
Definition: plperl.c:325
static Datum plperl_sv_to_datum(SV *sv, Oid typid, int32 typmod, FunctionCallInfo fcinfo, FmgrInfo *finfo, Oid typioparam, bool *isnull)
Definition: plperl.c:1312
#define dTHX
Definition: ppport.h:3208
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:84
int errcode(int sqlerrcode)
Definition: elog.c:575
static SV ** hv_fetch_string(HV *hv, const char *key)
Definition: plperl.c:3983
int natts
Definition: tupdesc.h:73
void pfree(void *pointer)
Definition: mcxt.c:949
#define ERROR
Definition: elog.h:43
#define SPI_ERROR_NOATTRIBUTE
Definition: spi.h:44
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:187
#define ereport(elevel, rest)
Definition: elog.h:122
void * palloc0(Size size)
Definition: mcxt.c:877
uintptr_t Datum
Definition: postgres.h:372
TupleDesc rd_att
Definition: rel.h:115
#define InvalidOid
Definition: postgres_ext.h:36
int errmsg(const char *fmt,...)
Definition: elog.c:797
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:794
long val
Definition: informix.c:689
Relation tg_relation
Definition: trigger.h:34
static SV * plperl_ref_from_pg_array ( Datum  arg,
Oid  typid 
)
static

Definition at line 1448 of file plperl.c.

References ARR_DIMS, ARR_ELEMTYPE, ARR_NDIM, av, 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, 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, and type_is_rowtype().

Referenced by plperl_call_perl_func(), and plperl_hash_from_tuple().

1449 {
1450  dTHX;
1452  Oid elementtype = ARR_ELEMTYPE(ar);
1453  int16 typlen;
1454  bool typbyval;
1455  char typalign,
1456  typdelim;
1457  Oid typioparam;
1458  Oid typoutputfunc;
1459  Oid transform_funcid;
1460  int i,
1461  nitems,
1462  *dims;
1463  plperl_array_info *info;
1464  SV *av;
1465  HV *hv;
1466 
1467  /*
1468  * Currently we make no effort to cache any of the stuff we look up here,
1469  * which is bad.
1470  */
1471  info = palloc0(sizeof(plperl_array_info));
1472 
1473  /* get element type information, including output conversion function */
1474  get_type_io_data(elementtype, IOFunc_output,
1475  &typlen, &typbyval, &typalign,
1476  &typdelim, &typioparam, &typoutputfunc);
1477 
1478  /* Check for a transform function */
1479  transform_funcid = get_transform_fromsql(elementtype,
1482 
1483  /* Look up transform or output function as appropriate */
1484  if (OidIsValid(transform_funcid))
1485  fmgr_info(transform_funcid, &info->transform_proc);
1486  else
1487  fmgr_info(typoutputfunc, &info->proc);
1488 
1489  info->elem_is_rowtype = type_is_rowtype(elementtype);
1490 
1491  /* Get the number and bounds of array dimensions */
1492  info->ndims = ARR_NDIM(ar);
1493  dims = ARR_DIMS(ar);
1494 
1495  /* No dimensions? Return an empty array */
1496  if (info->ndims == 0)
1497  {
1498  av = newRV_noinc((SV *) newAV());
1499  }
1500  else
1501  {
1502  deconstruct_array(ar, elementtype, typlen, typbyval,
1503  typalign, &info->elements, &info->nulls,
1504  &nitems);
1505 
1506  /* Get total number of elements in each dimension */
1507  info->nelems = palloc(sizeof(int) * info->ndims);
1508  info->nelems[0] = nitems;
1509  for (i = 1; i < info->ndims; i++)
1510  info->nelems[i] = info->nelems[i - 1] / dims[i - 1];
1511 
1512  av = split_array(info, 0, nitems, 0);
1513  }
1514 
1515  hv = newHV();
1516  (void) hv_store(hv, "array", 5, av, 0);
1517  (void) hv_store(hv, "typeoid", 7, newSVuv(typid), 0);
1518 
1519  return sv_bless(newRV_noinc((SV *) hv),
1520  gv_stashpv("PostgreSQL::InServer::ARRAY", 0));
1521 }
signed short int16
Definition: c.h:245
FmgrInfo transform_proc
Definition: plperl.c:220
Oid get_transform_fromsql(Oid typid, Oid langid, List *trftypes)
Definition: lsyscache.c:1872
List * trftypes
Definition: plperl.c:118
#define dTHX
Definition: ppport.h:3208
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:532
static SV * split_array(plperl_array_info *info, int first, int last, int nest)
Definition: plperl.c:1527
#define newSVuv(uv)
Definition: ppport.h:3596
#define ARR_DIMS(a)
Definition: array.h:275
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:127
bool type_is_rowtype(Oid typid)
Definition: lsyscache.c:2404
#define newRV_noinc(a)
Definition: ppport.h:4456
struct @18::@19 av[32]
void * palloc0(Size size)
Definition: mcxt.c:877
bool elem_is_rowtype
Definition: plperl.c:215
#define ARR_NDIM(a)
Definition: array.h:271
FmgrInfo proc
Definition: plperl.c:219
void deconstruct_array(ArrayType *array, Oid elmtype, int elmlen, bool elmbyval, char elmalign, Datum **elemsp, bool **nullsp, int *nelemsp)
Definition: arrayfuncs.c:3476
bool * nulls
Definition: plperl.c:217
void * palloc(Size size)
Definition: mcxt.c:848
int i
Datum * elements
Definition: plperl.c:216
void * arg
plperl_proc_desc * prodesc
Definition: plperl.c:180
static plperl_call_data * current_call_data
Definition: plperl.c:245
#define ARR_ELEMTYPE(a)
Definition: array.h:273
#define DatumGetArrayTypeP(X)
Definition: array.h:242
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:2075
void plperl_return_next ( SV *  sv)

Definition at line 3197 of file plperl.c.

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

3198 {
3199  MemoryContext oldcontext = CurrentMemoryContext;
3200 
3201  PG_TRY();
3202  {
3204  }
3205  PG_CATCH();
3206  {
3207  ErrorData *edata;
3208 
3209  /* Must reset elog.c's state */
3210  MemoryContextSwitchTo(oldcontext);
3211  edata = CopyErrorData();
3212  FlushErrorState();
3213 
3214  /* Punt the error to Perl */
3215  croak_cstr(edata->message);
3216  }
3217  PG_END_TRY();
3218 }
ErrorData * CopyErrorData(void)
Definition: elog.c:1497
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void FlushErrorState(void)
Definition: elog.c:1587
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
static void plperl_return_next_internal(SV *sv)
Definition: plperl.c:3225
static void croak_cstr(const char *str)
#define PG_CATCH()
Definition: elog.h:293
#define PG_TRY()
Definition: elog.h:284
#define PG_END_TRY()
Definition: elog.h:300
char * message
Definition: elog.h:343
static void plperl_return_next_internal ( SV *  sv)
static

Definition at line 3225 of file plperl.c.

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate(), ReturnSetInfo::allowedModes, Assert, CreateTupleDescCopy(), CurrentMemoryContext, 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(), MemoryContextReset(), MemoryContextSwitchTo(), tupleDesc::natts, 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, FunctionCallInfoData::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(), and work_mem.

Referenced by plperl_func_handler(), and plperl_return_next().

3226 {
3227  plperl_proc_desc *prodesc;
3228  FunctionCallInfo fcinfo;
3229  ReturnSetInfo *rsi;
3230  MemoryContext old_cxt;
3231 
3232  if (!sv)
3233  return;
3234 
3235  prodesc = current_call_data->prodesc;
3236  fcinfo = current_call_data->fcinfo;
3237  rsi = (ReturnSetInfo *) fcinfo->resultinfo;
3238 
3239  if (!prodesc->fn_retisset)
3240  ereport(ERROR,
3241  (errcode(ERRCODE_SYNTAX_ERROR),
3242  errmsg("cannot use return_next in a non-SETOF function")));
3243 
3245  {
3246  TupleDesc tupdesc;
3247 
3249 
3250  /*
3251  * This is the first call to return_next in the current PL/Perl
3252  * function call, so identify the output tuple descriptor and create a
3253  * tuplestore to hold the result rows.
3254  */
3255  if (prodesc->fn_retistuple)
3256  (void) get_call_result_type(fcinfo, NULL, &tupdesc);
3257  else
3258  {
3259  tupdesc = rsi->expectedDesc;
3260  /* Protect assumption below that we return exactly one column */
3261  if (tupdesc == NULL || tupdesc->natts != 1)
3262  elog(ERROR, "expected single-column result descriptor for non-composite SETOF result");
3263  }
3264 
3265  /*
3266  * Make sure the tuple_store and ret_tdesc are sufficiently
3267  * long-lived.
3268  */
3270 
3274  false, work_mem);
3275 
3276  MemoryContextSwitchTo(old_cxt);
3277  }
3278 
3279  /*
3280  * Producing the tuple we want to return requires making plenty of
3281  * palloc() allocations that are not cleaned up. Since this function can
3282  * be called many times before the current memory context is reset, we
3283  * need to do those allocations in a temporary context.
3284  */
3285  if (!current_call_data->tmp_cxt)
3286  {
3289  "PL/Perl return_next temporary cxt",
3291  }
3292 
3294 
3295  if (prodesc->fn_retistuple)
3296  {
3297  HeapTuple tuple;
3298 
3299  if (!(SvOK(sv) && SvROK(sv) && SvTYPE(SvRV(sv)) == SVt_PVHV))
3300  ereport(ERROR,
3301  (errcode(ERRCODE_DATATYPE_MISMATCH),
3302  errmsg("SETOF-composite-returning PL/Perl function "
3303  "must call return_next with reference to hash")));
3304 
3305  tuple = plperl_build_tuple_result((HV *) SvRV(sv),
3308  }
3309  else
3310  {
3311  Datum ret[1];
3312  bool isNull[1];
3313 
3314  ret[0] = plperl_sv_to_datum(sv,
3315  prodesc->result_oid,
3316  -1,
3317  fcinfo,
3318  &prodesc->result_in_func,
3319  prodesc->result_typioparam,
3320  &isNull[0]);
3321 
3324  ret, isNull);
3325  }
3326 
3327  MemoryContextSwitchTo(old_cxt);
3329 }
void tuplestore_putvalues(Tuplestorestate *state, TupleDesc tdesc, Datum *values, bool *isnull)
Definition: tuplestore.c:750
TupleDesc CreateTupleDescCopy(TupleDesc tupdesc)
Definition: tupdesc.c:102
TypeFuncClass get_call_result_type(FunctionCallInfo fcinfo, Oid *resultTypeId, TupleDesc *resultTupleDesc)
Definition: funcapi.c:211
static Datum plperl_sv_to_datum(SV *sv, Oid typid, int32 typmod, FunctionCallInfo fcinfo, FmgrInfo *finfo, Oid typioparam, bool *isnull)
Definition: plperl.c:1312
FunctionCallInfo fcinfo
Definition: plperl.c:181
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
int errcode(int sqlerrcode)
Definition: elog.c:575
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:135
int natts
Definition: tupdesc.h:73
TupleDesc expectedDesc
Definition: execnodes.h:267
bool fn_retisset
Definition: plperl.c:121
#define ERROR
Definition: elog.h:43
FmgrInfo result_in_func
Definition: plperl.c:125
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:165
void tuplestore_puttuple(Tuplestorestate *state, HeapTuple tuple)
Definition: tuplestore.c:730
fmNodePtr resultinfo
Definition: fmgr.h:81
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
Oid result_typioparam
Definition: plperl.c:126
#define ereport(elevel, rest)
Definition: elog.h:122
Tuplestorestate * tuplestore_begin_heap(bool randomAccess, bool interXact, int maxKBytes)
Definition: tuplestore.c:318
MemoryContext AllocSetContextCreate(MemoryContext parent, const char *name, Size minContextSize, Size initBlockSize, Size maxBlockSize)
Definition: aset.c:322
uintptr_t Datum
Definition: postgres.h:372
int work_mem
Definition: globals.c:113
Tuplestorestate * tuple_store
Definition: plperl.c:182
int allowedModes
Definition: execnodes.h:268
TupleDesc ret_tdesc
Definition: plperl.c:183
MemoryContext tmp_cxt
Definition: plperl.c:184
#define Assert(condition)
Definition: c.h:664
MemoryContext ecxt_per_query_memory
Definition: execnodes.h:202
static HeapTuple plperl_build_tuple_result(HV *perlhash, TupleDesc td)
Definition: plperl.c:1080
ExprContext * econtext
Definition: execnodes.h:266
int errmsg(const char *fmt,...)
Definition: elog.c:797
bool fn_retistuple
Definition: plperl.c:120
plperl_proc_desc * prodesc
Definition: plperl.c:180
#define elog
Definition: elog.h:219
static plperl_call_data * current_call_data
Definition: plperl.c:245
void plperl_spi_cursor_close ( char *  cursor)

Definition at line 3476 of file plperl.c.

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

3477 {
3478  Portal p;
3479 
3481 
3482  p = SPI_cursor_find(cursor);
3483 
3484  if (p)
3485  SPI_cursor_close(p);
3486 }
Portal SPI_cursor_find(const char *name)
Definition: spi.c:1337
Definition: type.h:124
static void check_spi_usage_allowed(void)
Definition: plperl.c:3073
void SPI_cursor_close(Portal portal)
Definition: spi.c:1405
HV* plperl_spi_exec ( char *  query,
int  limit 
)

Definition at line 3085 of file plperl.c.

References BeginInternalSubTransaction(), check_spi_usage_allowed(), CopyErrorData(), croak_cstr(), 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.

3086 {
3087  HV *ret_hv;
3088 
3089  /*
3090  * Execute the query inside a sub-transaction, so we can cope with errors
3091  * sanely
3092  */
3093  MemoryContext oldcontext = CurrentMemoryContext;
3095 
3097 
3099  /* Want to run inside function's memory context */
3100  MemoryContextSwitchTo(oldcontext);
3101 
3102  PG_TRY();
3103  {
3104  int spi_rv;
3105 
3106  pg_verifymbstr(query, strlen(query), false);
3107 
3109  limit);
3111  spi_rv);
3112 
3113  /* Commit the inner transaction, return to outer xact context */
3115  MemoryContextSwitchTo(oldcontext);
3116  CurrentResourceOwner = oldowner;
3117  }
3118  PG_CATCH();
3119  {
3120  ErrorData *edata;
3121 
3122  /* Save error info */
3123  MemoryContextSwitchTo(oldcontext);
3124  edata = CopyErrorData();
3125  FlushErrorState();
3126 
3127  /* Abort the inner transaction */
3129  MemoryContextSwitchTo(oldcontext);
3130  CurrentResourceOwner = oldowner;
3131 
3132  /* Punt the error to Perl */
3133  croak_cstr(edata->message);
3134 
3135  /* Can't get here, but keep compiler quiet */
3136  return NULL;
3137  }
3138  PG_END_TRY();
3139 
3140  return ret_hv;
3141 }
ErrorData * CopyErrorData(void)
Definition: elog.c:1497
ResourceOwner CurrentResourceOwner
Definition: resowner.c:138
void ReleaseCurrentSubTransaction(void)
Definition: xact.c:4250
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
SPITupleTable * SPI_tuptable
Definition: spi.c:41
void FlushErrorState(void)
Definition: elog.c:1587
uint64 SPI_processed
Definition: spi.c:39
void RollbackAndReleaseCurrentSubTransaction(void)
Definition: xact.c:4284
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
static void croak_cstr(const char *str)
bool fn_readonly
Definition: plperl.c:116
#define PG_CATCH()
Definition: elog.h:293
void BeginInternalSubTransaction(char *name)
Definition: xact.c:4179
static void check_spi_usage_allowed(void)
Definition: plperl.c:3073
static HV * plperl_spi_execute_fetch_result(SPITupleTable *, uint64, int)
Definition: plperl.c:3145
bool pg_verifymbstr(const char *mbstr, int len, bool noError)
Definition: wchar.c:1866
plperl_proc_desc * prodesc
Definition: plperl.c:180
#define PG_TRY()
Definition: elog.h:284
static plperl_call_data * current_call_data
Definition: plperl.c:245
#define PG_END_TRY()
Definition: elog.h:300
char * message
Definition: elog.h:343
int SPI_execute(const char *src, bool read_only, long tcount)
Definition: spi.c:304
HV* plperl_spi_exec_prepared ( char *  query,
HV *  attr,
int  argc,
SV **  argv 
)

Definition at line 3637 of file plperl.c.

References plperl_query_desc::arginfuncs, plperl_query_desc::argtypes, plperl_query_desc::argtypioparams, BeginInternalSubTransaction(), check_spi_usage_allowed(), CopyErrorData(), croak_cstr(), 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_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.

3638 {
3639  HV *ret_hv;
3640  SV **sv;
3641  int i,
3642  limit,
3643  spi_rv;
3644  char *nulls;
3645  Datum *argvalues;
3646  plperl_query_desc *qdesc;
3647  plperl_query_entry *hash_entry;
3648 
3649  /*
3650  * Execute the query inside a sub-transaction, so we can cope with errors
3651  * sanely
3652  */
3653  MemoryContext oldcontext = CurrentMemoryContext;
3655 
3657 
3659  /* Want to run inside function's memory context */
3660  MemoryContextSwitchTo(oldcontext);
3661 
3662  PG_TRY();
3663  {
3664  dTHX;
3665 
3666  /************************************************************
3667  * Fetch the saved plan descriptor, see if it's o.k.
3668  ************************************************************/
3669  hash_entry = hash_search(plperl_active_interp->query_hash, query,
3670  HASH_FIND, NULL);
3671  if (hash_entry == NULL)
3672  elog(ERROR, "spi_exec_prepared: Invalid prepared query passed");
3673 
3674  qdesc = hash_entry->query_data;
3675  if (qdesc == NULL)
3676  elog(ERROR, "spi_exec_prepared: plperl query_hash value vanished");
3677 
3678  if (qdesc->nargs != argc)
3679  elog(ERROR, "spi_exec_prepared: expected %d argument(s), %d passed",
3680  qdesc->nargs, argc);
3681 
3682  /************************************************************
3683  * Parse eventual attributes
3684  ************************************************************/
3685  limit = 0;
3686  if (attr != NULL)
3687  {
3688  sv = hv_fetch_string(attr, "limit");
3689  if (sv && *sv && SvIOK(*sv))
3690  limit = SvIV(*sv);
3691  }
3692  /************************************************************
3693  * Set up arguments
3694  ************************************************************/
3695  if (argc > 0)
3696  {
3697  nulls = (char *) palloc(argc);
3698  argvalues = (Datum *) palloc(argc * sizeof(Datum));
3699  }
3700  else
3701  {
3702  nulls = NULL;
3703  argvalues = NULL;
3704  }
3705 
3706  for (i = 0; i < argc; i++)
3707  {
3708  bool isnull;
3709 
3710  argvalues[i] = plperl_sv_to_datum(argv[i],
3711  qdesc->argtypes[i],
3712  -1,
3713  NULL,
3714  &qdesc->arginfuncs[i],
3715  qdesc->argtypioparams[i],
3716  &isnull);
3717  nulls[i] = isnull ? 'n' : ' ';
3718  }
3719 
3720  /************************************************************
3721  * go
3722  ************************************************************/
3723  spi_rv = SPI_execute_plan(qdesc->plan, argvalues, nulls,
3726  spi_rv);
3727  if (argc > 0)
3728  {
3729  pfree(argvalues);
3730  pfree(nulls);
3731  }
3732 
3733  /* Commit the inner transaction, return to outer xact context */
3735  MemoryContextSwitchTo(oldcontext);
3736  CurrentResourceOwner = oldowner;
3737  }
3738  PG_CATCH();
3739  {
3740  ErrorData *edata;
3741 
3742  /* Save error info */
3743  MemoryContextSwitchTo(oldcontext);
3744  edata = CopyErrorData();
3745  FlushErrorState();
3746 
3747  /* Abort the inner transaction */
3749  MemoryContextSwitchTo(oldcontext);
3750  CurrentResourceOwner = oldowner;
3751 
3752  /* Punt the error to Perl */
3753  croak_cstr(edata->message);
3754 
3755  /* Can't get here, but keep compiler quiet */
3756  return NULL;
3757  }
3758  PG_END_TRY();
3759 
3760  return ret_hv;
3761 }
Definition: plperl.c:203
static Datum plperl_sv_to_datum(SV *sv, Oid typid, int32 typmod, FunctionCallInfo fcinfo, FmgrInfo *finfo, Oid typioparam, bool *isnull)
Definition: plperl.c:1312
HTAB * query_hash
Definition: plperl.c:94
#define dTHX
Definition: ppport.h:3208
SPIPlanPtr plan
Definition: plperl.c:194
ErrorData * CopyErrorData(void)
Definition: elog.c:1497
Oid * argtypioparams
Definition: plperl.c:198
ResourceOwner CurrentResourceOwner
Definition: resowner.c:138
void ReleaseCurrentSubTransaction(void)
Definition: xact.c:4250
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
SPITupleTable * SPI_tuptable
Definition: spi.c:41
static SV ** hv_fetch_string(HV *hv, const char *key)
Definition: plperl.c:3983
static plperl_interp_desc * plperl_active_interp
Definition: plperl.c:229
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:902
void FlushErrorState(void)
Definition: elog.c:1587
uint64 SPI_processed
Definition: spi.c:39
void pfree(void *pointer)
Definition: mcxt.c:949
#define ERROR
Definition: elog.h:43
int SPI_execute_plan(SPIPlanPtr plan, Datum *Values, const char *Nulls, bool read_only, long tcount)
Definition: spi.c:339
void RollbackAndReleaseCurrentSubTransaction(void)
Definition: xact.c:4284
Oid * argtypes
Definition: plperl.c:196
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
uintptr_t Datum
Definition: postgres.h:372
FmgrInfo * arginfuncs
Definition: plperl.c:197
static void croak_cstr(const char *str)
bool fn_readonly
Definition: plperl.c:116
#define PG_CATCH()
Definition: elog.h:293
void BeginInternalSubTransaction(char *name)
Definition: xact.c:4179
static void check_spi_usage_allowed(void)
Definition: plperl.c:3073
void * palloc(Size size)
Definition: mcxt.c:848
int i
static HV * plperl_spi_execute_fetch_result(SPITupleTable *, uint64, int)
Definition: plperl.c:3145
plperl_proc_desc * prodesc
Definition: plperl.c:180
#define elog
Definition: elog.h:219
#define PG_TRY()
Definition: elog.h:284
static plperl_call_data * current_call_data
Definition: plperl.c:245
#define PG_END_TRY()
Definition: elog.h:300
char * message
Definition: elog.h:343
plperl_query_desc * query_data
Definition: plperl.c:206
static HV * plperl_spi_execute_fetch_result ( SPITupleTable tuptable,
uint64  processed,
int  status 
)
static

Definition at line 3145 of file plperl.c.

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

3147 {
3148  dTHX;
3149  HV *result;
3150 
3152 
3153  result = newHV();
3154 
3155  hv_store_string(result, "status",
3157  hv_store_string(result, "processed",
3158  (processed > (uint64) UV_MAX) ?
3159  newSVnv((NV) processed) :
3160  newSVuv((UV) processed));
3161 
3162  if (status > 0 && tuptable)
3163  {
3164  AV *rows;
3165  SV *row;
3166  uint64 i;
3167 
3168  /* Prevent overflow in call to av_extend() */
3169  if (processed > (uint64) AV_SIZE_MAX)
3170  ereport(ERROR,
3171  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
3172  errmsg("query result has too many rows to fit in a Perl array")));
3173 
3174  rows = newAV();
3175  av_extend(rows, processed);
3176  for (i = 0; i < processed; i++)
3177  {
3178  row = plperl_hash_from_tuple(tuptable->vals[i], tuptable->tupdesc);
3179  av_push(rows, row);
3180  }
3181  hv_store_string(result, "rows",
3182  newRV_noinc((SV *) rows));
3183  }
3184 
3185  SPI_freetuptable(tuptable);
3186 
3187  return result;
3188 }
#define dTHX
Definition: ppport.h:3208
#define AV_SIZE_MAX
Definition: plperl.h:107
int errcode(int sqlerrcode)
Definition: elog.c:575
static SV ** hv_store_string(HV *hv, const char *key, SV *val)
Definition: plperl.c:3956
HeapTuple * vals
Definition: spi.h:28
NVTYPE NV
Definition: ppport.h:3754
#define ERROR
Definition: elog.h:43
#define newSVuv(uv)
Definition: ppport.h:3596
const char * SPI_result_code_string(int code)
Definition: spi.c:1515
#define ereport(elevel, rest)
Definition: elog.h:122
static SV * plperl_hash_from_tuple(HeapTuple tuple, TupleDesc tupdesc)
Definition: plperl.c:3000
void SPI_freetuptable(SPITupleTable *tuptable)
Definition: spi.c:972
#define newRV_noinc(a)
Definition: ppport.h:4456
TupleDesc tupdesc
Definition: spi.h:27
static SV * cstr2sv(const char *str)
#define UV_MAX
Definition: ppport.h:3566
static void check_spi_usage_allowed(void)
Definition: plperl.c:3073
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:224
SV* plperl_spi_fetchrow ( char *  cursor)

Definition at line 3403 of file plperl.c.

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, and SPITupleTable::vals.

3404 {
3405  SV *row;
3406 
3407  /*
3408  * Execute the FETCH inside a sub-transaction, so we can cope with errors
3409  * sanely
3410  */
3411  MemoryContext oldcontext = CurrentMemoryContext;
3413 
3415 
3417  /* Want to run inside function's memory context */
3418  MemoryContextSwitchTo(oldcontext);
3419 
3420  PG_TRY();
3421  {
3422  dTHX;
3424 
3425  if (!p)
3426  {
3427  row = &PL_sv_undef;
3428  }
3429  else
3430  {
3431  SPI_cursor_fetch(p, true, 1);
3432  if (SPI_processed == 0)
3433  {
3434  SPI_cursor_close(p);
3435  row = &PL_sv_undef;
3436  }
3437  else
3438  {
3441  }
3443  }
3444 
3445  /* Commit the inner transaction, return to outer xact context */
3447  MemoryContextSwitchTo(oldcontext);
3448  CurrentResourceOwner = oldowner;
3449  }
3450  PG_CATCH();
3451  {
3452  ErrorData *edata;
3453 
3454  /* Save error info */
3455  MemoryContextSwitchTo(oldcontext);
3456  edata = CopyErrorData();
3457  FlushErrorState();
3458 
3459  /* Abort the inner transaction */
3461  MemoryContextSwitchTo(oldcontext);
3462  CurrentResourceOwner = oldowner;
3463 
3464  /* Punt the error to Perl */
3465  croak_cstr(edata->message);
3466 
3467  /* Can't get here, but keep compiler quiet */
3468  return NULL;
3469  }
3470  PG_END_TRY();
3471 
3472  return row;
3473 }
#define dTHX
Definition: ppport.h:3208
ErrorData * CopyErrorData(void)
Definition: elog.c:1497
ResourceOwner CurrentResourceOwner
Definition: resowner.c:138
void ReleaseCurrentSubTransaction(void)
Definition: xact.c:4250
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
SPITupleTable * SPI_tuptable
Definition: spi.c:41
#define PL_sv_undef
Definition: ppport.h:4129
HeapTuple * vals
Definition: spi.h:28
void FlushErrorState(void)
Definition: elog.c:1587
uint64 SPI_processed
Definition: spi.c:39
Portal SPI_cursor_find(const char *name)
Definition: spi.c:1337
void RollbackAndReleaseCurrentSubTransaction(void)
Definition: xact.c:4284
Definition: type.h:124
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
static SV * plperl_hash_from_tuple(HeapTuple tuple, TupleDesc tupdesc)
Definition: plperl.c:3000
void SPI_freetuptable(SPITupleTable *tuptable)
Definition: spi.c:972
static void croak_cstr(const char *str)
TupleDesc tupdesc
Definition: spi.h:27
#define PG_CATCH()
Definition: elog.h:293
void BeginInternalSubTransaction(char *name)
Definition: xact.c:4179
static void check_spi_usage_allowed(void)
Definition: plperl.c:3073
void SPI_cursor_close(Portal portal)
Definition: spi.c:1405
void SPI_cursor_fetch(Portal portal, bool forward, long count)
Definition: spi.c:1349
#define PG_TRY()
Definition: elog.h:284
#define PG_END_TRY()
Definition: elog.h:300
char * message
Definition: elog.h:343
void plperl_spi_freeplan ( char *  query)

Definition at line 3880 of file plperl.c.

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

3881 {
3882  SPIPlanPtr plan;
3883  plperl_query_desc *qdesc;
3884  plperl_query_entry *hash_entry;
3885 
3887 
3888  hash_entry = hash_search(plperl_active_interp->query_hash, query,
3889  HASH_FIND, NULL);
3890  if (hash_entry == NULL)
3891  elog(ERROR, "spi_freeplan: Invalid prepared query passed");
3892 
3893  qdesc = hash_entry->query_data;
3894  if (qdesc == NULL)
3895  elog(ERROR, "spi_freeplan: plperl query_hash value vanished");
3896  plan = qdesc->plan;
3897 
3898  /*
3899  * free all memory before SPI_freeplan, so if it dies, nothing will be
3900  * left over
3901  */
3903  HASH_REMOVE, NULL);
3904 
3905  MemoryContextDelete(qdesc->plan_cxt);
3906 
3907  SPI_freeplan(plan);
3908 }
Definition: plperl.c:203
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:200
HTAB * query_hash
Definition: plperl.c:94
SPIPlanPtr plan
Definition: plperl.c:194
static plperl_interp_desc * plperl_active_interp
Definition: plperl.c:229
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:902
#define ERROR
Definition: elog.h:43
MemoryContext plan_cxt
Definition: plperl.c:193
static void check_spi_usage_allowed(void)
Definition: plperl.c:3073
int SPI_freeplan(SPIPlanPtr plan)
Definition: spi.c:609
#define elog
Definition: elog.h:219
plperl_query_desc * query_data
Definition: plperl.c:206
SV* plperl_spi_prepare ( char *  query,
int  argc,
SV **  argv 
)

Definition at line 3489 of file plperl.c.

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, plperl_query_desc::plan_cxt, 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.

3490 {
3491  volatile SPIPlanPtr plan = NULL;
3492  volatile MemoryContext plan_cxt = NULL;
3493  plperl_query_desc *volatile qdesc = NULL;
3494  plperl_query_entry *volatile hash_entry = NULL;
3495  MemoryContext oldcontext = CurrentMemoryContext;
3497  MemoryContext work_cxt;
3498  bool found;
3499  int i;
3500 
3502 
3504  MemoryContextSwitchTo(oldcontext);
3505 
3506  PG_TRY();
3507  {
3509 
3510  /************************************************************
3511  * Allocate the new querydesc structure
3512  *
3513  * The qdesc struct, as well as all its subsidiary data, lives in its
3514  * plan_cxt. But note that the SPIPlan does not.
3515  ************************************************************/
3517  "PL/Perl spi_prepare query",
3519  MemoryContextSwitchTo(plan_cxt);
3520  qdesc = (plperl_query_desc *) palloc0(sizeof(plperl_query_desc));
3521  snprintf(qdesc->qname, sizeof(qdesc->qname), "%p", qdesc);
3522  qdesc->plan_cxt = plan_cxt;
3523  qdesc->nargs = argc;
3524  qdesc->argtypes = (Oid *) palloc(argc * sizeof(Oid));
3525  qdesc->arginfuncs = (FmgrInfo *) palloc(argc * sizeof(FmgrInfo));
3526  qdesc->argtypioparams = (Oid *) palloc(argc * sizeof(Oid));
3527  MemoryContextSwitchTo(oldcontext);
3528 
3529  /************************************************************
3530  * Do the following work in a short-lived context so that we don't
3531  * leak a lot of memory in the PL/Perl function's SPI Proc context.
3532  ************************************************************/
3534  "PL/Perl spi_prepare workspace",
3536  MemoryContextSwitchTo(work_cxt);
3537 
3538  /************************************************************
3539  * Resolve argument type names and then look them up by oid
3540  * in the system cache, and remember the required information
3541  * for input conversion.
3542  ************************************************************/
3543  for (i = 0; i < argc; i++)
3544  {
3545  Oid typId,
3546  typInput,
3547  typIOParam;
3548  int32 typmod;
3549  char *typstr;
3550 
3551  typstr = sv2cstr(argv[i]);
3552  parseTypeString(typstr, &typId, &typmod, false);
3553  pfree(typstr);
3554 
3555  getTypeInputInfo(typId, &typInput, &typIOParam);
3556 
3557  qdesc->argtypes[i] = typId;
3558  fmgr_info_cxt(typInput, &(qdesc->arginfuncs[i]), plan_cxt);
3559  qdesc->argtypioparams[i] = typIOParam;
3560  }
3561 
3562  /* Make sure the query is validly encoded */
3563  pg_verifymbstr(query, strlen(query), false);
3564 
3565  /************************************************************
3566  * Prepare the plan and check for errors
3567  ************************************************************/
3568  plan = SPI_prepare(query, argc, qdesc->argtypes);
3569 
3570  if (plan == NULL)
3571  elog(ERROR, "SPI_prepare() failed:%s",
3573 
3574  /************************************************************
3575  * Save the plan into permanent memory (right now it's in the
3576  * SPI procCxt, which will go away at function end).
3577  ************************************************************/
3578  if (SPI_keepplan(plan))
3579  elog(ERROR, "SPI_keepplan() failed");
3580  qdesc->plan = plan;
3581 
3582  /************************************************************
3583  * Insert a hashtable entry for the plan.
3584  ************************************************************/
3586  qdesc->qname,
3587  HASH_ENTER, &found);
3588  hash_entry->query_data = qdesc;
3589 
3590  /* Get rid of workspace */
3591  MemoryContextDelete(work_cxt);
3592 
3593  /* Commit the inner transaction, return to outer xact context */
3595  MemoryContextSwitchTo(oldcontext);
3596  CurrentResourceOwner = oldowner;
3597  }
3598  PG_CATCH();
3599  {
3600  ErrorData *edata;
3601 
3602  /* Save error info */
3603  MemoryContextSwitchTo(oldcontext);
3604  edata = CopyErrorData();
3605  FlushErrorState();
3606 
3607  /* Drop anything we managed to allocate */
3608  if (hash_entry)
3610  qdesc->qname,
3611  HASH_REMOVE, NULL);
3612  if (plan_cxt)
3613  MemoryContextDelete(plan_cxt);
3614  if (plan)
3615  SPI_freeplan(plan);
3616 
3617  /* Abort the inner transaction */
3619  MemoryContextSwitchTo(oldcontext);
3620  CurrentResourceOwner = oldowner;
3621 
3622  /* Punt the error to Perl */
3623  croak_cstr(edata->message);
3624 
3625  /* Can't get here, but keep compiler quiet */
3626  return NULL;
3627  }
3628  PG_END_TRY();
3629 
3630  /************************************************************
3631  * Return the query's hash key to the caller.
3632  ************************************************************/
3633  return cstr2sv(qdesc->qname);
3634 }
Definition: fmgr.h:56
Definition: plperl.c:203
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:200
HTAB * query_hash
Definition: plperl.c:94
SPIPlanPtr plan
Definition: plperl.c:194
ErrorData * CopyErrorData(void)
Definition: elog.c:1497
Oid * argtypioparams
Definition: plperl.c:198
ResourceOwner CurrentResourceOwner
Definition: resowner.c:138
SPIPlanPtr SPI_prepare(const char *src, int nargs, Oid *argtypes)
Definition: spi.c:482
#define ALLOCSET_SMALL_SIZES
Definition: memutils.h:175
void ReleaseCurrentSubTransaction(void)
Definition: xact.c:4250
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
static plperl_interp_desc * plperl_active_interp
Definition: plperl.c:229
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:902
unsigned int Oid
Definition: postgres_ext.h:31
void FlushErrorState(void)
Definition: elog.c:1587
signed int int32
Definition: c.h:246
int SPI_result
Definition: spi.c:42
void pfree(void *pointer)
Definition: mcxt.c:949
#define ERROR
Definition: elog.h:43
const char * SPI_result_code_string(int code)
Definition: spi.c:1515
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:165
int SPI_keepplan(SPIPlanPtr plan)
Definition: spi.c:560
void RollbackAndReleaseCurrentSubTransaction(void)
Definition: xact.c:4284
Oid * argtypes
Definition: plperl.c:196
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
MemoryContext plan_cxt
Definition: plperl.c:193
void fmgr_info_cxt(Oid functionId, FmgrInfo *finfo, MemoryContext mcxt)
Definition: fmgr.c:137
void getTypeInputInfo(Oid type, Oid *typInput, Oid *typIOParam)
Definition: lsyscache.c:2599
MemoryContext TopMemoryContext
Definition: mcxt.c:43
MemoryContext AllocSetContextCreate(MemoryContext parent, const char *name, Size minContextSize, Size initBlockSize, Size maxBlockSize)
Definition: aset.c:322
void * palloc0(Size size)
Definition: mcxt.c:877
char qname[24]
Definition: plperl.c:192
FmgrInfo * arginfuncs
Definition: plperl.c:197
static void croak_cstr(const char *str)
static SV * cstr2sv(const char *str)
void parseTypeString(const char *str, Oid *typeid_p, int32 *typmod_p, bool missing_ok)
Definition: parse_type.c:781
#define PG_CATCH()
Definition: elog.h:293
void BeginInternalSubTransaction(char *name)
Definition: xact.c:4179
static void check_spi_usage_allowed(void)
Definition: plperl.c:3073
int SPI_freeplan(SPIPlanPtr plan)
Definition: spi.c:609
void * palloc(Size size)
Definition: mcxt.c:848
int i
bool pg_verifymbstr(const char *mbstr, int len, bool noError)
Definition: wchar.c:1866
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:98
#define elog
Definition: elog.h:219
#define PG_TRY()
Definition: elog.h:284
#define PG_END_TRY()
Definition: elog.h:300
char * message
Definition: elog.h:343
static char * sv2cstr(SV *sv)
plperl_query_desc * query_data
Definition: plperl.c:206
SV* plperl_spi_query ( char *  query)

Definition at line 3333 of file plperl.c.

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(), ReleaseCurrentSubTransaction(), RollbackAndReleaseCurrentSubTransaction(), SPI_cursor_open(), SPI_freeplan(), SPI_prepare(), SPI_result, and SPI_result_code_string().

3334 {
3335  SV *cursor;
3336 
3337  /*
3338  * Execute the query inside a sub-transaction, so we can cope with errors
3339  * sanely
3340  */
3341  MemoryContext oldcontext = CurrentMemoryContext;
3343 
3345 
3347  /* Want to run inside function's memory context */
3348  MemoryContextSwitchTo(oldcontext);
3349 
3350  PG_TRY();
3351  {
3352  SPIPlanPtr plan;
3353  Portal portal;
3354 
3355  /* Make sure the query is validly encoded */
3356  pg_verifymbstr(query, strlen(query), false);
3357 
3358  /* Create a cursor for the query */
3359  plan = SPI_prepare(query, 0, NULL);
3360  if (plan == NULL)
3361  elog(ERROR, "SPI_prepare() failed:%s",
3363 
3364  portal = SPI_cursor_open(NULL, plan, NULL, NULL, false);
3365  SPI_freeplan(plan);
3366  if (portal == NULL)
3367  elog(ERROR, "SPI_cursor_open() failed:%s",
3369  cursor = cstr2sv(portal->name);
3370 
3371  /* Commit the inner transaction, return to outer xact context */
3373  MemoryContextSwitchTo(oldcontext);
3374  CurrentResourceOwner = oldowner;
3375  }
3376  PG_CATCH();
3377  {
3378  ErrorData *edata;
3379 
3380  /* Save error info */
3381  MemoryContextSwitchTo(oldcontext);
3382  edata = CopyErrorData();
3383  FlushErrorState();
3384 
3385  /* Abort the inner transaction */
3387  MemoryContextSwitchTo(oldcontext);
3388  CurrentResourceOwner = oldowner;
3389 
3390  /* Punt the error to Perl */
3391  croak_cstr(edata->message);
3392 
3393  /* Can't get here, but keep compiler quiet */
3394  return NULL;
3395  }
3396  PG_END_TRY();
3397 
3398  return cursor;
3399 }
ErrorData * CopyErrorData(void)
Definition: elog.c:1497
ResourceOwner CurrentResourceOwner
Definition: resowner.c:138
SPIPlanPtr SPI_prepare(const char *src, int nargs, Oid *argtypes)
Definition: spi.c:482
void ReleaseCurrentSubTransaction(void)
Definition: xact.c:4250
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Portal SPI_cursor_open(const char *name, SPIPlanPtr plan, Datum *Values, const char *Nulls, bool read_only)
Definition: spi.c:1031
void FlushErrorState(void)
Definition: elog.c:1587
int SPI_result
Definition: spi.c:42
const char * name
Definition: portal.h:117
#define ERROR
Definition: elog.h:43
const char * SPI_result_code_string(int code)
Definition: spi.c:1515
void RollbackAndReleaseCurrentSubTransaction(void)
Definition: xact.c:4284
Definition: type.h:124
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
static void croak_cstr(const char *str)
static SV * cstr2sv(const char *str)
#define PG_CATCH()
Definition: elog.h:293
void BeginInternalSubTransaction(char *name)
Definition: xact.c:4179
static void check_spi_usage_allowed(void)
Definition: plperl.c:3073
int SPI_freeplan(SPIPlanPtr plan)
Definition: spi.c:609
bool pg_verifymbstr(const char *mbstr, int len, bool noError)
Definition: wchar.c:1866
#define elog
Definition: elog.h:219
#define PG_TRY()
Definition: elog.h:284
#define PG_END_TRY()
Definition: elog.h:300
char * message
Definition: elog.h:343
SV* plperl_spi_query_prepared ( char *  query,
int  argc,
SV **  argv 
)

Definition at line 3764 of file plperl.c.

References plperl_query_desc::arginfuncs, plperl_query_desc::argtypes, plperl_query_desc::argtypioparams, BeginInternalSubTransaction(), check_spi_usage_allowed(), CopyErrorData(), croak_cstr(), cstr2sv(), 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, plperl_query_desc::plan, 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().

3765 {
3766  int i;
3767  char *nulls;
3768  Datum *argvalues;
3769  plperl_query_desc *qdesc;
3770  plperl_query_entry *hash_entry;
3771  SV *cursor;
3772  Portal portal = NULL;
3773 
3774  /*
3775  * Execute the query inside a sub-transaction, so we can cope with errors
3776  * sanely
3777  */
3778  MemoryContext oldcontext = CurrentMemoryContext;
3780 
3782 
3784  /* Want to run inside function's memory context */
3785  MemoryContextSwitchTo(oldcontext);
3786 
3787  PG_TRY();
3788  {
3789  /************************************************************
3790  * Fetch the saved plan descriptor, see if it's o.k.
3791  ************************************************************/
3792  hash_entry = hash_search(plperl_active_interp->query_hash, query,
3793  HASH_FIND, NULL);
3794  if (hash_entry == NULL)
3795  elog(ERROR, "spi_query_prepared: Invalid prepared query passed");
3796 
3797  qdesc = hash_entry->query_data;
3798  if (qdesc == NULL)
3799  elog(ERROR, "spi_query_prepared: plperl query_hash value vanished");
3800 
3801  if (qdesc->nargs != argc)
3802  elog(ERROR, "spi_query_prepared: expected %d argument(s), %d passed",
3803  qdesc->nargs, argc);
3804 
3805  /************************************************************
3806  * Set up arguments
3807  ************************************************************/
3808  if (argc > 0)
3809  {
3810  nulls = (char *) palloc(argc);
3811  argvalues = (Datum *) palloc(argc * sizeof(Datum));
3812  }
3813  else
3814  {
3815  nulls = NULL;
3816  argvalues = NULL;
3817  }
3818 
3819  for (i = 0; i < argc; i++)
3820  {
3821  bool isnull;
3822 
3823  argvalues[i] = plperl_sv_to_datum(argv[i],
3824  qdesc->argtypes[i],
3825  -1,
3826  NULL,
3827  &qdesc->arginfuncs[i],
3828  qdesc->argtypioparams[i],
3829  &isnull);
3830  nulls[i] = isnull ? 'n' : ' ';
3831  }
3832 
3833  /************************************************************
3834  * go
3835  ************************************************************/
3836  portal = SPI_cursor_open(NULL, qdesc->plan, argvalues, nulls,
3838  if (argc > 0)
3839  {
3840  pfree(argvalues);
3841  pfree(nulls);
3842  }
3843  if (portal == NULL)
3844  elog(ERROR, "SPI_cursor_open() failed:%s",
3846 
3847  cursor = cstr2sv(portal->name);
3848 
3849  /* Commit the inner transaction, return to outer xact context */
3851  MemoryContextSwitchTo(oldcontext);
3852  CurrentResourceOwner = oldowner;
3853  }
3854  PG_CATCH();
3855  {
3856  ErrorData *edata;
3857 
3858  /* Save error info */
3859  MemoryContextSwitchTo(oldcontext);
3860  edata = CopyErrorData();
3861  FlushErrorState();
3862 
3863  /* Abort the inner transaction */
3865  MemoryContextSwitchTo(oldcontext);
3866  CurrentResourceOwner = oldowner;
3867 
3868  /* Punt the error to Perl */
3869  croak_cstr(edata->message);
3870 
3871  /* Can't get here, but keep compiler quiet */
3872  return NULL;
3873  }
3874  PG_END_TRY();
3875 
3876  return cursor;
3877 }
Definition: plperl.c:203
static Datum plperl_sv_to_datum(SV *sv, Oid typid, int32 typmod, FunctionCallInfo fcinfo, FmgrInfo *finfo, Oid typioparam, bool *isnull)
Definition: plperl.c:1312
HTAB * query_hash
Definition: plperl.c:94
SPIPlanPtr plan
Definition: plperl.c:194
ErrorData * CopyErrorData(void)
Definition: elog.c:1497
Oid * argtypioparams
Definition: plperl.c:198
ResourceOwner CurrentResourceOwner
Definition: resowner.c:138
void ReleaseCurrentSubTransaction(void)
Definition: xact.c:4250
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
static plperl_interp_desc * plperl_active_interp
Definition: plperl.c:229
Portal SPI_cursor_open(const char *name, SPIPlanPtr plan, Datum *Values, const char *Nulls, bool read_only)
Definition: spi.c:1031
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:902
void FlushErrorState(void)
Definition: elog.c:1587
int SPI_result
Definition: spi.c:42
void pfree(void *pointer)
Definition: mcxt.c:949
const char * name
Definition: portal.h:117
#define ERROR
Definition: elog.h:43
const char * SPI_result_code_string(int code)
Definition: spi.c:1515
void RollbackAndReleaseCurrentSubTransaction(void)
Definition: xact.c:4284
Definition: type.h:124
Oid * argtypes
Definition: plperl.c:196
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
uintptr_t Datum
Definition: postgres.h:372
FmgrInfo * arginfuncs
Definition: plperl.c:197
static void croak_cstr(const char *str)
static SV * cstr2sv(const char *str)
bool fn_readonly
Definition: plperl.c:116
#define PG_CATCH()
Definition: elog.h:293
void BeginInternalSubTransaction(char *name)
Definition: xact.c:4179
static void check_spi_usage_allowed(void)
Definition: plperl.c:3073
void * palloc(Size size)
Definition: mcxt.c:848
int i
plperl_proc_desc * prodesc
Definition: plperl.c:180
#define elog
Definition: elog.h:219
#define PG_TRY()
Definition: elog.h:284
static plperl_call_data * current_call_data
Definition: plperl.c:245
#define PG_END_TRY()
Definition: elog.h:300
char * message
Definition: elog.h:343
plperl_query_desc * query_data
Definition: plperl.c:206
static Datum plperl_sv_to_datum ( SV *  sv,
Oid  typid,
int32  typmod,
FunctionCallInfo  fcinfo,
FmgrInfo finfo,
Oid  typioparam,
bool isnull 
)
static

Definition at line 1312 of file plperl.c.

References _sv_to_datum_finfo(), check_stack_depth(), 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_noerror(), OidFunctionCall1, pfree(), plperl_array_to_datum(), plperl_hash_to_datum(), PointerGetDatum, plperl_call_data::prodesc, ReleaseTupleDesc, sv2cstr(), plperl_proc_desc::trftypes, type_is_rowtype(), TYPEFUNC_COMPOSITE, and VOIDOID.

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

1316 {
1317  FmgrInfo tmp;
1318  Oid funcid;
1319 
1320  /* we might recurse */
1322 
1323  *isnull = false;
1324 
1325  /*
1326  * Return NULL if result is undef, or if we're in a function returning
1327  * VOID. In the latter case, we should pay no attention to the last Perl
1328  * statement's result, and this is a convenient means to ensure that.
1329  */
1330  if (!sv || !SvOK(sv) || typid == VOIDOID)
1331  {
1332  /* look up type info if they did not pass it */
1333  if (!finfo)
1334  {
1335  _sv_to_datum_finfo(typid, &tmp, &typioparam);
1336  finfo = &tmp;
1337  }
1338  *isnull = true;
1339  /* must call typinput in case it wants to reject NULL */
1340  return InputFunctionCall(finfo, NULL, typioparam, typmod);
1341  }
1343  return OidFunctionCall1(funcid, PointerGetDatum(sv));
1344  else if (SvROK(sv))
1345  {
1346  /* handle references */
1347  SV *sav = get_perl_array_ref(sv);
1348 
1349  if (sav)
1350  {
1351  /* handle an arrayref */
1352  return plperl_array_to_datum(sav, typid, typmod);
1353  }
1354  else if (SvTYPE(SvRV(sv)) == SVt_PVHV)
1355  {
1356  /* handle a hashref */
1357  Datum ret;
1358  TupleDesc td;
1359 
1360  if (!type_is_rowtype(typid))
1361  ereport(ERROR,
1362  (errcode(ERRCODE_DATATYPE_MISMATCH),
1363  errmsg("cannot convert Perl hash to non-composite type %s",
1364  format_type_be(typid))));
1365 
1366  td = lookup_rowtype_tupdesc_noerror(typid, typmod, true);
1367  if (td == NULL)
1368  {
1369  /* Try to look it up based on our result type */
1370  if (fcinfo == NULL ||
1371  get_call_result_type(fcinfo, NULL, &td) != TYPEFUNC_COMPOSITE)
1372  ereport(ERROR,
1373  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1374  errmsg("function returning record called in context "
1375  "that cannot accept type record")));
1376  }
1377 
1378  ret = plperl_hash_to_datum(sv, td);
1379 
1380  /* Release on the result of get_call_result_type is harmless */
1381  ReleaseTupleDesc(td);
1382 
1383  return ret;
1384  }
1385 
1386  /* Reference, but not reference to hash or array ... */
1387  ereport(ERROR,
1388  (errcode(ERRCODE_DATATYPE_MISMATCH),
1389  errmsg("PL/Perl function must return reference to hash or array")));
1390  return (Datum) 0; /* shut up compiler */
1391  }
1392  else
1393  {
1394  /* handle a string/number */
1395  Datum ret;
1396  char *str = sv2cstr(sv);
1397 
1398  /* did not pass in any typeinfo? look it up */
1399  if (!finfo)
1400  {
1401  _sv_to_datum_finfo(typid, &tmp, &typioparam);
1402  finfo = &tmp;
1403  }
1404 
1405  ret = InputFunctionCall(finfo, str, typioparam, typmod);
1406  pfree(str);
1407 
1408  return ret;
1409  }
1410 }
Definition: fmgr.h:56
List * trftypes
Definition: plperl.c:118
TypeFuncClass get_call_result_type(FunctionCallInfo fcinfo, Oid *resultTypeId, TupleDesc *resultTupleDesc)
Definition: funcapi.c:211
static SV * get_perl_array_ref(SV *sv)
Definition: plperl.c:1143
static Datum plperl_array_to_datum(SV *src, Oid typid, int32 typmod)
Definition: plperl.c:1245
#define PointerGetDatum(X)
Definition: postgres.h:562
int errcode(int sqlerrcode)
Definition: elog.c:575
char * format_type_be(Oid type_oid)
Definition: format_type.c:94
unsigned int Oid
Definition: postgres_ext.h:31
void pfree(void *pointer)
Definition: mcxt.c:949
#define VOIDOID
Definition: pg_type.h:690
#define ERROR
Definition: elog.h:43
#define OidFunctionCall1(functionId, arg1)
Definition: fmgr.h:623
void check_stack_depth(void)
Definition: postgres.c:3144
static Datum plperl_hash_to_datum(SV *src, TupleDesc td)
Definition: plperl.c:1131
TupleDesc lookup_rowtype_tupdesc_noerror(Oid type_id, int32 typmod, bool noError)
Definition: typcache.c:1503
bool type_is_rowtype(Oid typid)
Definition: lsyscache.c:2404
#define ereport(elevel, rest)
Definition: elog.h:122
uintptr_t Datum
Definition: postgres.h:372
Datum InputFunctionCall(FmgrInfo *flinfo, char *str, Oid typioparam, int32 typmod)
Definition: fmgr.c:1623
Oid get_transform_tosql(Oid typid, Oid langid, List *trftypes)
Definition: lsyscache.c:1893
int errmsg(const char *fmt,...)
Definition: elog.c:797
plperl_proc_desc * prodesc
Definition: plperl.c:180
static void _sv_to_datum_finfo(Oid typid, FmgrInfo *finfo, Oid *typioparam)
Definition: plperl.c:1289
#define ReleaseTupleDesc(tupdesc)
Definition: tupdesc.h:115
static plperl_call_data * current_call_data
Definition: plperl.c:245
static char * sv2cstr(SV *sv)
char* plperl_sv_to_literal ( SV *  sv,
char *  fqtypename 
)

Definition at line 1414 of file plperl.c.

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

1415 {
1416  Datum str = CStringGetDatum(fqtypename);
1417  Oid typid = DirectFunctionCall1(regtypein, str);
1418  Oid typoutput;
1419  Datum datum;
1420  bool typisvarlena,
1421  isnull;
1422 
1423  if (!OidIsValid(typid))
1424  ereport(ERROR,
1425  (errcode(ERRCODE_UNDEFINED_OBJECT),
1426  errmsg("lookup failed for type %s", fqtypename)));
1427 
1428  datum = plperl_sv_to_datum(sv,
1429  typid, -1,
1430  NULL, NULL, InvalidOid,
1431  &isnull);
1432 
1433  if (isnull)
1434  return NULL;
1435 
1436  getTypeOutputInfo(typid,
1437  &typoutput, &typisvarlena);
1438 
1439  return OidOutputFunctionCall(typoutput, datum);
1440 }
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:2632
static Datum plperl_sv_to_datum(SV *sv, Oid typid, int32 typmod, FunctionCallInfo fcinfo, FmgrInfo *finfo, Oid typioparam, bool *isnull)
Definition: plperl.c:1312
int errcode(int sqlerrcode)
Definition: elog.c:575
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:585
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:532
#define ERROR
Definition: elog.h:43
#define CStringGetDatum(X)
Definition: postgres.h:584
#define ereport(elevel, rest)
Definition: elog.h:122
Datum regtypein(PG_FUNCTION_ARGS)
Definition: regproc.c:1061
uintptr_t Datum
Definition: postgres.h:372
#define InvalidOid
Definition: postgres_ext.h:36
char * OidOutputFunctionCall(Oid functionId, Datum val)
Definition: fmgr.c:1747
int errmsg(const char *fmt,...)
Definition: elog.c:797
static SV* plperl_trigger_build_args ( FunctionCallInfo  fcinfo)
static

Definition at line 1599 of file plperl.c.

References av, FunctionCallInfoData::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().

1600 {
1601  dTHX;
1602  TriggerData *tdata;
1603  TupleDesc tupdesc;
1604  int i;
1605  char *level;
1606  char *event;
1607  char *relid;
1608  char *when;
1609  HV *hv;
1610 
1611  hv = newHV();
1612  hv_ksplit(hv, 12); /* pre-grow the hash */
1613 
1614  tdata = (TriggerData *) fcinfo->context;
1615  tupdesc = tdata->tg_relation->rd_att;
1616 
1617  relid = DatumGetCString(
1620  )
1621  );
1622 
1623  hv_store_string(hv, "name", cstr2sv(tdata->tg_trigger->tgname));
1624  hv_store_string(hv, "relid", cstr2sv(relid));
1625 
1626  if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
1627  {
1628  event = "INSERT";
1629  if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
1630  hv_store_string(hv, "new",
1632  tupdesc));
1633  }
1634  else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
1635  {
1636  event = "DELETE";
1637  if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
1638  hv_store_string(hv, "old",
1640  tupdesc));
1641  }
1642  else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
1643  {
1644  event = "UPDATE";
1645  if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
1646  {
1647  hv_store_string(hv, "old",
1649  tupdesc));
1650  hv_store_string(hv, "new",
1652  tupdesc));
1653  }
1654  }
1655  else if (TRIGGER_FIRED_BY_TRUNCATE(tdata->tg_event))
1656  event = "TRUNCATE";
1657  else
1658  event = "UNKNOWN";
1659 
1660  hv_store_string(hv, "event", cstr2sv(event));
1661  hv_store_string(hv, "argc", newSViv(tdata->tg_trigger->tgnargs));
1662 
1663  if (tdata->tg_trigger->tgnargs > 0)
1664  {
1665  AV *av = newAV();
1666 
1667  av_extend(av, tdata->tg_trigger->tgnargs);
1668  for (i = 0; i < tdata->tg_trigger->tgnargs; i++)
1669  av_push(av, cstr2sv(tdata->tg_trigger->tgargs[i]));
1670  hv_store_string(hv, "args", newRV_noinc((SV *) av));
1671  }
1672 
1673  hv_store_string(hv, "relname",
1675 
1676  hv_store_string(hv, "table_name",
1678 
1679  hv_store_string(hv, "table_schema",
1681 
1682  if (TRIGGER_FIRED_BEFORE(tdata->tg_event))
1683  when = "BEFORE";
1684  else if (TRIGGER_FIRED_AFTER(tdata->tg_event))
1685  when = "AFTER";
1686  else if (TRIGGER_FIRED_INSTEAD(tdata->tg_event))
1687  when = "INSTEAD OF";
1688  else
1689  when = "UNKNOWN";
1690  hv_store_string(hv, "when", cstr2sv(when));
1691 
1692  if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
1693  level = "ROW";
1694  else if (TRIGGER_FIRED_FOR_STATEMENT(tdata->tg_event))
1695  level = "STATEMENT";
1696  else
1697  level = "UNKNOWN";
1698  hv_store_string(hv, "level", cstr2sv(level));
1699 
1700  return newRV_noinc((SV *) hv);
1701 }
#define dTHX
Definition: ppport.h:3208
fmNodePtr context
Definition: fmgr.h:80
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:585
static SV ** hv_store_string(HV *hv, const char *key, SV *val)
Definition: plperl.c:3956
#define TRIGGER_FIRED_AFTER(event)
Definition: trigger.h:137
Datum oidout(PG_FUNCTION_ARGS)
Definition: oid.c:127
#define TRIGGER_FIRED_FOR_STATEMENT(event)
Definition: trigger.h:131
HeapTuple tg_trigtuple
Definition: trigger.h:35
#define TRIGGER_FIRED_BY_TRUNCATE(event)
Definition: trigger.h:125
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define DatumGetCString(X)
Definition: postgres.h:572
char * tgname
Definition: reltrigger.h:27
Definition: type.h:82
Oid rd_id
Definition: rel.h:116
static SV * plperl_hash_from_tuple(HeapTuple tuple, TupleDesc tupdesc)
Definition: plperl.c:3000
char ** tgargs
Definition: reltrigger.h:40
#define newRV_noinc(a)
Definition: ppport.h:4456
#define TRIGGER_FIRED_BY_DELETE(event)
Definition: trigger.h:119
struct @18::@19 av[32]
Trigger * tg_trigger
Definition: trigger.h:37
TupleDesc rd_att
Definition: rel.h:115
HeapTuple tg_newtuple
Definition: trigger.h:36
static SV * cstr2sv(const char *str)
char * SPI_getrelname(Relation rel)
Definition: spi.c:912
TriggerEvent tg_event
Definition: trigger.h:33
char * SPI_getnspname(Relation rel)
Definition: spi.c:918
#define TRIGGER_FIRED_BEFORE(event)
Definition: trigger.h:134
#define TRIGGER_FIRED_INSTEAD(event)
Definition: trigger.h:140
#define TRIGGER_FIRED_BY_INSERT(event)
Definition: trigger.h:116
int i
int16 tgnargs
Definition: reltrigger.h:37
#define TRIGGER_FIRED_FOR_ROW(event)
Definition: trigger.h:128
#define TRIGGER_FIRED_BY_UPDATE(event)
Definition: trigger.h:122
Relation tg_relation
Definition: trigger.h:34
static Datum plperl_trigger_handler ( PG_FUNCTION_ARGS  )
static

Definition at line 2489 of file plperl.c.

References activate_interpreter(), ErrorContextCallback::arg, Assert, ErrorContextCallback::callback, compile_plperl_function(), elog, ereport, errcode(), errmsg(), ERROR, error_context_stack, 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_CONNECT, 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().

2490 {
2491  plperl_proc_desc *prodesc;
2492  SV *perlret;
2493  Datum retval;
2494  SV *svTD;
2495  HV *hvTD;
2496  ErrorContextCallback pl_error_context;
2497  TriggerData *tdata;
2498  int rc PG_USED_FOR_ASSERTS_ONLY;
2499 
2500  /* Connect to SPI manager */
2501  if (SPI_connect() != SPI_OK_CONNECT)
2502  elog(ERROR, "could not connect to SPI manager");
2503 
2504  /* Make transition tables visible to this SPI connection */
2505  tdata = (TriggerData *) fcinfo->context;
2506  rc = SPI_register_trigger_data(tdata);
2507  Assert(rc >= 0);
2508 
2509  /* Find or compile the function */
2510  prodesc = compile_plperl_function(fcinfo->flinfo->fn_oid, true, false);
2511  current_call_data->prodesc = prodesc;
2512  increment_prodesc_refcount(prodesc);
2513 
2514  /* Set a callback for error reporting */
2515  pl_error_context.callback = plperl_exec_callback;
2516  pl_error_context.previous = error_context_stack;
2517  pl_error_context.arg = prodesc->proname;
2518  error_context_stack = &pl_error_context;
2519 
2520  activate_interpreter(prodesc->interp);
2521 
2522  svTD = plperl_trigger_build_args(fcinfo);
2523  perlret = plperl_call_perl_trigger_func(prodesc, fcinfo, svTD);
2524  hvTD = (HV *) SvRV(svTD);
2525 
2526  /************************************************************
2527  * Disconnect from SPI manager and then create the return
2528  * values datum (if the input function does a palloc for it
2529  * this must not be allocated in the SPI memory context
2530  * because SPI_finish would free it).
2531  ************************************************************/
2532  if (SPI_finish() != SPI_OK_FINISH)
2533  elog(ERROR, "SPI_finish() failed");
2534 
2535  if (perlret == NULL || !SvOK(perlret))
2536