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

Go to the source code of this file.

Data Structures

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

Macros

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

Typedefs

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

Functions

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

Variables

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

Macro Definition Documentation

◆ decrement_prodesc_refcount

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

Definition at line 128 of file plperl.c.

◆ increment_prodesc_refcount

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

Definition at line 126 of file plperl.c.

◆ setlocale_perl

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

Definition at line 301 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 379 of file plperl.c.

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

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

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 683 of file plperl.c.

684{
685 if (interp_desc && plperl_active_interp != interp_desc)
686 {
687 Assert(interp_desc->interp);
688 PERL_SET_CONTEXT(interp_desc->interp);
689 /* trusted iff user_id isn't InvalidOid */
691 plperl_active_interp = interp_desc;
692 }
693}
#define Assert(condition)
Definition: c.h:815
#define OidIsValid(objectId)
Definition: c.h:732
static void set_interp_require(bool trusted)
Definition: plperl.c:489
static plperl_interp_desc * plperl_active_interp
Definition: plperl.c:224
PerlInterpreter * interp
Definition: plperl.c:85

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 1169 of file plperl.c.

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

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

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 2713 of file plperl.c.

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

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

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 1137 of file plperl.c.

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

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 322 of file plperl.c.

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

4119{
4120 dTHX;
4121 int32 hlen;
4122 char *hkey;
4123 SV **ret;
4124
4125 hkey = pg_server_to_any(key, strlen(key), PG_UTF8);
4126
4127 /* See notes in hv_store_string */
4128 hlen = -(int) strlen(hkey);
4129 ret = hv_fetch(hv, hkey, hlen, 0);
4130
4131 if (hkey != key)
4132 pfree(hkey);
4133
4134 return ret;
4135}
int32_t int32
Definition: c.h:484
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 4091 of file plperl.c.

4092{
4093 dTHX;
4094 int32 hlen;
4095 char *hkey;
4096 SV **ret;
4097
4098 hkey = pg_server_to_any(key, strlen(key), PG_UTF8);
4099
4100 /*
4101 * hv_store() recognizes a negative klen parameter as meaning a UTF-8
4102 * encoded key.
4103 */
4104 hlen = -(int) strlen(hkey);
4105 ret = hv_store(hv, hkey, hlen, val, 0);
4106
4107 if (hkey != key)
4108 pfree(hkey);
4109
4110 return ret;
4111}
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 1592 of file plperl.c.

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

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

Referenced by split_array().

◆ PG_FUNCTION_INFO_V1() [1/6]

PG_FUNCTION_INFO_V1 ( plperl_call_handler  )

◆ PG_FUNCTION_INFO_V1() [2/6]

PG_FUNCTION_INFO_V1 ( plperl_inline_handler  )

◆ PG_FUNCTION_INFO_V1() [3/6]

PG_FUNCTION_INFO_V1 ( plperl_validator  )

◆ PG_FUNCTION_INFO_V1() [4/6]

PG_FUNCTION_INFO_V1 ( plperlu_call_handler  )

◆ PG_FUNCTION_INFO_V1() [5/6]

PG_FUNCTION_INFO_V1 ( plperlu_inline_handler  )

◆ PG_FUNCTION_INFO_V1() [6/6]

PG_FUNCTION_INFO_V1 ( plperlu_validator  )

◆ plperl_array_to_datum()

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

Definition at line 1256 of file plperl.c.

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

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

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 1851 of file plperl.c.

1852{
1853 Datum retval = (Datum) 0;
1854 plperl_call_data *volatile save_call_data = current_call_data;
1855 plperl_interp_desc *volatile oldinterp = plperl_active_interp;
1856 plperl_call_data this_call_data;
1857
1858 /* Initialize current-call status record */
1859 MemSet(&this_call_data, 0, sizeof(this_call_data));
1860 this_call_data.fcinfo = fcinfo;
1861
1862 PG_TRY();
1863 {
1864 current_call_data = &this_call_data;
1865 if (CALLED_AS_TRIGGER(fcinfo))
1866 retval = plperl_trigger_handler(fcinfo);
1867 else if (CALLED_AS_EVENT_TRIGGER(fcinfo))
1868 {
1870 retval = (Datum) 0;
1871 }
1872 else
1873 retval = plperl_func_handler(fcinfo);
1874 }
1875 PG_FINALLY();
1876 {
1877 current_call_data = save_call_data;
1878 activate_interpreter(oldinterp);
1879 if (this_call_data.prodesc)
1880 decrement_prodesc_refcount(this_call_data.prodesc);
1881 }
1882 PG_END_TRY();
1883
1884 return retval;
1885}
#define MemSet(start, val, len)
Definition: c.h:977
#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:2630
static Datum plperl_func_handler(PG_FUNCTION_ARGS)
Definition: plperl.c:2400
#define decrement_prodesc_refcount(prodesc)
Definition: plperl.c:128
static Datum plperl_trigger_handler(PG_FUNCTION_ARGS)
Definition: plperl.c:2518
FunctionCallInfo fcinfo
Definition: plperl.c:173
#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 2339 of file plperl.c.

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

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

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

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

