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

Go to the source code of this file.

Data Structures

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

Macros

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

Typedefs

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

Functions

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

Variables

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

Macro Definition Documentation

◆ decrement_prodesc_refcount

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

Definition at line 131 of file plperl.c.

◆ increment_prodesc_refcount

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

Definition at line 129 of file plperl.c.

◆ setlocale_perl

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

Definition at line 304 of file plperl.c.

◆ TEXTDOMAIN

#define TEXTDOMAIN   PG_TEXTDOMAIN("plperl")

Definition at line 42 of file plperl.c.

Typedef Documentation

◆ plperl_array_info

◆ plperl_call_data

◆ plperl_interp_desc

◆ plperl_proc_desc

◆ plperl_proc_key

◆ plperl_proc_ptr

◆ plperl_query_desc

◆ plperl_query_entry

Function Documentation

◆ _PG_init()

void _PG_init ( void  )

Definition at line 382 of file plperl.c.

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 MarkGUCPrefixReserved("plperl");
459
460 /*
461 * Create hash tables.
462 */
463 hash_ctl.keysize = sizeof(Oid);
464 hash_ctl.entrysize = sizeof(plperl_interp_desc);
465 plperl_interp_hash = hash_create("PL/Perl interpreters",
466 8,
467 &hash_ctl,
469
470 hash_ctl.keysize = sizeof(plperl_proc_key);
471 hash_ctl.entrysize = sizeof(plperl_proc_ptr);
472 plperl_proc_hash = hash_create("PL/Perl procedures",
473 32,
474 &hash_ctl,
476
477 /*
478 * Save the default opmask.
479 */
480 PLPERL_SET_OPMASK(plperl_opmask);
481
482 /*
483 * Create the first Perl interpreter, but only partially initialize it.
484 */
486
487 inited = true;
488}
#define gettext_noop(x)
Definition: c.h:1167
HTAB * hash_create(const char *tabname, long nelem, const HASHCTL *info, int flags)
Definition: dynahash.c:352
void DefineCustomStringVariable(const char *name, const char *short_desc, const char *long_desc, char **valueAddr, const char *bootValue, GucContext context, int flags, GucStringCheckHook check_hook, GucStringAssignHook assign_hook, GucShowHook show_hook)
Definition: guc.c:5219
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:5133
void MarkGUCPrefixReserved(const char *className)
Definition: guc.c:5280
@ PGC_SUSET
Definition: guc.h:78
@ PGC_USERSET
Definition: guc.h:79
@ PGC_SIGHUP
Definition: guc.h:75
#define HASH_ELEM
Definition: hsearch.h:95
#define HASH_BLOBS
Definition: hsearch.h:97
void pg_bindtextdomain(const char *domain)
Definition: miscinit.c:1939
static HTAB * plperl_interp_hash
Definition: plperl.c:225
static char plperl_opmask[MAXO]
Definition: plperl.c:240
static bool plperl_use_strict
Definition: plperl.c:233
struct plperl_proc_key plperl_proc_key
static HTAB * plperl_proc_hash
Definition: plperl.c:226
static PerlInterpreter * plperl_held_interp
Definition: plperl.c:230
#define TEXTDOMAIN
Definition: plperl.c:42
static char * plperl_on_init
Definition: plperl.c:234
static char * plperl_on_plperl_init
Definition: plperl.c:235
struct plperl_proc_ptr plperl_proc_ptr
struct plperl_interp_desc plperl_interp_desc
static PerlInterpreter * plperl_init_interp(void)
Definition: plperl.c:707
static char * plperl_on_plperlu_init
Definition: plperl.c:236
unsigned int Oid
Definition: postgres_ext.h:30
Size keysize
Definition: hsearch.h:75
Size entrysize
Definition: hsearch.h:76

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

◆ _sv_to_datum_finfo()

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

Definition at line 1302 of file plperl.c.

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

References fmgr_info(), and getTypeInputInfo().

Referenced by plperl_array_to_datum(), and plperl_sv_to_datum().

◆ activate_interpreter()

static void activate_interpreter ( plperl_interp_desc interp_desc)
static

Definition at line 686 of file plperl.c.

687{
688 if (interp_desc && plperl_active_interp != interp_desc)
689 {
690 Assert(interp_desc->interp);
691 PERL_SET_CONTEXT(interp_desc->interp);
692 /* trusted iff user_id isn't InvalidOid */
694 plperl_active_interp = interp_desc;
695 }
696}
#define OidIsValid(objectId)
Definition: c.h:746
Assert(PointerIsAligned(start, uint64))
static void set_interp_require(bool trusted)
Definition: plperl.c:492
static plperl_interp_desc * plperl_active_interp
Definition: plperl.c:227
PerlInterpreter * interp
Definition: plperl.c:88

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

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

◆ array_to_datum_internal()

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

Definition at line 1172 of file plperl.c.

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

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

Referenced by array_to_datum_internal(), and plperl_array_to_datum().

◆ boot_DynaLoader()

EXTERN_C void boot_DynaLoader ( pTHX_ CV *  cv)

Referenced by plperl_init_shared_libs().

◆ boot_PostgreSQL__InServer__SPI()

EXTERN_C void boot_PostgreSQL__InServer__SPI ( pTHX_ CV *  cv)

Referenced by select_perl_context().

◆ boot_PostgreSQL__InServer__Util()

EXTERN_C void boot_PostgreSQL__InServer__Util ( pTHX_ CV *  cv)

Referenced by plperl_init_shared_libs().

◆ check_spi_usage_allowed()

static void check_spi_usage_allowed ( void  )
static

Definition at line 3107 of file plperl.c.

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

References current_call_data, plperl_ending, and plperl_call_data::prodesc.

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

◆ compile_plperl_function()

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

Definition at line 2716 of file plperl.c.

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

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

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

◆ free_plperl_function()

static void free_plperl_function ( plperl_proc_desc prodesc)
static

Definition at line 2698 of file plperl.c.

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

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

Referenced by compile_plperl_function().

◆ get_perl_array_ref()

static SV * get_perl_array_ref ( SV *  sv)
static

Definition at line 1140 of file plperl.c.

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

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

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

◆ hek2cstr()

static char * hek2cstr ( HE *  he)
static

Definition at line 325 of file plperl.c.

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}
static char * sv2cstr(SV *sv)
Definition: plperl.h:89
#define HeUTF8(he)