References arg, and errcontext.

Referenced by compile_plperl_function().

◆ plperl_create_sub()

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

Definition at line 2093 of file plperl.c.

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

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

1744{
1745 dTHX;
1746 EventTriggerData *tdata;
1747 HV *hv;
1748
1749 hv = newHV();
1750
1751 tdata = (EventTriggerData *) fcinfo->context;
1752
1753 hv_store_string(hv, "event", cstr2sv(tdata->event));
1754 hv_store_string(hv, "tag", cstr2sv(GetCommandTagName(tdata->tag)));
1755
1756 return newRV_noinc((SV *) hv);
1757}
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 2630 of file plperl.c.

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

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

Referenced by plperl_call_handler().

◆ plperl_exec_callback()

static void plperl_exec_callback ( void *  arg)
static

Definition at line 4141 of file plperl.c.

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

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 508 of file plperl.c.

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

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 2400 of file plperl.c.

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

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 2993 of file plperl.c.

2994{
2995 HeapTupleHeader td;
2996 Oid tupType;
2997 int32 tupTypmod;
2998 TupleDesc tupdesc;
2999 HeapTupleData tmptup;
3000 SV *sv;
3001
3002 td = DatumGetHeapTupleHeader(attr);
3003
3004 /* Extract rowtype info and find a tupdesc */
3005 tupType = HeapTupleHeaderGetTypeId(td);
3006 tupTypmod = HeapTupleHeaderGetTypMod(td);
3007 tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
3008
3009 /* Build a temporary HeapTuple control structure */
3011 tmptup.t_data = td;
3012
3013 sv = plperl_hash_from_tuple(&tmptup, tupdesc, true);
3014 ReleaseTupleDesc(tupdesc);
3015
3016 return sv;
3017}
#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:3021
uint32 t_len
Definition: htup.h:64
#define ReleaseTupleDesc(tupdesc)
Definition: tupdesc.h:213
TupleDesc lookup_rowtype_tupdesc(Oid type_id, int32 typmod)
Definition: typcache.c:1920

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 3021 of file plperl.c.

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

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

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 704 of file plperl.c.

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

2167{
2168 char *file = __FILE__;
2169
2170 newXS("DynaLoader::boot_DynaLoader", boot_DynaLoader, file);
2171 newXS("PostgreSQL::InServer::Util::bootstrap",
2173 /* newXS for...::SPI::bootstrap is in select_perl_context() */
2174}
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 4165 of file plperl.c.

4166{
4167 errcontext("PL/Perl anonymous code block");
4168}

References errcontext.

Referenced by plperl_inline_handler().

◆ plperl_inline_handler()

Datum plperl_inline_handler ( PG_FUNCTION_ARGS  )

Definition at line 1893 of file plperl.c.

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

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 1761 of file plperl.c.

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

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

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

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

◆ plperl_return_next_internal()

static void plperl_return_next_internal ( SV *  sv)
static

Definition at line 3273 of file plperl.c.

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

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

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

◆ plperl_spi_cursor_close()

void plperl_spi_cursor_close ( char *  cursor)

Definition at line 3549 of file plperl.c.

3550{
3551 Portal p;
3552
3554
3556
3557 if (p)
3558 {
3559 UnpinPortal(p);
3561 }
3562}
void UnpinPortal(Portal portal)
Definition: portalmem.c:380
Portal SPI_cursor_find(const char *name)
Definition: spi.c:1794
void SPI_cursor_close(Portal portal)
Definition: spi.c:1862
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 3131 of file plperl.c.

3132{
3133 HV *ret_hv;
3134
3135 /*
3136 * Execute the query inside a sub-transaction, so we can cope with errors
3137 * sanely
3138 */
3141
3143
3145 /* Want to run inside function's memory context */
3146 MemoryContextSwitchTo(oldcontext);
3147
3148 PG_TRY();
3149 {
3150 int spi_rv;
3151
3152 pg_verifymbstr(query, strlen(query), false);
3153
3155 limit);
3157 spi_rv);
3158
3159 /* Commit the inner transaction, return to outer xact context */
3161 MemoryContextSwitchTo(oldcontext);
3162 CurrentResourceOwner = oldowner;
3163 }
3164 PG_CATCH();
3165 {
3166 ErrorData *edata;
3167
3168 /* Save error info */
3169 MemoryContextSwitchTo(oldcontext);
3170 edata = CopyErrorData();
3172
3173 /* Abort the inner transaction */
3175 MemoryContextSwitchTo(oldcontext);
3176 CurrentResourceOwner = oldowner;
3177
3178 /* Punt the error to Perl */
3179 croak_cstr(edata->message);
3180
3181 /* Can't get here, but keep compiler quiet */
3182 return NULL;
3183 }
3184 PG_END_TRY();
3185
3186 return ret_hv;
3187}
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:3191
ResourceOwner CurrentResourceOwner
Definition: resowner.c:165
uint64 SPI_processed
Definition: spi.c:44
SPITupleTable * SPI_tuptable
Definition: spi.c:45
int SPI_execute(const char *src, bool read_only, long tcount)
Definition: spi.c:596
void BeginInternalSubTransaction(const char *name)
Definition: xact.c:4686
void RollbackAndReleaseCurrentSubTransaction(void)
Definition: xact.c:4788
void ReleaseCurrentSubTransaction(void)
Definition: xact.c:4760

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 3713 of file plperl.c.

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

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 3191 of file plperl.c.

3193{
3194 dTHX;
3195 HV *result;
3196
3198
3199 result = newHV();
3200
3201 hv_store_string(result, "status",
3203 hv_store_string(result, "processed",
3204 (processed > (uint64) UV_MAX) ?
3205 newSVnv((NV) processed) :
3206 newSVuv((UV) processed));
3207
3208 if (status > 0 && tuptable)
3209 {
3210 AV *rows;
3211 SV *row;
3212 uint64 i;
3213
3214 /* Prevent overflow in call to av_extend() */
3215 if (processed > (uint64) AV_SIZE_MAX)
3216 ereport(ERROR,
3217 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
3218 errmsg("query result has too many rows to fit in a Perl array")));
3219
3220 rows = newAV();
3221 av_extend(rows, processed);
3222 for (i = 0; i < processed; i++)
3223 {
3224 row = plperl_hash_from_tuple(tuptable->vals[i], tuptable->tupdesc, true);
3225 av_push(rows, row);
3226 }
3227 hv_store_string(result, "rows",
3228 newRV_noinc((SV *) rows));
3229 }
3230
3231 SPI_freetuptable(tuptable);
3232
3233 return result;
3234}
uint64_t uint64
Definition: c.h:489
#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:1972
void SPI_freetuptable(SPITupleTable *tuptable)
Definition: spi.c:1386
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 3474 of file plperl.c.

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

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 3958 of file plperl.c.

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

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 3565 of file plperl.c.

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

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 3402 of file plperl.c.

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

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

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 4015 of file plperl.c.

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

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

◆ plperl_sv_to_datum()

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

Definition at line 1322 of file plperl.c.

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

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 1443 of file plperl.c.

1444{
1445 Oid typid;
1446 Oid typoutput;
1447 Datum datum;
1448 bool typisvarlena,
1449 isnull;
1450
1452
1453 typid = DirectFunctionCall1(regtypein, CStringGetDatum(fqtypename));
1454 if (!OidIsValid(typid))
1455 ereport(ERROR,
1456 (errcode(ERRCODE_UNDEFINED_OBJECT),
1457 errmsg("lookup failed for type %s", fqtypename)));
1458
1459 datum = plperl_sv_to_datum(sv,
1460 typid, -1,
1461 NULL, NULL, InvalidOid,
1462 &isnull);
1463
1464 if (isnull)
1465 return NULL;
1466
1467 getTypeOutputInfo(typid,
1468 &typoutput, &typisvarlena);
1469
1470 return OidOutputFunctionCall(typoutput, datum);
1471}
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:641
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 1630 of file plperl.c.