References dTHX, HeUTF8, and sv2cstr().

Referenced by plperl_build_tuple_result(), and plperl_modify_tuple().

◆ hv_fetch_string()

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

Definition at line 4121 of file plperl.c.

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

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

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

◆ hv_store_string()

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

Definition at line 4094 of file plperl.c.

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

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

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

◆ make_array_ref()

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

Definition at line 1595 of file plperl.c.

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

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

Referenced by split_array().

◆ PG_FUNCTION_INFO_V1() [1/6]

PG_FUNCTION_INFO_V1 ( plperl_call_handler  )

◆ PG_FUNCTION_INFO_V1() [2/6]

PG_FUNCTION_INFO_V1 ( plperl_inline_handler  )

◆ PG_FUNCTION_INFO_V1() [3/6]

PG_FUNCTION_INFO_V1 ( plperl_validator  )

◆ PG_FUNCTION_INFO_V1() [4/6]

PG_FUNCTION_INFO_V1 ( plperlu_call_handler  )

◆ PG_FUNCTION_INFO_V1() [5/6]

PG_FUNCTION_INFO_V1 ( plperlu_inline_handler  )

◆ PG_FUNCTION_INFO_V1() [6/6]

PG_FUNCTION_INFO_V1 ( plperlu_validator  )

◆ PG_MODULE_MAGIC_EXT()

PG_MODULE_MAGIC_EXT ( name = "plperl",
version = PG_VERSION 
)

◆ plperl_array_to_datum()

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

Definition at line 1259 of file plperl.c.

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

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

Referenced by plperl_sv_to_datum().

◆ plperl_build_tuple_result()

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

Definition at line 1077 of file plperl.c.

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

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

Referenced by plperl_hash_to_datum(), and plperl_return_next_internal().

◆ plperl_call_handler()

Datum plperl_call_handler ( PG_FUNCTION_ARGS  )

Definition at line 1854 of file plperl.c.

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

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

Referenced by plperlu_call_handler().

◆ plperl_call_perl_event_trigger_func()

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

Definition at line 2342 of file plperl.c.

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

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

Referenced by plperl_event_trigger_handler().

◆ plperl_call_perl_func()

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

Definition at line 2181 of file plperl.c.

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

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

Referenced by plperl_func_handler(), and plperl_inline_handler().

◆ plperl_call_perl_trigger_func()

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

Definition at line 2274 of file plperl.c.

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

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

Referenced by plperl_trigger_handler().

◆ plperl_compile_callback()

static void plperl_compile_callback ( void *  arg)
static

Definition at line 4156 of file plperl.c.

4157{
4158 char *procname = (char *) arg;
4159
4160 if (procname)
4161 errcontext("compilation of PL/Perl function \"%s\"", procname);
4162}
#define errcontext
Definition: elog.h:197
void * arg

References arg, and errcontext.

Referenced by compile_plperl_function().

◆ plperl_create_sub()

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

Definition at line 2096 of file plperl.c.

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

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

Referenced by compile_plperl_function(), and plperl_inline_handler().

◆ plperl_destroy_interp()

static void plperl_destroy_interp ( PerlInterpreter **  interp)
static

Definition at line 920 of file plperl.c.

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

References dTHX, PERL_UNUSED_VAR, and x.

Referenced by plperl_fini().

◆ plperl_event_trigger_build_args()

static SV * plperl_event_trigger_build_args ( FunctionCallInfo  fcinfo)
static

Definition at line 1746 of file plperl.c.

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

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

Referenced by plperl_event_trigger_handler().

◆ plperl_event_trigger_handler()

static void plperl_event_trigger_handler ( PG_FUNCTION_ARGS  )
static

Definition at line 2633 of file plperl.c.

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

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

Referenced by plperl_call_handler().

◆ plperl_exec_callback()

static void plperl_exec_callback ( void *  arg)
static

Definition at line 4144 of file plperl.c.

4145{
4146 char *procname = (char *) arg;
4147
4148 if (procname)
4149 errcontext("PL/Perl function \"%s\"", procname);
4150}

References arg, and errcontext.

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

◆ plperl_fini()

static void plperl_fini ( int  code,
Datum  arg 
)
static

Definition at line 511 of file plperl.c.

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

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

Referenced by select_perl_context().

◆ plperl_func_handler()

static Datum plperl_func_handler ( PG_FUNCTION_ARGS  )
static

Definition at line 2403 of file plperl.c.

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

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

Referenced by plperl_call_handler().

◆ plperl_hash_from_datum()

static SV * plperl_hash_from_datum ( Datum  attr)
static

Definition at line 2996 of file plperl.c.

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

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

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

◆ plperl_hash_from_tuple()

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

Definition at line 3024 of file plperl.c.

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

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

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

◆ plperl_hash_to_datum()

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

Definition at line 1128 of file plperl.c.

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

References HeapTupleGetDatum(), and plperl_build_tuple_result().

Referenced by plperl_sv_to_datum().

◆ plperl_init_interp()

static PerlInterpreter * plperl_init_interp ( void  )
static

Definition at line 707 of file plperl.c.

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

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

Referenced by _PG_init(), and select_perl_context().

◆ plperl_init_shared_libs()

static void plperl_init_shared_libs ( pTHX  )
static

Definition at line 2169 of file plperl.c.

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

References boot_DynaLoader(), and boot_PostgreSQL__InServer__Util().

Referenced by plperl_init_interp().

◆ plperl_inline_callback()

static void plperl_inline_callback ( void *  arg)
static

Definition at line 4168 of file plperl.c.

4169{
4170 errcontext("PL/Perl anonymous code block");
4171}

References errcontext.

Referenced by plperl_inline_handler().

◆ plperl_inline_handler()

Datum plperl_inline_handler ( PG_FUNCTION_ARGS  )

Definition at line 1896 of file plperl.c.

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

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

Referenced by plperlu_inline_handler().

◆ plperl_modify_tuple()

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

Definition at line 1764 of file plperl.c.

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

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

Referenced by plperl_trigger_handler().

◆ plperl_ref_from_pg_array()

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

Definition at line 1482 of file plperl.c.

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

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

Referenced by plperl_call_perl_func(), and plperl_hash_from_tuple().

◆ plperl_return_next()