1631{
1632 dTHX;
1633 TriggerData *tdata;
1634 TupleDesc tupdesc;
1635 int i;
1636 char *level;
1637 char *event;
1638 char *relid;
1639 char *when;
1640 HV *hv;
1641
1642 hv = newHV();
1643 hv_ksplit(hv, 12); /* pre-grow the hash */
1644
1645 tdata = (TriggerData *) fcinfo->context;
1646 tupdesc = tdata->tg_relation->rd_att;
1647
1650
1651 hv_store_string(hv, "name", cstr2sv(tdata->tg_trigger->tgname));
1652 hv_store_string(hv, "relid", cstr2sv(relid));
1653
1654 /*
1655 * Note: In BEFORE trigger, stored generated columns are not computed yet,
1656 * so don't make them accessible in NEW row.
1657 */
1658
1660 {
1661 event = "INSERT";
1662 if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
1663 hv_store_string(hv, "new",
1665 tupdesc,
1666 !TRIGGER_FIRED_BEFORE(tdata->tg_event)));
1667 }
1668 else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
1669 {
1670 event = "DELETE";
1671 if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
1672 hv_store_string(hv, "old",
1674 tupdesc,
1675 true));
1676 }
1677 else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
1678 {
1679 event = "UPDATE";
1680 if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
1681 {
1682 hv_store_string(hv, "old",
1684 tupdesc,
1685 true));
1686 hv_store_string(hv, "new",
1688 tupdesc,
1689 !TRIGGER_FIRED_BEFORE(tdata->tg_event)));
1690 }
1691 }
1692 else if (TRIGGER_FIRED_BY_TRUNCATE(tdata->tg_event))
1693 event = "TRUNCATE";
1694 else
1695 event = "UNKNOWN";
1696
1697 hv_store_string(hv, "event", cstr2sv(event));
1698 hv_store_string(hv, "argc", newSViv(tdata->tg_trigger->tgnargs));
1699
1700 if (tdata->tg_trigger->tgnargs > 0)
1701 {
1702 AV *av = newAV();
1703
1704 av_extend(av, tdata->tg_trigger->tgnargs);
1705 for (i = 0; i < tdata->tg_trigger->tgnargs; i++)
1706 av_push(av, cstr2sv(tdata->tg_trigger->tgargs[i]));
1707 hv_store_string(hv, "args", newRV_noinc((SV *) av));
1708 }
1709
1710 hv_store_string(hv, "relname",
1712
1713 hv_store_string(hv, "table_name",
1715
1716 hv_store_string(hv, "table_schema",
1718
1719 if (TRIGGER_FIRED_BEFORE(tdata->tg_event))
1720 when = "BEFORE";
1721 else if (TRIGGER_FIRED_AFTER(tdata->tg_event))
1722 when = "AFTER";
1723 else if (TRIGGER_FIRED_INSTEAD(tdata->tg_event))
1724 when = "INSTEAD OF";
1725 else
1726 when = "UNKNOWN";
1727 hv_store_string(hv, "when", cstr2sv(when));
1728
1729 if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
1730 level = "ROW";
1731 else if (TRIGGER_FIRED_FOR_STATEMENT(tdata->tg_event))
1732 level = "STATEMENT";
1733 else
1734 level = "UNKNOWN";
1735 hv_store_string(hv, "level", cstr2sv(level));
1736
1737 return newRV_noinc((SV *) hv);
1738}
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:1332
char * SPI_getrelname(Relation rel)
Definition: spi.c:1326
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 2518 of file plperl.c.

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

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 956 of file plperl.c.

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

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

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 4052 of file plperl.c.

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

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 1987 of file plperl.c.

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

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 2065 of file plperl.c.

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

References plperl_call_handler().

◆ plperlu_inline_handler()

Datum plperlu_inline_handler ( PG_FUNCTION_ARGS  )

Definition at line 2073 of file plperl.c.

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

References plperl_inline_handler().

◆ plperlu_validator()

Datum plperlu_validator ( PG_FUNCTION_ARGS  )

Definition at line 2081 of file plperl.c.

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

References plperl_validator().

◆ pp_require_safe()

static OP * pp_require_safe ( pTHX  )
static

Definition at line 879 of file plperl.c.

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

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

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

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 1558 of file plperl.c.

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

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 1060 of file plperl.c.

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

References len, pstrdup(), and res.

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

◆ SvREFCNT_dec_current()

static void SvREFCNT_dec_current ( SV *  sv)
inlinestatic

Definition at line 311 of file plperl.c.

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

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 2666 of file plperl.c.

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

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

Referenced by compile_plperl_function().

Variable Documentation

◆ current_call_data

◆ PG_MODULE_MAGIC

PG_MODULE_MAGIC

Definition at line 55 of file plperl.c.

◆ plperl_active_interp

◆ plperl_ending

bool plperl_ending = false
static

Definition at line 235 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 227 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 222 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 231 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 232 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 233 of file plperl.c.

Referenced by _PG_init(), and plperl_untrusted_init().

◆ plperl_opmask

char plperl_opmask[MAXO]
static

Definition at line 237 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 223 of file plperl.c.

Referenced by _PG_init(), and compile_plperl_function().

◆ plperl_use_strict

bool plperl_use_strict = false
static

Definition at line 230 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 236 of file plperl.c.

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