void plperl_return_next ( SV *  sv)

Definition at line 3246 of file plperl.c.

3247{
3249
3251
3252 PG_TRY();
3253 {
3255 }
3256 PG_CATCH();
3257 {
3258 ErrorData *edata;
3259
3260 /* Must reset elog.c's state */
3261 MemoryContextSwitchTo(oldcontext);
3262 edata = CopyErrorData();
3264
3265 /* Punt the error to Perl */
3266 croak_cstr(edata->message);
3267 }
3268 PG_END_TRY();
3269}
ErrorData * CopyErrorData(void)
Definition: elog.c:1751
void FlushErrorState(void)
Definition: elog.c:1872
static void check_spi_usage_allowed(void)
Definition: plperl.c:3107
static void croak_cstr(const char *str)
Definition: plperl.h:175
char * message
Definition: elog.h:431

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

◆ plperl_return_next_internal()

static void plperl_return_next_internal ( SV *  sv)
static

Definition at line 3276 of file plperl.c.

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

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

Referenced by plperl_func_handler(), and plperl_return_next().

◆ plperl_spi_commit()

void plperl_spi_commit ( void  )

Definition at line 3992 of file plperl.c.

3993{
3995
3997
3998 PG_TRY();
3999 {
4000 SPI_commit();
4001 }
4002 PG_CATCH();
4003 {
4004 ErrorData *edata;
4005
4006 /* Save error info */
4007 MemoryContextSwitchTo(oldcontext);
4008 edata = CopyErrorData();
4010
4011 /* Punt the error to Perl */
4012 croak_cstr(edata->message);
4013 }
4014 PG_END_TRY();
4015}
void SPI_commit(void)
Definition: spi.c:321

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

◆ plperl_spi_cursor_close()

void plperl_spi_cursor_close ( char *  cursor)

Definition at line 3552 of file plperl.c.

3553{
3554 Portal p;
3555
3557
3559
3560 if (p)
3561 {
3562 UnpinPortal(p);
3564 }
3565}
void UnpinPortal(Portal portal)
Definition: portalmem.c:382
Portal SPI_cursor_find(const char *name)
Definition: spi.c:1796
void SPI_cursor_close(Portal portal)
Definition: spi.c:1864
Definition: type.h:138

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

◆ plperl_spi_exec()

HV * plperl_spi_exec ( char *  query,
int  limit 
)

Definition at line 3134 of file plperl.c.

3135{
3136 HV *ret_hv;
3137
3138 /*
3139 * Execute the query inside a sub-transaction, so we can cope with errors
3140 * sanely
3141 */
3144
3146
3148 /* Want to run inside function's memory context */
3149 MemoryContextSwitchTo(oldcontext);
3150
3151 PG_TRY();
3152 {
3153 int spi_rv;
3154
3155 pg_verifymbstr(query, strlen(query), false);
3156
3158 limit);
3160 spi_rv);
3161
3162 /* Commit the inner transaction, return to outer xact context */
3164 MemoryContextSwitchTo(oldcontext);
3165 CurrentResourceOwner = oldowner;
3166 }
3167 PG_CATCH();
3168 {
3169 ErrorData *edata;
3170
3171 /* Save error info */
3172 MemoryContextSwitchTo(oldcontext);
3173 edata = CopyErrorData();
3175
3176 /* Abort the inner transaction */
3178 MemoryContextSwitchTo(oldcontext);
3179 CurrentResourceOwner = oldowner;
3180
3181 /* Punt the error to Perl */
3182 croak_cstr(edata->message);
3183
3184 /* Can't get here, but keep compiler quiet */
3185 return NULL;
3186 }
3187 PG_END_TRY();
3188
3189 return ret_hv;
3190}
bool pg_verifymbstr(const char *mbstr, int len, bool noError)
Definition: mbutils.c:1556
static HV * plperl_spi_execute_fetch_result(SPITupleTable *, uint64, int)
Definition: plperl.c:3194
ResourceOwner CurrentResourceOwner
Definition: resowner.c:173
uint64 SPI_processed
Definition: spi.c:44
SPITupleTable * SPI_tuptable
Definition: spi.c:45
int SPI_execute(const char *src, bool read_only, long tcount)
Definition: spi.c:597
void BeginInternalSubTransaction(const char *name)
Definition: xact.c:4694
void RollbackAndReleaseCurrentSubTransaction(void)
Definition: xact.c:4796
void ReleaseCurrentSubTransaction(void)
Definition: xact.c:4768

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

◆ plperl_spi_exec_prepared()

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

Definition at line 3716 of file plperl.c.

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

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

◆ plperl_spi_execute_fetch_result()

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

Definition at line 3194 of file plperl.c.

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

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

Referenced by plperl_spi_exec(), and plperl_spi_exec_prepared().

◆ plperl_spi_fetchrow()

SV * plperl_spi_fetchrow ( char *  cursor)

Definition at line 3477 of file plperl.c.

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

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

◆ plperl_spi_freeplan()

void plperl_spi_freeplan ( char *  query)

Definition at line 3961 of file plperl.c.

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

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

◆ plperl_spi_prepare()

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

Definition at line 3568 of file plperl.c.

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

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

◆ plperl_spi_query()

SV * plperl_spi_query ( char *  query)

Definition at line 3405 of file plperl.c.

3406{
3407 SV *cursor;
3408
3409 /*
3410 * Execute the query inside a sub-transaction, so we can cope with errors
3411 * sanely
3412 */
3415
3417
3419 /* Want to run inside function's memory context */
3420 MemoryContextSwitchTo(oldcontext);
3421
3422 PG_TRY();
3423 {
3425 Portal portal;
3426
3427 /* Make sure the query is validly encoded */
3428 pg_verifymbstr(query, strlen(query), false);
3429
3430 /* Create a cursor for the query */
3431 plan = SPI_prepare(query, 0, NULL);
3432 if (plan == NULL)
3433 elog(ERROR, "SPI_prepare() failed:%s",
3435
3436 portal = SPI_cursor_open(NULL, plan, NULL, NULL, false);
3438 if (portal == NULL)
3439 elog(ERROR, "SPI_cursor_open() failed:%s",
3441 cursor = cstr2sv(portal->name);
3442
3443 PinPortal(portal);
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();
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 cursor;
3473}
void PinPortal(Portal portal)
Definition: portalmem.c:373
Portal SPI_cursor_open(const char *name, SPIPlanPtr plan, Datum *Values, const char *Nulls, bool read_only)
Definition: spi.c:1446
const char * name
Definition: portal.h:118

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

◆ plperl_spi_query_prepared()

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

Definition at line 3843 of file plperl.c.

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

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

◆ plperl_spi_rollback()

void plperl_spi_rollback ( void  )

Definition at line 4018 of file plperl.c.

4019{
4021
4023
4024 PG_TRY();
4025 {
4026 SPI_rollback();
4027 }
4028 PG_CATCH();
4029 {
4030 ErrorData *edata;
4031
4032 /* Save error info */
4033 MemoryContextSwitchTo(oldcontext);
4034 edata = CopyErrorData();
4036
4037 /* Punt the error to Perl */
4038 croak_cstr(edata->message);
4039 }
4040 PG_END_TRY();
4041}
void SPI_rollback(void)
Definition: spi.c:414

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

◆ plperl_sv_to_datum()

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

Definition at line 1325 of file plperl.c.

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

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

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

◆ plperl_sv_to_literal()

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

Definition at line 1446 of file plperl.c.

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

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

◆ plperl_trigger_build_args()

static SV * plperl_trigger_build_args ( FunctionCallInfo  fcinfo)
static

Definition at line 1633 of file plperl.c.

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

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

Referenced by plperl_trigger_handler().

◆ plperl_trigger_handler()

static Datum plperl_trigger_handler ( PG_FUNCTION_ARGS  )
static

Definition at line 2521 of file plperl.c.

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

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

Referenced by plperl_call_handler().

◆ plperl_trusted_init()

static void plperl_trusted_init ( void  )
static

Definition at line 959 of file plperl.c.

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

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

Referenced by select_perl_context().

◆ plperl_untrusted_init()

static void plperl_untrusted_init ( void  )
static

Definition at line 1040 of file plperl.c.

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

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

Referenced by select_perl_context().

◆ plperl_util_elog()

void plperl_util_elog ( int  level,
SV *  msg 
)

Definition at line 4055 of file plperl.c.

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

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

◆ plperl_validator()

Datum plperl_validator ( PG_FUNCTION_ARGS  )

Definition at line 1990 of file plperl.c.

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

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

Referenced by plperlu_validator().

◆ plperlu_call_handler()

Datum plperlu_call_handler ( PG_FUNCTION_ARGS  )

Definition at line 2068 of file plperl.c.

2069{
2070 return plperl_call_handler(fcinfo);
2071}
Datum plperl_call_handler(PG_FUNCTION_ARGS)
Definition: plperl.c:1854

References plperl_call_handler().

◆ plperlu_inline_handler()

Datum plperlu_inline_handler ( PG_FUNCTION_ARGS  )

Definition at line 2076 of file plperl.c.

2077{
2078 return plperl_inline_handler(fcinfo);
2079}
Datum plperl_inline_handler(PG_FUNCTION_ARGS)
Definition: plperl.c:1896

References plperl_inline_handler().

◆ plperlu_validator()

Datum plperlu_validator ( PG_FUNCTION_ARGS  )

Definition at line 2084 of file plperl.c.

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

References plperl_validator().

◆ pp_require_safe()

static OP * pp_require_safe ( pTHX  )
static

Definition at line 882 of file plperl.c.

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

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

Referenced by plperl_trusted_init(), and set_interp_require().

◆ select_perl_context()

static void select_perl_context ( bool  trusted)
static

Definition at line 555 of file plperl.c.

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

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

Referenced by compile_plperl_function(), and plperl_inline_handler().

◆ set_interp_require()

static void set_interp_require ( bool  trusted)
static

Definition at line 492 of file plperl.c.

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

References PL_ppaddr, pp_require_orig, and pp_require_safe().

Referenced by activate_interpreter(), and select_perl_context().

◆ split_array()

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

Definition at line 1561 of file plperl.c.

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

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

Referenced by plperl_ref_from_pg_array(), and split_array().

◆ strip_trailing_ws()

static char * strip_trailing_ws ( const char *  msg)
static

Definition at line 1063 of file plperl.c.

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

References len, and pstrdup().

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

◆ SvREFCNT_dec_current()

static void SvREFCNT_dec_current ( SV *  sv)
inlinestatic

Definition at line 314 of file plperl.c.

315{
316 dTHX;
317
318 SvREFCNT_dec(sv);
319}

References dTHX.

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

◆ validate_plperl_function()

static bool validate_plperl_function ( plperl_proc_ptr proc_ptr,
HeapTuple  procTup 
)
static

Definition at line 2669 of file plperl.c.

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

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

Referenced by compile_plperl_function().

Variable Documentation

◆ current_call_data

◆ plperl_active_interp

◆ plperl_ending

bool plperl_ending = false
static

Definition at line 238 of file plperl.c.

Referenced by check_spi_usage_allowed(), and plperl_fini().

◆ plperl_held_interp

PerlInterpreter* plperl_held_interp = NULL
static

Definition at line 230 of file plperl.c.

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

◆ plperl_interp_hash

HTAB* plperl_interp_hash = NULL
static

Definition at line 225 of file plperl.c.

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

◆ plperl_on_init

char* plperl_on_init = NULL
static

Definition at line 234 of file plperl.c.

Referenced by _PG_init(), and plperl_init_interp().

◆ plperl_on_plperl_init

char* plperl_on_plperl_init = NULL
static

Definition at line 235 of file plperl.c.

Referenced by _PG_init(), and plperl_trusted_init().

◆ plperl_on_plperlu_init

char* plperl_on_plperlu_init = NULL
static

Definition at line 236 of file plperl.c.

Referenced by _PG_init(), and plperl_untrusted_init().

◆ plperl_opmask

char plperl_opmask[MAXO]
static

Definition at line 240 of file plperl.c.

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

◆ plperl_proc_hash

HTAB* plperl_proc_hash = NULL
static

Definition at line 226 of file plperl.c.

Referenced by _PG_init(), and compile_plperl_function().

◆ plperl_use_strict

bool plperl_use_strict = false
static

Definition at line 233 of file plperl.c.

Referenced by _PG_init(), and plperl_create_sub().

◆ pp_require_orig

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

Definition at line 239 of file plperl.c.

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