plperl.c 62.2 KB
Newer Older
1 2 3
/**********************************************************************
 * plperl.c - perl as a procedural language for PostgreSQL
 *
4
 *	  $PostgreSQL: pgsql/src/pl/plperl/plperl.c,v 1.116 2006/08/13 02:37:11 momjian Exp $
5
 *
6 7
 **********************************************************************/

8
#include "postgres.h"
9
/* Defined by Perl */
10
#undef _
11 12

/* system stuff */
13
#include <ctype.h>
14
#include <fcntl.h>
15
#include <unistd.h>
A
 
Andrew Dunstan 已提交
16
#include <locale.h>
17 18

/* postgreSQL stuff */
19 20
#include "commands/trigger.h"
#include "executor/spi.h"
21
#include "funcapi.h"
22 23 24 25
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "parser/parse_type.h"
26
#include "utils/lsyscache.h"
27
#include "utils/memutils.h"
28
#include "utils/typcache.h"
29

A
 
Andrew Dunstan 已提交
30 31 32
/* define this before the perl headers get a chance to mangle DLLIMPORT */
extern DLLIMPORT bool check_function_bodies;

33
/* perl stuff */
A
 
Andrew Dunstan 已提交
34
#include "plperl.h"
35

36 37
PG_MODULE_MAGIC;

38 39 40 41 42 43
/**********************************************************************
 * The information we cache about loaded procedures
 **********************************************************************/
typedef struct plperl_proc_desc
{
	char	   *proname;
44 45
	TransactionId fn_xmin;
	CommandId	fn_cmin;
46
	bool		fn_readonly;
47
	bool		lanpltrusted;
48
	bool		fn_retistuple;	/* true, if function returns tuple */
B
Bruce Momjian 已提交
49
	bool		fn_retisset;	/* true, if function returns set */
B
Bruce Momjian 已提交
50
	bool		fn_retisarray;	/* true if function returns array */
51
	Oid			result_oid;		/* Oid of result type */
B
Bruce Momjian 已提交
52
	FmgrInfo	result_in_func; /* I/O function and arg for result type */
53
	Oid			result_typioparam;
54
	int			nargs;
55
	int         num_out_args;   /* number of out arguments */
56
	FmgrInfo	arg_out_func[FUNC_MAX_ARGS];
57
	bool		arg_is_rowtype[FUNC_MAX_ARGS];
58
	SV		   *reference;
59
} plperl_proc_desc;
60

61 62 63 64 65 66 67 68 69 70 71 72 73 74
/*
 * The information we cache for the duration of a single call to a
 * function.
 */
typedef struct plperl_call_data
{
	plperl_proc_desc *prodesc;
	FunctionCallInfo  fcinfo;
	Tuplestorestate  *tuple_store;
	TupleDesc		  ret_tdesc;
	AttInMetadata	 *attinmeta;
	MemoryContext	  tmp_cxt;
} plperl_call_data;

A
 
Andrew Dunstan 已提交
75 76 77 78 79 80 81 82 83 84 85 86
/**********************************************************************
 * The information we cache about prepared and saved plans
 **********************************************************************/
typedef struct plperl_query_desc
{
	char		qname[sizeof(long) * 2 + 1];
	void	   *plan;
	int			nargs;
	Oid		   *argtypes;
	FmgrInfo   *arginfuncs;
	Oid		   *argtypioparams;
} plperl_query_desc;
87 88 89 90

/**********************************************************************
 * Global data
 **********************************************************************/
91
static bool plperl_safe_init_done = false;
92
static PerlInterpreter *plperl_interp = NULL;
93
static HV  *plperl_proc_hash = NULL;
A
 
Andrew Dunstan 已提交
94
static HV  *plperl_query_hash = NULL;
95

96 97
static bool plperl_use_strict = false;

98 99
/* this is saved and restored by plperl_call_handler */
static plperl_call_data *current_call_data = NULL;
100

101 102 103
/**********************************************************************
 * Forward declarations
 **********************************************************************/
B
Bruce Momjian 已提交
104
Datum		plperl_call_handler(PG_FUNCTION_ARGS);
105
Datum		plperl_validator(PG_FUNCTION_ARGS);
106 107 108
void		_PG_init(void);

static void plperl_init_interp(void);
109

110
static Datum plperl_func_handler(PG_FUNCTION_ARGS);
111

112
static Datum plperl_trigger_handler(PG_FUNCTION_ARGS);
113 114
static plperl_proc_desc *compile_plperl_function(Oid fn_oid, bool is_trigger);

115
static SV  *plperl_hash_from_tuple(HeapTuple tuple, TupleDesc tupdesc);
116
static void plperl_init_shared_libs(pTHX);
117
static HV  *plperl_spi_execute_fetch_result(SPITupleTable *, int, int);
118

119 120 121
static SV  *plperl_convert_to_pg_array(SV *src);
static SV *plperl_transform_result(plperl_proc_desc *prodesc, SV *result);

122 123 124 125 126 127 128
/*
 * This routine is a crock, and so is everyplace that calls it.  The problem
 * is that the cached form of plperl functions/queries is allocated permanently
 * (mostly via malloc()) and never released until backend exit.  Subsidiary
 * data structures such as fmgr info records therefore must live forever
 * as well.  A better implementation would store all this stuff in a per-
 * function memory context that could be reclaimed at need.  In the meantime,
129 130 131
 * fmgr_info_cxt must be called specifying TopMemoryContext so that whatever
 * it might allocate, and whatever the eventual function might allocate using
 * fn_mcxt, will live forever too.
132 133 134 135
 */
static void
perm_fmgr_info(Oid functionId, FmgrInfo *finfo)
{
136
	fmgr_info_cxt(functionId, finfo, TopMemoryContext);
137 138
}

139

140 141 142 143 144
/*
 * _PG_init()			- library load-time initialization
 *
 * DO NOT make this static nor change its name!
 */
145
void
146
_PG_init(void)
147
{
148 149 150 151
	/* Be sure we do initialization only once (should be redundant now) */
	static bool inited = false;

	if (inited)
152 153
		return;

154
	DefineCustomBoolVariable("plperl.use_strict",
B
Bruce Momjian 已提交
155 156 157 158 159
	  "If true, will compile trusted and untrusted perl code in strict mode",
							 NULL,
							 &plperl_use_strict,
							 PGC_USERSET,
							 NULL, NULL);
160 161

	EmitWarningsOnPlaceholders("plperl");
162

163 164
	plperl_init_interp();

165
	inited = true;
166 167
}

168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
/* Each of these macros must represent a single string literal */

#define PERLBOOT \
	"SPI::bootstrap(); use vars qw(%_SHARED);" \
	"sub ::plperl_warn { my $msg = shift; " \
	"       $msg =~ s/\\(eval \\d+\\) //g; &elog(&NOTICE, $msg); } " \
	"$SIG{__WARN__} = \\&::plperl_warn; " \
	"sub ::plperl_die { my $msg = shift; " \
	"       $msg =~ s/\\(eval \\d+\\) //g; die $msg; } " \
	"$SIG{__DIE__} = \\&::plperl_die; " \
	"sub ::mkunsafefunc {" \
	"      my $ret = eval(qq[ sub { $_[0] $_[1] } ]); " \
	"      $@ =~ s/\\(eval \\d+\\) //g if $@; return $ret; }" \
	"use strict; " \
	"sub ::mk_strict_unsafefunc {" \
	"      my $ret = eval(qq[ sub { use strict; $_[0] $_[1] } ]); " \
	"      $@ =~ s/\\(eval \\d+\\) //g if $@; return $ret; } " \
	"sub ::_plperl_to_pg_array {" \
	"  my $arg = shift; ref $arg eq 'ARRAY' || return $arg; " \
	"  my $res = ''; my $first = 1; " \
	"  foreach my $elem (@$arg) " \
	"  { " \
	"    $res .= ', ' unless $first; $first = undef; " \
	"    if (ref $elem) " \
	"    { " \
	"      $res .= _plperl_to_pg_array($elem); " \
	"    } " \
A
 
Andrew Dunstan 已提交
195
	"    elsif (defined($elem)) " \
196 197 198 199 200
	"    { " \
	"      my $str = qq($elem); " \
	"      $str =~ s/([\"\\\\])/\\\\$1/g; " \
	"      $res .= qq(\"$str\"); " \
	"    } " \
A
 
Andrew Dunstan 已提交
201 202 203 204
	"    else " \
	"    { "\
	"      $res .= 'NULL' ; " \
	"    } "\
205 206 207 208 209 210 211 212 213 214 215 216
	"  } " \
	"  return qq({$res}); " \
	"} "

#define SAFE_MODULE \
	"require Safe; $Safe::VERSION"

#define SAFE_OK \
	"use vars qw($PLContainer); $PLContainer = new Safe('PLPerl');" \
	"$PLContainer->permit_only(':default');" \
	"$PLContainer->permit(qw[:base_math !:base_io sort time]);" \
	"$PLContainer->share(qw[&elog &spi_exec_query &return_next " \
A
 
Andrew Dunstan 已提交
217 218
	"&spi_query &spi_fetchrow &spi_cursor_close " \
	"&spi_prepare &spi_exec_prepared &spi_query_prepared &spi_freeplan " \
219 220 221 222 223 224 225 226 227
	"&_plperl_to_pg_array " \
	"&DEBUG &LOG &INFO &NOTICE &WARNING &ERROR %_SHARED ]);" \
	"sub ::mksafefunc {" \
	"      my $ret = $PLContainer->reval(qq[sub { $_[0] $_[1] }]); " \
	"      $@ =~ s/\\(eval \\d+\\) //g if $@; return $ret; }" \
	"$PLContainer->permit('require'); $PLContainer->reval('use strict;');" \
	"$PLContainer->deny('require');" \
	"sub ::mk_strict_safefunc {" \
	"      my $ret = $PLContainer->reval(qq[sub { BEGIN { strict->import(); } $_[0] $_[1] }]); " \
B
Bruce Momjian 已提交
228
	"      $@ =~ s/\\(eval \\d+\\) //g if $@; return $ret; }"
229 230 231 232 233 234 235 236 237 238 239 240

#define SAFE_BAD \
	"use vars qw($PLContainer); $PLContainer = new Safe('PLPerl');" \
	"$PLContainer->permit_only(':default');" \
	"$PLContainer->share(qw[&elog &ERROR ]);" \
	"sub ::mksafefunc { return $PLContainer->reval(qq[sub { " \
	"      elog(ERROR,'trusted Perl functions disabled - " \
	"      please upgrade Perl Safe module to version 2.09 or later');}]); }" \
	"sub ::mk_strict_safefunc { return $PLContainer->reval(qq[sub { " \
	"      elog(ERROR,'trusted Perl functions disabled - " \
	"      please upgrade Perl Safe module to version 2.09 or later');}]); }"

241 242

static void
243
plperl_init_interp(void)
244
{
B
Bruce Momjian 已提交
245
	static char *embedding[3] = {
246
		"", "-e", PERLBOOT
247 248
	};

A
 
Andrew Dunstan 已提交
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
#ifdef WIN32

	/* 
	 * The perl library on startup does horrible things like call
	 * setlocale(LC_ALL,""). We have protected against that on most
	 * platforms by setting the environment appropriately. However, on
	 * Windows, setlocale() does not consult the environment, so we need
	 * to save the existing locale settings before perl has a chance to 
	 * mangle them and restore them after its dirty deeds are done.
	 *
	 * MSDN ref:
	 * http://msdn.microsoft.com/library/en-us/vclib/html/_crt_locale.asp
	 *
	 * It appears that we only need to do this on interpreter startup, and
	 * subsequent calls to the interpreter don't mess with the locale
	 * settings.
	 *
	 * We restore them using Perl's POSIX::setlocale() function so that
	 * Perl doesn't have a different idea of the locale from Postgres.
	 *
	 */

	char *loc;
	char *save_collate, *save_ctype, *save_monetary, *save_numeric, *save_time;
	char buf[1024];

	loc = setlocale(LC_COLLATE,NULL);
	save_collate = loc ? pstrdup(loc) : NULL;
	loc = setlocale(LC_CTYPE,NULL);
	save_ctype = loc ? pstrdup(loc) : NULL;
	loc = setlocale(LC_MONETARY,NULL);
	save_monetary = loc ? pstrdup(loc) : NULL;
	loc = setlocale(LC_NUMERIC,NULL);
	save_numeric = loc ? pstrdup(loc) : NULL;
	loc = setlocale(LC_TIME,NULL);
	save_time = loc ? pstrdup(loc) : NULL;

#endif

288 289
	plperl_interp = perl_alloc();
	if (!plperl_interp)
290
		elog(ERROR, "could not allocate Perl interpreter");
291

292
	perl_construct(plperl_interp);
293
	perl_parse(plperl_interp, plperl_init_shared_libs, 3, embedding, NULL);
294
	perl_run(plperl_interp);
295

296
	plperl_proc_hash = newHV();
A
 
Andrew Dunstan 已提交
297
	plperl_query_hash = newHV();
A
 
Andrew Dunstan 已提交
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340

#ifdef WIN32

	eval_pv("use POSIX qw(locale_h);", TRUE); /* croak on failure */

	if (save_collate != NULL)
	{
		snprintf(buf, sizeof(buf),"setlocale(%s,'%s');",
				 "LC_COLLATE",save_collate);
		eval_pv(buf,TRUE);
		pfree(save_collate);
	}
	if (save_ctype != NULL)
	{
		snprintf(buf, sizeof(buf),"setlocale(%s,'%s');",
				 "LC_CTYPE",save_ctype);
		eval_pv(buf,TRUE);
		pfree(save_ctype);
	}
	if (save_monetary != NULL)
	{
		snprintf(buf, sizeof(buf),"setlocale(%s,'%s');",
				 "LC_MONETARY",save_monetary);
		eval_pv(buf,TRUE);
		pfree(save_monetary);
	}
	if (save_numeric != NULL)
	{
		snprintf(buf, sizeof(buf),"setlocale(%s,'%s');",
				 "LC_NUMERIC",save_numeric);
		eval_pv(buf,TRUE);
		pfree(save_numeric);
	}
	if (save_time != NULL)
	{
		snprintf(buf, sizeof(buf),"setlocale(%s,'%s');",
				 "LC_TIME",save_time);
		eval_pv(buf,TRUE);
		pfree(save_time);
	}

#endif

341 342
}

343 344 345 346

static void
plperl_safe_init(void)
{
B
Bruce Momjian 已提交
347
	SV		   *res;
348
	double		safe_version;
349

350
	res = eval_pv(SAFE_MODULE, FALSE);	/* TRUE = croak if failure */
351 352 353

	safe_version = SvNV(res);

354 355 356 357 358
	/*
	 * We actually want to reject safe_version < 2.09, but it's risky to
	 * assume that floating-point comparisons are exact, so use a slightly
	 * smaller comparison value.
	 */
B
Bruce Momjian 已提交
359
	if (safe_version < 2.0899)
360 361
	{
		/* not safe, so disallow all trusted funcs */
362
		eval_pv(SAFE_BAD, FALSE);
363 364 365
	}
	else
	{
366
		eval_pv(SAFE_OK, FALSE);
367
	}
368 369 370 371

	plperl_safe_init_done = true;
}

372 373 374 375 376 377
/*
 * Perl likes to put a newline after its error messages; clean up such
 */
static char *
strip_trailing_ws(const char *msg)
{
B
Bruce Momjian 已提交
378 379
	char	   *res = pstrdup(msg);
	int			len = strlen(res);
380

B
Bruce Momjian 已提交
381
	while (len > 0 && isspace((unsigned char) res[len - 1]))
382 383 384 385 386
		res[--len] = '\0';
	return res;
}


387 388
/* Build a tuple from a hash. */

389
static HeapTuple
390
plperl_build_tuple_result(HV *perlhash, AttInMetadata *attinmeta)
391
{
392 393 394 395 396 397
	TupleDesc	td = attinmeta->tupdesc;
	char	  **values;
	SV		   *val;
	char	   *key;
	I32			klen;
	HeapTuple	tup;
398

399
	values = (char **) palloc0(td->natts * sizeof(char *));
400

401 402 403
	hv_iterinit(perlhash);
	while ((val = hv_iternextsv(perlhash, &key, &klen)))
	{
B
Bruce Momjian 已提交
404
		int			attn = SPI_fnumber(td, key);
405

406
		if (attn <= 0 || td->attrs[attn - 1]->attisdropped)
407 408 409 410
			ereport(ERROR,
					(errcode(ERRCODE_UNDEFINED_COLUMN),
					 errmsg("Perl hash contains nonexistent column \"%s\"",
							key)));
411 412 413 414 415 416

		/* if value is ref on array do to pg string array conversion */
		if (SvTYPE(val) == SVt_RV &&
			SvTYPE(SvRV(val)) == SVt_PVAV)
			values[attn - 1] = SvPV(plperl_convert_to_pg_array(val), PL_na);
		else if (SvOK(val) && SvTYPE(val) != SVt_NULL)
417
			values[attn - 1] = SvPV(val, PL_na);
418
	}
419 420 421 422 423
	hv_iterinit(perlhash);

	tup = BuildTupleFromCStrings(attinmeta, values);
	pfree(values);
	return tup;
424 425
}

426 427 428
/*
 * convert perl array to postgres string representation
 */
B
Bruce Momjian 已提交
429
static SV  *
430
plperl_convert_to_pg_array(SV *src)
431
{
B
Bruce Momjian 已提交
432 433 434 435
	SV		   *rv;
	int			count;

	dSP;
436

B
Bruce Momjian 已提交
437
	PUSHMARK(SP);
438
	XPUSHs(src);
B
Bruce Momjian 已提交
439
	PUTBACK;
440

441
	count = call_pv("::_plperl_to_pg_array", G_SCALAR);
442

B
Bruce Momjian 已提交
443
	SPAGAIN;
444 445

	if (count != 1)
446
		elog(ERROR, "unexpected _plperl_to_pg_array failure");
447 448 449

	rv = POPs;

B
Bruce Momjian 已提交
450 451 452
	PUTBACK;

	return rv;
453 454
}

455

456 457
/* Set up the arguments for a trigger call. */

458 459 460 461 462
static SV  *
plperl_trigger_build_args(FunctionCallInfo fcinfo)
{
	TriggerData *tdata;
	TupleDesc	tupdesc;
463
	int			i;
464 465 466 467 468
	char	   *level;
	char	   *event;
	char	   *relid;
	char	   *when;
	HV		   *hv;
469

470
	hv = newHV();
471 472 473 474

	tdata = (TriggerData *) fcinfo->context;
	tupdesc = tdata->tg_relation->rd_att;

475
	relid = DatumGetCString(
B
Bruce Momjian 已提交
476 477 478 479
							DirectFunctionCall1(oidout,
								  ObjectIdGetDatum(tdata->tg_relation->rd_id)
												)
		);
480 481 482

	hv_store(hv, "name", 4, newSVpv(tdata->tg_trigger->tgname, 0), 0);
	hv_store(hv, "relid", 5, newSVpv(relid, 0), 0);
483 484 485

	if (TRIGGER_FIRED_BY_INSERT(tdata->tg_event))
	{
486
		event = "INSERT";
487 488 489 490
		if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
			hv_store(hv, "new", 3,
					 plperl_hash_from_tuple(tdata->tg_trigtuple, tupdesc),
					 0);
491 492 493
	}
	else if (TRIGGER_FIRED_BY_DELETE(tdata->tg_event))
	{
494
		event = "DELETE";
495 496 497 498
		if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
			hv_store(hv, "old", 3,
					 plperl_hash_from_tuple(tdata->tg_trigtuple, tupdesc),
					 0);
499 500 501
	}
	else if (TRIGGER_FIRED_BY_UPDATE(tdata->tg_event))
	{
502
		event = "UPDATE";
503 504 505 506 507 508 509 510 511
		if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
		{
			hv_store(hv, "old", 3,
					 plperl_hash_from_tuple(tdata->tg_trigtuple, tupdesc),
					 0);
			hv_store(hv, "new", 3,
					 plperl_hash_from_tuple(tdata->tg_newtuple, tupdesc),
					 0);
		}
512
	}
513
	else
514
		event = "UNKNOWN";
515

516 517
	hv_store(hv, "event", 5, newSVpv(event, 0), 0);
	hv_store(hv, "argc", 4, newSViv(tdata->tg_trigger->tgnargs), 0);
518

519
	if (tdata->tg_trigger->tgnargs > 0)
520
	{
B
Bruce Momjian 已提交
521 522 523
		AV		   *av = newAV();

		for (i = 0; i < tdata->tg_trigger->tgnargs; i++)
524
			av_push(av, newSVpv(tdata->tg_trigger->tgargs[i], 0));
B
Bruce Momjian 已提交
525
		hv_store(hv, "args", 4, newRV_noinc((SV *) av), 0);
526
	}
527 528 529

	hv_store(hv, "relname", 7,
			 newSVpv(SPI_getrelname(tdata->tg_relation), 0), 0);
530

A
 
Andrew Dunstan 已提交
531 532 533 534 535 536
	hv_store(hv, "table_name", 10,
			 newSVpv(SPI_getrelname(tdata->tg_relation), 0), 0);

	hv_store(hv, "table_schema", 12,
			 newSVpv(SPI_getnspname(tdata->tg_relation), 0), 0);

537
	if (TRIGGER_FIRED_BEFORE(tdata->tg_event))
538
		when = "BEFORE";
539
	else if (TRIGGER_FIRED_AFTER(tdata->tg_event))
540
		when = "AFTER";
541
	else
542 543
		when = "UNKNOWN";
	hv_store(hv, "when", 4, newSVpv(when, 0), 0);
544 545

	if (TRIGGER_FIRED_FOR_ROW(tdata->tg_event))
546
		level = "ROW";
547
	else if (TRIGGER_FIRED_FOR_STATEMENT(tdata->tg_event))
548
		level = "STATEMENT";
549
	else
550 551
		level = "UNKNOWN";
	hv_store(hv, "level", 5, newSVpv(level, 0), 0);
552

B
Bruce Momjian 已提交
553
	return newRV_noinc((SV *) hv);
554 555 556
}


557
/* Set up the new tuple returned from a trigger. */
558

559
static HeapTuple
560
plperl_modify_tuple(HV *hvTD, TriggerData *tdata, HeapTuple otup)
561 562 563 564
{
	SV		  **svp;
	HV		   *hvNew;
	HeapTuple	rtup;
565 566 567 568 569 570 571 572
	SV		   *val;
	char	   *key;
	I32			klen;
	int			slotsused;
	int		   *modattrs;
	Datum	   *modvalues;
	char	   *modnulls;

573 574 575 576 577
	TupleDesc	tupdesc;

	tupdesc = tdata->tg_relation->rd_att;

	svp = hv_fetch(hvTD, "new", 3, FALSE);
578
	if (!svp)
579 580 581
		ereport(ERROR,
				(errcode(ERRCODE_UNDEFINED_COLUMN),
				 errmsg("$_TD->{new} does not exist")));
582
	if (!SvOK(*svp) || SvTYPE(*svp) != SVt_RV || SvTYPE(SvRV(*svp)) != SVt_PVHV)
583 584 585
		ereport(ERROR,
				(errcode(ERRCODE_DATATYPE_MISMATCH),
				 errmsg("$_TD->{new} is not a hash reference")));
586 587
	hvNew = (HV *) SvRV(*svp);

588 589 590 591
	modattrs = palloc(tupdesc->natts * sizeof(int));
	modvalues = palloc(tupdesc->natts * sizeof(Datum));
	modnulls = palloc(tupdesc->natts * sizeof(char));
	slotsused = 0;
592

593 594
	hv_iterinit(hvNew);
	while ((val = hv_iternextsv(hvNew, &key, &klen)))
595
	{
596
		int			attn = SPI_fnumber(tupdesc, key);
597 598 599 600
		Oid			typinput;
		Oid			typioparam;
		int32		atttypmod;
		FmgrInfo	finfo;
601

602
		if (attn <= 0 || tupdesc->attrs[attn - 1]->attisdropped)
603 604 605 606
			ereport(ERROR,
					(errcode(ERRCODE_UNDEFINED_COLUMN),
					 errmsg("Perl hash contains nonexistent column \"%s\"",
							key)));
607 608 609 610 611
		/* XXX would be better to cache these lookups */
		getTypeInputInfo(tupdesc->attrs[attn - 1]->atttypid,
						 &typinput, &typioparam);
		fmgr_info(typinput, &finfo);
		atttypmod = tupdesc->attrs[attn - 1]->atttypmod;
612
		if (SvOK(val) && SvTYPE(val) != SVt_NULL)
613
		{
614 615 616 617
			modvalues[slotsused] = InputFunctionCall(&finfo,
													 SvPV(val, PL_na),
													 typioparam,
													 atttypmod);
618
			modnulls[slotsused] = ' ';
619 620 621
		}
		else
		{
622 623 624 625
			modvalues[slotsused] = InputFunctionCall(&finfo,
													 NULL,
													 typioparam,
													 atttypmod);
626
			modnulls[slotsused] = 'n';
627
		}
628 629
		modattrs[slotsused] = attn;
		slotsused++;
630
	}
631 632 633 634
	hv_iterinit(hvNew);

	rtup = SPI_modifytuple(tdata->tg_relation, otup, slotsused,
						   modattrs, modvalues, modnulls);
635 636 637 638

	pfree(modattrs);
	pfree(modvalues);
	pfree(modnulls);
639

640
	if (rtup == NULL)
641
		elog(ERROR, "SPI_modifytuple failed: %s",
642
			 SPI_result_code_string(SPI_result));
643 644 645

	return rtup;
}
646

647

648 649
/*
 * This is the only externally-visible part of the plperl call interface.
650
 * The Postgres function and trigger managers call it to execute a
651 652
 * perl function.
 */
653
PG_FUNCTION_INFO_V1(plperl_call_handler);
654 655

Datum
656
plperl_call_handler(PG_FUNCTION_ARGS)
657
{
B
Bruce Momjian 已提交
658
	Datum		retval;
659
	plperl_call_data *save_call_data;
660

661
	save_call_data = current_call_data;
662 663 664 665 666 667 668 669 670
	PG_TRY();
	{
		if (CALLED_AS_TRIGGER(fcinfo))
			retval = PointerGetDatum(plperl_trigger_handler(fcinfo));
		else
			retval = plperl_func_handler(fcinfo);
	}
	PG_CATCH();
	{
671
		current_call_data = save_call_data;
672 673 674 675
		PG_RE_THROW();
	}
	PG_END_TRY();

676
	current_call_data = save_call_data;
677 678 679
	return retval;
}

680 681 682 683 684 685 686 687 688 689 690 691
/*
 * This is the other externally visible function - it is called when CREATE
 * FUNCTION is issued to validate the function being created/replaced.
 */
PG_FUNCTION_INFO_V1(plperl_validator);

Datum
plperl_validator(PG_FUNCTION_ARGS)
{
	Oid			funcoid = PG_GETARG_OID(0);
	HeapTuple	tuple;
	Form_pg_proc proc;
692
	char		functyptype;
693 694 695 696 697 698 699 700 701 702
	bool		istrigger = false;

	/* Get the new function's pg_proc entry */
	tuple = SearchSysCache(PROCOID,
						   ObjectIdGetDatum(funcoid),
						   0, 0, 0);
	if (!HeapTupleIsValid(tuple))
		elog(ERROR, "cache lookup failed for function %u", funcoid);
	proc = (Form_pg_proc) GETSTRUCT(tuple);

703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720
	functyptype = get_typtype(proc->prorettype);

	/* Disallow pseudotype result */
	/* except for TRIGGER, RECORD, or VOID */
	if (functyptype == 'p')
	{
		/* we assume OPAQUE with no arguments means a trigger */
		if (proc->prorettype == TRIGGEROID ||
			(proc->prorettype == OPAQUEOID && proc->pronargs == 0))
			istrigger = true;
		else if (proc->prorettype != RECORDOID &&
				 proc->prorettype != VOIDOID)
			ereport(ERROR,
					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
					 errmsg("plperl functions cannot return type %s",
							format_type_be(proc->prorettype))));
	}

721 722
	ReleaseSysCache(tuple);

723 724 725
	/* Postpone body checks if !check_function_bodies */
	if (check_function_bodies)
	{
726
		(void) compile_plperl_function(funcoid, istrigger);
727
	}
728 729 730 731 732

	/* the result of a validator is ignored */
	PG_RETURN_VOID();
}

733

734 735 736
/* Uses mksafefunc/mkunsafefunc to create an anonymous sub whose text is
 * supplied in s, and returns a reference to the closure. */

B
Bruce Momjian 已提交
737
static SV  *
738
plperl_create_sub(char *s, bool trusted)
739
{
740
	dSP;
741
	SV		   *subref;
B
Bruce Momjian 已提交
742
	int			count;
B
Bruce Momjian 已提交
743
	char	   *compile_sub;
744

B
Bruce Momjian 已提交
745
	if (trusted && !plperl_safe_init_done)
746
	{
747
		plperl_safe_init();
748 749
		SPAGAIN;
	}
750

751 752 753
	ENTER;
	SAVETMPS;
	PUSHMARK(SP);
A
 
Andrew Dunstan 已提交
754
	XPUSHs(sv_2mortal(newSVpv("our $_TD; local $_TD=$_[0]; shift;", 0)));
B
Bruce Momjian 已提交
755
	XPUSHs(sv_2mortal(newSVpv(s, 0)));
B
Bruce Momjian 已提交
756
	PUTBACK;
B
Bruce Momjian 已提交
757

758 759
	/*
	 * G_KEEPERR seems to be needed here, else we don't recognize compile
B
Bruce Momjian 已提交
760 761
	 * errors properly.  Perhaps it's because there's another level of eval
	 * inside mksafefunc?
762
	 */
763 764 765 766 767 768 769 770 771 772 773

	if (trusted && plperl_use_strict)
		compile_sub = "::mk_strict_safefunc";
	else if (plperl_use_strict)
		compile_sub = "::mk_strict_unsafefunc";
	else if (trusted)
		compile_sub = "::mksafefunc";
	else
		compile_sub = "::mkunsafefunc";

	count = perl_call_pv(compile_sub, G_SCALAR | G_EVAL | G_KEEPERR);
774 775
	SPAGAIN;

776 777 778 779 780
	if (count != 1)
	{
		PUTBACK;
		FREETMPS;
		LEAVE;
781
		elog(ERROR, "didn't get a return item from mksafefunc");
782 783
	}

784
	if (SvTRUE(ERRSV))
785
	{
786
		(void) POPs;
787 788 789
		PUTBACK;
		FREETMPS;
		LEAVE;
790 791 792 793
		ereport(ERROR,
				(errcode(ERRCODE_SYNTAX_ERROR),
				 errmsg("creation of Perl function failed: %s",
						strip_trailing_ws(SvPV(ERRSV, PL_na)))));
794 795 796
	}

	/*
797 798
	 * need to make a deep copy of the return. it comes off the stack as a
	 * temporary.
799 800 801
	 */
	subref = newSVsv(POPs);

802
	if (!SvROK(subref) || SvTYPE(SvRV(subref)) != SVt_PVCV)
803
	{
804 805 806
		PUTBACK;
		FREETMPS;
		LEAVE;
807

808 809 810 811
		/*
		 * subref is our responsibility because it is not mortal
		 */
		SvREFCNT_dec(subref);
812
		elog(ERROR, "didn't get a code ref");
813 814 815 816 817
	}

	PUTBACK;
	FREETMPS;
	LEAVE;
818

819 820 821
	return subref;
}

822

823
/**********************************************************************
824
 * plperl_init_shared_libs()		-
825 826 827 828
 *
 * We cannot use the DynaLoader directly to get at the Opcode
 * module (used by Safe.pm). So, we link Opcode into ourselves
 * and do the initialization behind perl's back.
829
 *
830 831
 **********************************************************************/

832 833
EXTERN_C void boot_DynaLoader(pTHX_ CV *cv);
EXTERN_C void boot_SPI(pTHX_ CV *cv);
834

835
static void
836
plperl_init_shared_libs(pTHX)
837
{
838 839
	char	   *file = __FILE__;

840
	newXS("DynaLoader::boot_DynaLoader", boot_DynaLoader, file);
841
	newXS("SPI::bootstrap", boot_SPI, file);
842 843
}

844

B
Bruce Momjian 已提交
845
static SV  *
846
plperl_call_perl_func(plperl_proc_desc *desc, FunctionCallInfo fcinfo)
847 848
{
	dSP;
849 850 851
	SV		   *retval;
	int			i;
	int			count;
B
Bruce Momjian 已提交
852
	SV		   *sv;
853 854 855 856

	ENTER;
	SAVETMPS;

857
	PUSHMARK(SP);
858

B
Bruce Momjian 已提交
859
	XPUSHs(&PL_sv_undef);		/* no trigger data */
860

861 862
	for (i = 0; i < desc->nargs; i++)
	{
863 864 865
		if (fcinfo->argnull[i])
			XPUSHs(&PL_sv_undef);
		else if (desc->arg_is_rowtype[i])
866
		{
867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882
			HeapTupleHeader td;
			Oid			tupType;
			int32		tupTypmod;
			TupleDesc	tupdesc;
			HeapTupleData tmptup;
			SV		   *hashref;

			td = DatumGetHeapTupleHeader(fcinfo->arg[i]);
			/* Extract rowtype info and find a tupdesc */
			tupType = HeapTupleHeaderGetTypeId(td);
			tupTypmod = HeapTupleHeaderGetTypMod(td);
			tupdesc = lookup_rowtype_tupdesc(tupType, tupTypmod);
			/* Build a temporary HeapTuple control structure */
			tmptup.t_len = HeapTupleHeaderGetDatumLength(td);
			tmptup.t_data = td;

883 884
			hashref = plperl_hash_from_tuple(&tmptup, tupdesc);
			XPUSHs(sv_2mortal(hashref));
885
			ReleaseTupleDesc(tupdesc);
886 887 888
		}
		else
		{
889 890
			char	   *tmp;

891 892
			tmp = OutputFunctionCall(&(desc->arg_out_func[i]),
									 fcinfo->arg[i]);
893 894
			sv = newSVpv(tmp, 0);
#if PERL_BCDVERSION >= 0x5006000L
B
Bruce Momjian 已提交
895 896
			if (GetDatabaseEncoding() == PG_UTF8)
				SvUTF8_on(sv);
897 898
#endif
			XPUSHs(sv_2mortal(sv));
899
			pfree(tmp);
900 901 902
		}
	}
	PUTBACK;
903 904 905

	/* Do NOT use G_KEEPERR here */
	count = perl_call_sv(desc->reference, G_SCALAR | G_EVAL);
906 907 908

	SPAGAIN;

909 910 911 912
	if (count != 1)
	{
		PUTBACK;
		FREETMPS;
913
		LEAVE;
914
		elog(ERROR, "didn't get a return item from function");
915 916
	}

917
	if (SvTRUE(ERRSV))
918
	{
919
		(void) POPs;
920 921
		PUTBACK;
		FREETMPS;
922
		LEAVE;
923 924 925 926
		/* XXX need to find a way to assign an errcode here */
		ereport(ERROR,
				(errmsg("error from Perl function: %s",
						strip_trailing_ws(SvPV(ERRSV, PL_na)))));
927 928 929 930
	}

	retval = newSVsv(POPs);

931 932 933
	PUTBACK;
	FREETMPS;
	LEAVE;
934 935 936 937

	return retval;
}

938

939
static SV  *
940 941
plperl_call_perl_trigger_func(plperl_proc_desc *desc, FunctionCallInfo fcinfo,
							  SV *td)
942 943 944
{
	dSP;
	SV		   *retval;
945
	Trigger    *tg_trigger;
946 947 948 949 950 951 952
	int			i;
	int			count;

	ENTER;
	SAVETMPS;

	PUSHMARK(sp);
953

954
	XPUSHs(td);
955

956 957 958
	tg_trigger = ((TriggerData *) fcinfo->context)->tg_trigger;
	for (i = 0; i < tg_trigger->tgnargs; i++)
		XPUSHs(sv_2mortal(newSVpv(tg_trigger->tgargs[i], 0)));
959 960
	PUTBACK;

961 962
	/* Do NOT use G_KEEPERR here */
	count = perl_call_sv(desc->reference, G_SCALAR | G_EVAL);
963 964 965 966 967 968 969 970

	SPAGAIN;

	if (count != 1)
	{
		PUTBACK;
		FREETMPS;
		LEAVE;
971
		elog(ERROR, "didn't get a return item from trigger function");
972 973 974 975
	}

	if (SvTRUE(ERRSV))
	{
976
		(void) POPs;
977 978 979
		PUTBACK;
		FREETMPS;
		LEAVE;
980 981 982 983
		/* XXX need to find a way to assign an errcode here */
		ereport(ERROR,
				(errmsg("error from Perl trigger function: %s",
						strip_trailing_ws(SvPV(ERRSV, PL_na)))));
984 985 986 987 988 989 990 991 992 993
	}

	retval = newSVsv(POPs);

	PUTBACK;
	FREETMPS;
	LEAVE;

	return retval;
}
994

995

996
static Datum
997
plperl_func_handler(PG_FUNCTION_ARGS)
998 999
{
	plperl_proc_desc *prodesc;
1000 1001
	SV		   *perlret;
	Datum		retval;
1002
	ReturnSetInfo *rsi;
B
Bruce Momjian 已提交
1003
	SV		   *array_ret = NULL;
1004

1005 1006 1007 1008 1009 1010 1011
	/*
	 * Create the call_data beforing connecting to SPI, so that it is
	 * not allocated in the SPI memory context
	 */
	current_call_data = (plperl_call_data *) palloc0(sizeof(plperl_call_data));
	current_call_data->fcinfo = fcinfo;

1012 1013 1014
	if (SPI_connect() != SPI_OK_CONNECT)
		elog(ERROR, "could not connect to SPI manager");

1015
	prodesc = compile_plperl_function(fcinfo->flinfo->fn_oid, false);
1016
	current_call_data->prodesc = prodesc;
1017

B
Bruce Momjian 已提交
1018
	rsi = (ReturnSetInfo *) fcinfo->resultinfo;
B
Bruce Momjian 已提交
1019

T
Tom Lane 已提交
1020
	if (prodesc->fn_retisset)
1021
	{
T
Tom Lane 已提交
1022 1023 1024 1025 1026 1027 1028 1029
		/* Check context before allowing the call to go through */
		if (!rsi || !IsA(rsi, ReturnSetInfo) ||
			(rsi->allowedModes & SFRM_Materialize) == 0 ||
			rsi->expectedDesc == NULL)
			ereport(ERROR,
					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
					 errmsg("set-valued function called in context that "
							"cannot accept a set")));
1030 1031
	}

1032
	perlret = plperl_call_perl_func(prodesc, fcinfo);
1033 1034 1035 1036 1037 1038 1039 1040

	/************************************************************
	 * Disconnect from SPI manager and then create the return
	 * values datum (if the input function does a palloc for it
	 * this must not be allocated in the SPI memory context
	 * because SPI_finish would free it).
	 ************************************************************/
	if (SPI_finish() != SPI_OK_FINISH)
1041
		elog(ERROR, "SPI_finish() failed");
1042

T
Tom Lane 已提交
1043
	if (prodesc->fn_retisset)
1044
	{
T
Tom Lane 已提交
1045 1046
		/*
		 * If the Perl function returned an arrayref, we pretend that it
B
Bruce Momjian 已提交
1047 1048 1049
		 * called return_next() for each element of the array, to handle old
		 * SRFs that didn't know about return_next(). Any other sort of return
		 * value is an error.
T
Tom Lane 已提交
1050
		 */
1051 1052
		if (SvTYPE(perlret) == SVt_RV &&
			SvTYPE(SvRV(perlret)) == SVt_PVAV)
1053
		{
B
Bruce Momjian 已提交
1054 1055 1056 1057 1058
			int			i = 0;
			SV		  **svp = 0;
			AV		   *rav = (AV *) SvRV(perlret);

			while ((svp = av_fetch(rav, i, FALSE)) != NULL)
1059
			{
1060 1061 1062
				plperl_return_next(*svp);
				i++;
			}
1063
		}
1064
		else if (SvTYPE(perlret) != SVt_NULL)
1065
		{
1066 1067
			ereport(ERROR,
					(errcode(ERRCODE_DATATYPE_MISMATCH),
1068 1069
					 errmsg("set-returning Perl function must return "
							"reference to array or use return_next")));
1070
		}
B
Bruce Momjian 已提交
1071

1072
		rsi->returnMode = SFRM_Materialize;
1073
		if (current_call_data->tuple_store)
1074
		{
1075 1076
			rsi->setResult = current_call_data->tuple_store;
			rsi->setDesc = current_call_data->ret_tdesc;
1077
		}
B
Bruce Momjian 已提交
1078
		retval = (Datum) 0;
1079 1080 1081 1082 1083 1084
	}
	else if (SvTYPE(perlret) == SVt_NULL)
	{
		/* Return NULL if Perl code returned undef */
		if (rsi && IsA(rsi, ReturnSetInfo))
			rsi->isDone = ExprEndResult;
1085 1086
		retval = InputFunctionCall(&prodesc->result_in_func, NULL,
								   prodesc->result_typioparam, -1);
1087
		fcinfo->isnull = true;
B
Bruce Momjian 已提交
1088
	}
1089
	else if (prodesc->fn_retistuple)
1090
	{
1091
		/* Return a perl hash converted to a Datum */
B
Bruce Momjian 已提交
1092
		TupleDesc	td;
1093
		AttInMetadata *attinmeta;
B
Bruce Momjian 已提交
1094
		HeapTuple	tup;
1095

1096 1097 1098
		if (!SvOK(perlret) || SvTYPE(perlret) != SVt_RV ||
			SvTYPE(SvRV(perlret)) != SVt_PVHV)
		{
1099 1100
			ereport(ERROR,
					(errcode(ERRCODE_DATATYPE_MISMATCH),
1101 1102 1103
					 errmsg("composite-returning Perl function "
							"must return reference to hash")));
		}
1104

1105 1106 1107 1108 1109 1110 1111 1112
		/* XXX should cache the attinmeta data instead of recomputing */
		if (get_call_result_type(fcinfo, NULL, &td) != TYPEFUNC_COMPOSITE)
		{
			ereport(ERROR,
					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
					 errmsg("function returning record called in context "
							"that cannot accept type record")));
		}
1113

1114
		attinmeta = TupleDescGetAttInMetadata(td);
B
Bruce Momjian 已提交
1115
		tup = plperl_build_tuple_result((HV *) SvRV(perlret), attinmeta);
1116 1117 1118 1119
		retval = HeapTupleGetDatum(tup);
	}
	else
	{
B
Bruce Momjian 已提交
1120 1121 1122
		/* Return a perl string converted to a Datum */
		char	   *val;

1123 1124
		perlret = plperl_transform_result(prodesc, perlret);

B
Bruce Momjian 已提交
1125
		if (prodesc->fn_retisarray && SvROK(perlret) &&
1126
			SvTYPE(SvRV(perlret)) == SVt_PVAV)
B
Bruce Momjian 已提交
1127 1128 1129 1130 1131
		{
			array_ret = plperl_convert_to_pg_array(perlret);
			SvREFCNT_dec(perlret);
			perlret = array_ret;
		}
1132 1133 1134

		val = SvPV(perlret, PL_na);

1135 1136
		retval = InputFunctionCall(&prodesc->result_in_func, val,
								   prodesc->result_typioparam, -1);
1137
	}
1138

1139
	if (array_ret == NULL)
B
Bruce Momjian 已提交
1140
		SvREFCNT_dec(perlret);
1141

1142
	current_call_data = NULL;
1143 1144 1145
	return retval;
}

1146

1147 1148 1149 1150 1151 1152 1153 1154 1155
static Datum
plperl_trigger_handler(PG_FUNCTION_ARGS)
{
	plperl_proc_desc *prodesc;
	SV		   *perlret;
	Datum		retval;
	SV		   *svTD;
	HV		   *hvTD;

1156 1157 1158 1159 1160 1161 1162
	/*
	 * Create the call_data beforing connecting to SPI, so that it is
	 * not allocated in the SPI memory context
	 */
	current_call_data = (plperl_call_data *) palloc0(sizeof(plperl_call_data));
	current_call_data->fcinfo = fcinfo;

1163 1164 1165 1166
	/* Connect to SPI manager */
	if (SPI_connect() != SPI_OK_CONNECT)
		elog(ERROR, "could not connect to SPI manager");

1167 1168
	/* Find or compile the function */
	prodesc = compile_plperl_function(fcinfo->flinfo->fn_oid, true);
1169
	current_call_data->prodesc = prodesc;
1170

1171 1172
	svTD = plperl_trigger_build_args(fcinfo);
	perlret = plperl_call_perl_trigger_func(prodesc, fcinfo, svTD);
1173
	hvTD = (HV *) SvRV(svTD);
1174 1175 1176 1177 1178 1179 1180 1181

	/************************************************************
	* Disconnect from SPI manager and then create the return
	* values datum (if the input function does a palloc for it
	* this must not be allocated in the SPI memory context
	* because SPI_finish would free it).
	************************************************************/
	if (SPI_finish() != SPI_OK_FINISH)
1182
		elog(ERROR, "SPI_finish() failed");
1183

1184
	if (!(perlret && SvOK(perlret) && SvTYPE(perlret) != SVt_NULL))
1185
	{
1186
		/* undef result means go ahead with original tuple */
1187 1188 1189 1190 1191 1192 1193 1194
		TriggerData *trigdata = ((TriggerData *) fcinfo->context);

		if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
			retval = (Datum) trigdata->tg_trigtuple;
		else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
			retval = (Datum) trigdata->tg_newtuple;
		else if (TRIGGER_FIRED_BY_DELETE(trigdata->tg_event))
			retval = (Datum) trigdata->tg_trigtuple;
1195
		else
B
Bruce Momjian 已提交
1196
			retval = (Datum) 0; /* can this happen? */
1197 1198 1199
	}
	else
	{
1200 1201
		HeapTuple	trv;
		char	   *tmp;
1202

1203
		tmp = SvPV(perlret, PL_na);
1204

1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216
		if (pg_strcasecmp(tmp, "SKIP") == 0)
			trv = NULL;
		else if (pg_strcasecmp(tmp, "MODIFY") == 0)
		{
			TriggerData *trigdata = (TriggerData *) fcinfo->context;

			if (TRIGGER_FIRED_BY_INSERT(trigdata->tg_event))
				trv = plperl_modify_tuple(hvTD, trigdata,
										  trigdata->tg_trigtuple);
			else if (TRIGGER_FIRED_BY_UPDATE(trigdata->tg_event))
				trv = plperl_modify_tuple(hvTD, trigdata,
										  trigdata->tg_newtuple);
1217 1218
			else
			{
1219 1220
				ereport(WARNING,
						(errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
B
Bruce Momjian 已提交
1221
					   errmsg("ignoring modified tuple in DELETE trigger")));
1222 1223 1224
				trv = NULL;
			}
		}
1225
		else
1226
		{
1227 1228
			ereport(ERROR,
					(errcode(ERRCODE_E_R_I_E_TRIGGER_PROTOCOL_VIOLATED),
1229 1230
					 errmsg("result of Perl trigger function must be undef, "
							"\"SKIP\" or \"MODIFY\"")));
1231 1232 1233
			trv = NULL;
		}
		retval = PointerGetDatum(trv);
1234 1235
	}

1236 1237 1238
	SvREFCNT_dec(svTD);
	if (perlret)
		SvREFCNT_dec(perlret);
1239

1240
	current_call_data = NULL;
1241 1242
	return retval;
}
1243

1244

1245 1246
static plperl_proc_desc *
compile_plperl_function(Oid fn_oid, bool is_trigger)
1247
{
1248 1249 1250 1251 1252
	HeapTuple	procTup;
	Form_pg_proc procStruct;
	char		internal_proname[64];
	int			proname_len;
	plperl_proc_desc *prodesc = NULL;
B
Bruce Momjian 已提交
1253
	SV		  **svp;
1254

1255 1256 1257 1258 1259
	/* We'll need the pg_proc tuple in any case... */
	procTup = SearchSysCache(PROCOID,
							 ObjectIdGetDatum(fn_oid),
							 0, 0, 0);
	if (!HeapTupleIsValid(procTup))
1260
		elog(ERROR, "cache lookup failed for function %u", fn_oid);
1261
	procStruct = (Form_pg_proc) GETSTRUCT(procTup);
1262 1263

	/************************************************************
1264
	 * Build our internal proc name from the function's Oid
1265
	 ************************************************************/
1266 1267 1268 1269
	if (!is_trigger)
		sprintf(internal_proname, "__PLPerl_proc_%u", fn_oid);
	else
		sprintf(internal_proname, "__PLPerl_proc_%u_trigger", fn_oid);
1270

1271
	proname_len = strlen(internal_proname);
1272 1273 1274 1275

	/************************************************************
	 * Lookup the internal proc name in the hashtable
	 ************************************************************/
1276 1277
	svp = hv_fetch(plperl_proc_hash, internal_proname, proname_len, FALSE);
	if (svp)
1278
	{
1279 1280
		bool		uptodate;

A
 
Andrew Dunstan 已提交
1281
		prodesc = INT2PTR( plperl_proc_desc *, SvUV(*svp));
1282

1283
		/************************************************************
1284 1285 1286
		 * If it's present, must check whether it's still up to date.
		 * This is needed because CREATE OR REPLACE FUNCTION can modify the
		 * function's pg_proc entry without changing its OID.
1287
		 ************************************************************/
1288
		uptodate = (prodesc->fn_xmin == HeapTupleHeaderGetXmin(procTup->t_data) &&
B
Bruce Momjian 已提交
1289
				prodesc->fn_cmin == HeapTupleHeaderGetCmin(procTup->t_data));
1290 1291 1292 1293 1294 1295 1296 1297 1298 1299

		if (!uptodate)
		{
			/* need we delete old entry? */
			prodesc = NULL;
		}
	}

	/************************************************************
	 * If we haven't found it in the hashtable, we analyze
1300
	 * the function's arguments and return type and store
1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311
	 * the in-/out-functions in the prodesc block and create
	 * a new hashtable entry for it.
	 *
	 * Then we load the procedure into the Perl interpreter.
	 ************************************************************/
	if (prodesc == NULL)
	{
		HeapTuple	langTup;
		HeapTuple	typeTup;
		Form_pg_language langStruct;
		Form_pg_type typeStruct;
1312 1313
		Datum		prosrcdatum;
		bool		isnull;
1314
		char	   *proc_source;
1315 1316 1317 1318 1319 1320
		int			i;
		int			numargs;
		Oid		   *argtypes;
		char	  **argnames;
		char	   *argmodes;

1321 1322 1323 1324 1325

		/************************************************************
		 * Allocate a new procedure description block
		 ************************************************************/
		prodesc = (plperl_proc_desc *) malloc(sizeof(plperl_proc_desc));
1326
		if (prodesc == NULL)
1327 1328 1329
			ereport(ERROR,
					(errcode(ERRCODE_OUT_OF_MEMORY),
					 errmsg("out of memory")));
1330 1331
		MemSet(prodesc, 0, sizeof(plperl_proc_desc));
		prodesc->proname = strdup(internal_proname);
1332 1333
		prodesc->fn_xmin = HeapTupleHeaderGetXmin(procTup->t_data);
		prodesc->fn_cmin = HeapTupleHeaderGetCmin(procTup->t_data);
1334

1335 1336 1337 1338
		/* Remember if function is STABLE/IMMUTABLE */
		prodesc->fn_readonly =
			(procStruct->provolatile != PROVOLATILE_VOLATILE);

1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357

		/* Disallow pseudotypes in arguments (either IN or OUT) */
		/* Count number of out arguments */
		numargs = get_func_arg_info(procTup,
									&argtypes, &argnames, &argmodes);
		for (i = 0; i < numargs; i++)
		{
			if (get_typtype(argtypes[i]) == 'p')
				ereport(ERROR,
						(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
						 errmsg("plperl functions cannot take type %s",
								format_type_be(argtypes[i]))));

		    if (argmodes && argmodes[i] == PROARGMODE_OUT)
				prodesc->num_out_args++;

		}


1358
		/************************************************************
1359
		 * Lookup the pg_language tuple by Oid
1360
		 ************************************************************/
1361 1362
		langTup = SearchSysCache(LANGOID,
								 ObjectIdGetDatum(procStruct->prolang),
1363
								 0, 0, 0);
1364
		if (!HeapTupleIsValid(langTup))
1365 1366 1367
		{
			free(prodesc->proname);
			free(prodesc);
1368
			elog(ERROR, "cache lookup failed for language %u",
1369
				 procStruct->prolang);
1370
		}
1371 1372 1373
		langStruct = (Form_pg_language) GETSTRUCT(langTup);
		prodesc->lanpltrusted = langStruct->lanpltrusted;
		ReleaseSysCache(langTup);
1374 1375

		/************************************************************
1376 1377
		 * Get the required information for input conversion of the
		 * return value.
1378
		 ************************************************************/
1379 1380 1381
		if (!is_trigger)
		{
			typeTup = SearchSysCache(TYPEOID,
B
Bruce Momjian 已提交
1382
									 ObjectIdGetDatum(procStruct->prorettype),
1383 1384 1385 1386 1387
									 0, 0, 0);
			if (!HeapTupleIsValid(typeTup))
			{
				free(prodesc->proname);
				free(prodesc);
1388
				elog(ERROR, "cache lookup failed for type %u",
1389
					 procStruct->prorettype);
1390 1391 1392
			}
			typeStruct = (Form_pg_type) GETSTRUCT(typeTup);

1393
			/* Disallow pseudotype result, except VOID or RECORD */
1394 1395
			if (typeStruct->typtype == 'p')
			{
1396 1397
				if (procStruct->prorettype == VOIDOID ||
					procStruct->prorettype == RECORDOID)
B
Bruce Momjian 已提交
1398
					 /* okay */ ;
1399
				else if (procStruct->prorettype == TRIGGEROID)
1400 1401 1402
				{
					free(prodesc->proname);
					free(prodesc);
1403 1404
					ereport(ERROR,
							(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1405 1406
							 errmsg("trigger functions may only be called "
									"as triggers")));
1407 1408 1409 1410 1411
				}
				else
				{
					free(prodesc->proname);
					free(prodesc);
1412 1413
					ereport(ERROR,
							(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
B
Bruce Momjian 已提交
1414 1415
							 errmsg("plperl functions cannot return type %s",
									format_type_be(procStruct->prorettype))));
1416 1417 1418
				}
			}

1419 1420 1421 1422
			prodesc->result_oid = procStruct->prorettype;
			prodesc->fn_retisset = procStruct->proretset;
			prodesc->fn_retistuple = (typeStruct->typtype == 'c' ||
									  procStruct->prorettype == RECORDOID);
1423

B
Bruce Momjian 已提交
1424 1425
			prodesc->fn_retisarray =
				(typeStruct->typlen == -1 && typeStruct->typelem);
1426

1427
			perm_fmgr_info(typeStruct->typinput, &(prodesc->result_in_func));
1428
			prodesc->result_typioparam = getTypeIOParam(typeTup);
1429 1430 1431

			ReleaseSysCache(typeTup);
		}
1432 1433

		/************************************************************
1434 1435
		 * Get the required information for output conversion
		 * of all procedure arguments
1436
		 ************************************************************/
1437 1438 1439 1440 1441 1442
		if (!is_trigger)
		{
			prodesc->nargs = procStruct->pronargs;
			for (i = 0; i < prodesc->nargs; i++)
			{
				typeTup = SearchSysCache(TYPEOID,
B
Bruce Momjian 已提交
1443
						 ObjectIdGetDatum(procStruct->proargtypes.values[i]),
1444 1445 1446 1447 1448
										 0, 0, 0);
				if (!HeapTupleIsValid(typeTup))
				{
					free(prodesc->proname);
					free(prodesc);
1449
					elog(ERROR, "cache lookup failed for type %u",
1450
						 procStruct->proargtypes.values[i]);
1451 1452 1453
				}
				typeStruct = (Form_pg_type) GETSTRUCT(typeTup);

1454 1455 1456 1457 1458
				/* Disallow pseudotype argument */
				if (typeStruct->typtype == 'p')
				{
					free(prodesc->proname);
					free(prodesc);
1459 1460
					ereport(ERROR,
							(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
B
Bruce Momjian 已提交
1461 1462
							 errmsg("plperl functions cannot take type %s",
						format_type_be(procStruct->proargtypes.values[i]))));
1463 1464
				}

1465 1466
				if (typeStruct->typtype == 'c')
					prodesc->arg_is_rowtype[i] = true;
1467
				else
1468 1469 1470 1471 1472
				{
					prodesc->arg_is_rowtype[i] = false;
					perm_fmgr_info(typeStruct->typoutput,
								   &(prodesc->arg_out_func[i]));
				}
1473 1474 1475 1476

				ReleaseSysCache(typeTup);
			}
		}
1477

1478 1479 1480 1481 1482
		/************************************************************
		 * create the text of the anonymous subroutine.
		 * we do not use a named subroutine so that we can call directly
		 * through the reference.
		 ************************************************************/
1483 1484 1485 1486
		prosrcdatum = SysCacheGetAttr(PROCOID, procTup,
									  Anum_pg_proc_prosrc, &isnull);
		if (isnull)
			elog(ERROR, "null prosrc");
1487
		proc_source = DatumGetCString(DirectFunctionCall1(textout,
1488
														  prosrcdatum));
1489 1490

		/************************************************************
1491
		 * Create the procedure in the interpreter
1492
		 ************************************************************/
1493 1494
		prodesc->reference = plperl_create_sub(proc_source, prodesc->lanpltrusted);
		pfree(proc_source);
B
Bruce Momjian 已提交
1495
		if (!prodesc->reference)	/* can this happen? */
1496 1497 1498
		{
			free(prodesc->proname);
			free(prodesc);
1499
			elog(ERROR, "could not create internal procedure \"%s\"",
1500
				 internal_proname);
1501 1502
		}

1503
		hv_store(plperl_proc_hash, internal_proname, proname_len,
A
 
Andrew Dunstan 已提交
1504
				 newSVuv( PTR2UV( prodesc)), 0);
1505 1506
	}

1507
	ReleaseSysCache(procTup);
1508

1509 1510
	return prodesc;
}
1511 1512


1513 1514
/* Build a hash from all attributes of a given tuple. */

B
Bruce Momjian 已提交
1515
static SV  *
1516
plperl_hash_from_tuple(HeapTuple tuple, TupleDesc tupdesc)
1517
{
1518
	HV		   *hv;
1519
	int			i;
1520

1521
	hv = newHV();
1522 1523 1524

	for (i = 0; i < tupdesc->natts; i++)
	{
1525 1526 1527 1528 1529 1530 1531
		Datum		attr;
		bool		isnull;
		char	   *attname;
		char	   *outputstr;
		Oid			typoutput;
		bool		typisvarlena;
		int			namelen;
B
Bruce Momjian 已提交
1532
		SV		   *sv;
1533

1534 1535 1536
		if (tupdesc->attrs[i]->attisdropped)
			continue;

1537
		attname = NameStr(tupdesc->attrs[i]->attname);
1538
		namelen = strlen(attname);
1539 1540
		attr = heap_getattr(tuple, i + 1, tupdesc, &isnull);

B
Bruce Momjian 已提交
1541 1542
		if (isnull)
		{
1543 1544
			/* Store (attname => undef) and move on. */
			hv_store(hv, attname, namelen, newSV(0), 0);
1545 1546 1547
			continue;
		}

1548
		/* XXX should have a way to cache these lookups */
1549

1550
		getTypeOutputInfo(tupdesc->attrs[i]->atttypid,
1551
						  &typoutput, &typisvarlena);
1552

1553
		outputstr = OidOutputFunctionCall(typoutput, attr);
1554

1555 1556
		sv = newSVpv(outputstr, 0);
#if PERL_BCDVERSION >= 0x5006000L
1557 1558
		if (GetDatabaseEncoding() == PG_UTF8)
			SvUTF8_on(sv);
1559 1560
#endif
		hv_store(hv, attname, namelen, sv, 0);
1561 1562

		pfree(outputstr);
1563
	}
1564

1565
	return newRV_noinc((SV *) hv);
1566
}
1567 1568 1569 1570 1571 1572 1573


HV *
plperl_spi_exec(char *query, int limit)
{
	HV		   *ret_hv;

1574
	/*
B
Bruce Momjian 已提交
1575 1576
	 * Execute the query inside a sub-transaction, so we can cope with errors
	 * sanely
1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588
	 */
	MemoryContext oldcontext = CurrentMemoryContext;
	ResourceOwner oldowner = CurrentResourceOwner;

	BeginInternalSubTransaction(NULL);
	/* Want to run inside function's memory context */
	MemoryContextSwitchTo(oldcontext);

	PG_TRY();
	{
		int			spi_rv;

1589
		spi_rv = SPI_execute(query, current_call_data->prodesc->fn_readonly,
1590 1591 1592 1593 1594 1595 1596 1597
							 limit);
		ret_hv = plperl_spi_execute_fetch_result(SPI_tuptable, SPI_processed,
												 spi_rv);

		/* Commit the inner transaction, return to outer xact context */
		ReleaseCurrentSubTransaction();
		MemoryContextSwitchTo(oldcontext);
		CurrentResourceOwner = oldowner;
B
Bruce Momjian 已提交
1598

1599
		/*
B
Bruce Momjian 已提交
1600 1601
		 * AtEOSubXact_SPI() should not have popped any SPI context, but just
		 * in case it did, make sure we remain connected.
1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619
		 */
		SPI_restore_connection();
	}
	PG_CATCH();
	{
		ErrorData  *edata;

		/* Save error info */
		MemoryContextSwitchTo(oldcontext);
		edata = CopyErrorData();
		FlushErrorState();

		/* Abort the inner transaction */
		RollbackAndReleaseCurrentSubTransaction();
		MemoryContextSwitchTo(oldcontext);
		CurrentResourceOwner = oldowner;

		/*
B
Bruce Momjian 已提交
1620 1621 1622
		 * If AtEOSubXact_SPI() popped any SPI context of the subxact, it will
		 * have left us in a disconnected state.  We need this hack to return
		 * to connected state.
1623 1624 1625 1626 1627 1628 1629 1630 1631 1632
		 */
		SPI_restore_connection();

		/* Punt the error to Perl */
		croak("%s", edata->message);

		/* Can't get here, but keep compiler quiet */
		return NULL;
	}
	PG_END_TRY();
1633 1634 1635 1636

	return ret_hv;
}

1637

1638
static HV  *
1639 1640
plperl_spi_execute_fetch_result(SPITupleTable *tuptable, int processed,
								int status)
1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652
{
	HV		   *result;

	result = newHV();

	hv_store(result, "status", strlen("status"),
			 newSVpv((char *) SPI_result_code_string(status), 0), 0);
	hv_store(result, "processed", strlen("processed"),
			 newSViv(processed), 0);

	if (status == SPI_OK_SELECT)
	{
1653
		AV		   *rows;
1654
		SV		   *row;
1655
		int			i;
1656

1657 1658 1659 1660
		rows = newAV();
		for (i = 0; i < processed; i++)
		{
			row = plperl_hash_from_tuple(tuptable->vals[i], tuptable->tupdesc);
1661
			av_push(rows, row);
1662
		}
1663 1664
		hv_store(result, "rows", strlen("rows"),
				 newRV_noinc((SV *) rows), 0);
1665 1666 1667 1668 1669 1670
	}

	SPI_freetuptable(tuptable);

	return result;
}
1671 1672


1673 1674
/*
 * Note: plperl_return_next is called both in Postgres and Perl contexts.
1675
 * We report any errors in Postgres fashion (via ereport).	If called in
1676 1677 1678 1679 1680
 * Perl context, it is SPI.xs's responsibility to catch the error and
 * convert to a Perl error.  We assume (perhaps without adequate justification)
 * that we need not abort the current transaction if the Perl code traps the
 * error.
 */
1681
void
1682
plperl_return_next(SV *sv)
1683
{
1684 1685 1686 1687
	plperl_proc_desc *prodesc;
	FunctionCallInfo fcinfo;
	ReturnSetInfo *rsi;
	MemoryContext old_cxt;
B
Bruce Momjian 已提交
1688
	HeapTuple	tuple;
1689 1690 1691 1692

	if (!sv)
		return;

1693 1694 1695 1696
	prodesc = current_call_data->prodesc;
	fcinfo = current_call_data->fcinfo;
	rsi = (ReturnSetInfo *) fcinfo->resultinfo;

1697 1698
	sv = plperl_transform_result(prodesc, sv);

1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710
	if (!prodesc->fn_retisset)
		ereport(ERROR,
				(errcode(ERRCODE_SYNTAX_ERROR),
				 errmsg("cannot use return_next in a non-SETOF function")));

	if (prodesc->fn_retistuple &&
		!(SvOK(sv) && SvTYPE(sv) == SVt_RV && SvTYPE(SvRV(sv)) == SVt_PVHV))
		ereport(ERROR,
				(errcode(ERRCODE_DATATYPE_MISMATCH),
				 errmsg("setof-composite-returning Perl function "
						"must call return_next with reference to hash")));

1711 1712 1713 1714 1715 1716
	if (!current_call_data->ret_tdesc)
	{
		TupleDesc tupdesc;

		Assert(!current_call_data->tuple_store);
		Assert(!current_call_data->attinmeta);
1717

1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734
		/*
		 * This is the first call to return_next in the current
		 * PL/Perl function call, so memoize some lookups
		 */
		if (prodesc->fn_retistuple)
			(void) get_call_result_type(fcinfo, NULL, &tupdesc);
		else
			tupdesc = rsi->expectedDesc;

		/*
		 * Make sure the tuple_store and ret_tdesc are sufficiently
		 * long-lived.
		 */
		old_cxt = MemoryContextSwitchTo(rsi->econtext->ecxt_per_query_memory);

		current_call_data->ret_tdesc = CreateTupleDescCopy(tupdesc);
		current_call_data->tuple_store =
1735
			tuplestore_begin_heap(true, false, work_mem);
1736 1737 1738 1739 1740
		if (prodesc->fn_retistuple)
		{
			current_call_data->attinmeta =
				TupleDescGetAttInMetadata(current_call_data->ret_tdesc);
		}
1741

1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752
		MemoryContextSwitchTo(old_cxt);
	}		

	/*
	 * Producing the tuple we want to return requires making plenty of
	 * palloc() allocations that are not cleaned up. Since this
	 * function can be called many times before the current memory
	 * context is reset, we need to do those allocations in a
	 * temporary context.
	 */
	if (!current_call_data->tmp_cxt)
1753
	{
1754 1755 1756 1757 1758 1759 1760 1761 1762
		current_call_data->tmp_cxt =
			AllocSetContextCreate(rsi->econtext->ecxt_per_tuple_memory,
								  "PL/Perl return_next temporary cxt",
								  ALLOCSET_DEFAULT_MINSIZE,
								  ALLOCSET_DEFAULT_INITSIZE,
								  ALLOCSET_DEFAULT_MAXSIZE);
	}

	old_cxt = MemoryContextSwitchTo(current_call_data->tmp_cxt);
1763

1764 1765 1766 1767
	if (prodesc->fn_retistuple)
	{
		tuple = plperl_build_tuple_result((HV *) SvRV(sv),
										  current_call_data->attinmeta);
1768 1769 1770
	}
	else
	{
1771 1772
		Datum		ret;
		bool		isNull;
1773 1774 1775

		if (SvOK(sv) && SvTYPE(sv) != SVt_NULL)
		{
1776 1777 1778 1779 1780 1781 1782 1783 1784 1785
			char	   *val;
			SV         *array_ret;

			if (SvROK(sv) && SvTYPE(SvRV(sv)) == SVt_PVAV )
			{
				array_ret = plperl_convert_to_pg_array(sv);
				sv = array_ret;
			}

			val = SvPV(sv, PL_na);
B
Bruce Momjian 已提交
1786

1787 1788
			ret = InputFunctionCall(&prodesc->result_in_func, val,
									prodesc->result_typioparam, -1);
1789 1790
			isNull = false;
		}
1791 1792 1793 1794 1795 1796
		else
		{
			ret = InputFunctionCall(&prodesc->result_in_func, NULL,
									prodesc->result_typioparam, -1);
			isNull = true;
		}
1797

1798
		tuple = heap_form_tuple(current_call_data->ret_tdesc, &ret, &isNull);
1799 1800
	}

1801 1802 1803 1804
	/* Make sure to store the tuple in a long-lived memory context */
	MemoryContextSwitchTo(rsi->econtext->ecxt_per_query_memory);
	tuplestore_puttuple(current_call_data->tuple_store, tuple);
	MemoryContextSwitchTo(old_cxt);
1805

1806
	MemoryContextReset(current_call_data->tmp_cxt);
1807
}
1808 1809 1810 1811 1812


SV *
plperl_spi_query(char *query)
{
B
Bruce Momjian 已提交
1813
	SV		   *cursor;
1814

1815 1816 1817 1818
	/*
	 * Execute the query inside a sub-transaction, so we can cope with errors
	 * sanely
	 */
1819 1820 1821 1822
	MemoryContext oldcontext = CurrentMemoryContext;
	ResourceOwner oldowner = CurrentResourceOwner;

	BeginInternalSubTransaction(NULL);
1823
	/* Want to run inside function's memory context */
1824 1825 1826 1827
	MemoryContextSwitchTo(oldcontext);

	PG_TRY();
	{
B
Bruce Momjian 已提交
1828
		void	   *plan;
A
 
Andrew Dunstan 已提交
1829
		Portal		portal;
1830

1831
		/* Create a cursor for the query */
1832
		plan = SPI_prepare(query, 0, NULL);
A
 
Andrew Dunstan 已提交
1833 1834 1835 1836 1837 1838 1839 1840 1841 1842
		if ( plan == NULL)
			elog(ERROR, "SPI_prepare() failed:%s",
				SPI_result_code_string(SPI_result));

		portal = SPI_cursor_open(NULL, plan, NULL, NULL, false);
		SPI_freeplan( plan);
		if ( portal == NULL) 
			elog(ERROR, "SPI_cursor_open() failed:%s",
				SPI_result_code_string(SPI_result));
		cursor = newSVpv(portal->name, 0);
1843

1844
		/* Commit the inner transaction, return to outer xact context */
1845 1846 1847
		ReleaseCurrentSubTransaction();
		MemoryContextSwitchTo(oldcontext);
		CurrentResourceOwner = oldowner;
1848 1849 1850 1851 1852

		/*
		 * AtEOSubXact_SPI() should not have popped any SPI context, but just
		 * in case it did, make sure we remain connected.
		 */
1853 1854 1855 1856 1857 1858
		SPI_restore_connection();
	}
	PG_CATCH();
	{
		ErrorData  *edata;

1859
		/* Save error info */
1860 1861 1862 1863
		MemoryContextSwitchTo(oldcontext);
		edata = CopyErrorData();
		FlushErrorState();

1864
		/* Abort the inner transaction */
1865 1866 1867 1868
		RollbackAndReleaseCurrentSubTransaction();
		MemoryContextSwitchTo(oldcontext);
		CurrentResourceOwner = oldowner;

1869 1870 1871 1872 1873
		/*
		 * If AtEOSubXact_SPI() popped any SPI context of the subxact, it will
		 * have left us in a disconnected state.  We need this hack to return
		 * to connected state.
		 */
1874
		SPI_restore_connection();
1875 1876

		/* Punt the error to Perl */
1877
		croak("%s", edata->message);
1878 1879

		/* Can't get here, but keep compiler quiet */
1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890
		return NULL;
	}
	PG_END_TRY();

	return cursor;
}


SV *
plperl_spi_fetchrow(char *cursor)
{
1891 1892 1893 1894 1895 1896 1897 1898
	SV		   *row;

	/*
	 * Execute the FETCH inside a sub-transaction, so we can cope with errors
	 * sanely
	 */
	MemoryContext oldcontext = CurrentMemoryContext;
	ResourceOwner oldowner = CurrentResourceOwner;
1899

1900 1901 1902
	BeginInternalSubTransaction(NULL);
	/* Want to run inside function's memory context */
	MemoryContextSwitchTo(oldcontext);
1903

1904
	PG_TRY();
B
Bruce Momjian 已提交
1905
	{
1906 1907 1908
		Portal		p = SPI_cursor_find(cursor);

		if (!p)
A
 
Andrew Dunstan 已提交
1909 1910 1911
		{
			row = &PL_sv_undef;
		}
1912 1913 1914 1915 1916 1917
		else
		{
			SPI_cursor_fetch(p, true, 1);
			if (SPI_processed == 0)
			{
				SPI_cursor_close(p);
A
 
Andrew Dunstan 已提交
1918
				row = &PL_sv_undef;
1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937
			}
			else
			{
				row = plperl_hash_from_tuple(SPI_tuptable->vals[0],
											 SPI_tuptable->tupdesc);
			}
			SPI_freetuptable(SPI_tuptable);
		}

		/* Commit the inner transaction, return to outer xact context */
		ReleaseCurrentSubTransaction();
		MemoryContextSwitchTo(oldcontext);
		CurrentResourceOwner = oldowner;

		/*
		 * AtEOSubXact_SPI() should not have popped any SPI context, but just
		 * in case it did, make sure we remain connected.
		 */
		SPI_restore_connection();
1938
	}
1939 1940 1941
	PG_CATCH();
	{
		ErrorData  *edata;
1942

1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966
		/* Save error info */
		MemoryContextSwitchTo(oldcontext);
		edata = CopyErrorData();
		FlushErrorState();

		/* Abort the inner transaction */
		RollbackAndReleaseCurrentSubTransaction();
		MemoryContextSwitchTo(oldcontext);
		CurrentResourceOwner = oldowner;

		/*
		 * If AtEOSubXact_SPI() popped any SPI context of the subxact, it will
		 * have left us in a disconnected state.  We need this hack to return
		 * to connected state.
		 */
		SPI_restore_connection();

		/* Punt the error to Perl */
		croak("%s", edata->message);

		/* Can't get here, but keep compiler quiet */
		return NULL;
	}
	PG_END_TRY();
1967 1968 1969

	return row;
}
A
 
Andrew Dunstan 已提交
1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010

void
plperl_spi_cursor_close(char *cursor)
{
	Portal p = SPI_cursor_find(cursor);
	if (p)
		SPI_cursor_close(p);
}

SV *
plperl_spi_prepare(char* query, int argc, SV ** argv)
{
	plperl_query_desc *qdesc;
	void	   *plan;
	int			i;

	MemoryContext oldcontext = CurrentMemoryContext;
	ResourceOwner oldowner = CurrentResourceOwner;

	BeginInternalSubTransaction(NULL);
	MemoryContextSwitchTo(oldcontext);

	/************************************************************
	 * Allocate the new querydesc structure
	 ************************************************************/
	qdesc = (plperl_query_desc *) malloc(sizeof(plperl_query_desc));
	MemSet(qdesc, 0, sizeof(plperl_query_desc));
	snprintf(qdesc-> qname, sizeof(qdesc-> qname), "%lx", (long) qdesc);
	qdesc-> nargs = argc;
	qdesc-> argtypes = (Oid *) malloc(argc * sizeof(Oid));
	qdesc-> arginfuncs = (FmgrInfo *) malloc(argc * sizeof(FmgrInfo));
	qdesc-> argtypioparams = (Oid *) malloc(argc * sizeof(Oid));

	PG_TRY();
	{
		/************************************************************
		 * Lookup the argument types by name in the system cache
		 * and remember the required information for input conversion
		 ************************************************************/
		for (i = 0; i < argc; i++)
		{
2011 2012 2013 2014 2015 2016 2017
			List	   *names;
			HeapTuple	typeTup;

			/* Parse possibly-qualified type name and look it up in pg_type */
			names = stringToQualifiedNameList(SvPV(argv[i], PL_na),
											  "plperl_spi_prepare");
			typeTup = typenameType(NULL, makeTypeNameFromNameList(names));
A
 
Andrew Dunstan 已提交
2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151
			qdesc->argtypes[i] = HeapTupleGetOid(typeTup);
			perm_fmgr_info(((Form_pg_type) GETSTRUCT(typeTup))->typinput,
						   &(qdesc->arginfuncs[i]));
			qdesc->argtypioparams[i] = getTypeIOParam(typeTup);
			ReleaseSysCache(typeTup);
		}

		/************************************************************
		 * Prepare the plan and check for errors
		 ************************************************************/
		plan = SPI_prepare(query, argc, qdesc->argtypes);

		if (plan == NULL)
			elog(ERROR, "SPI_prepare() failed:%s",
				SPI_result_code_string(SPI_result));

		/************************************************************
		 * Save the plan into permanent memory (right now it's in the
		 * SPI procCxt, which will go away at function end).
		 ************************************************************/
		qdesc->plan = SPI_saveplan(plan);
		if (qdesc->plan == NULL)
			elog(ERROR, "SPI_saveplan() failed: %s", 
				SPI_result_code_string(SPI_result));

		/* Release the procCxt copy to avoid within-function memory leak */
		SPI_freeplan(plan);

		/* Commit the inner transaction, return to outer xact context */
		ReleaseCurrentSubTransaction();
		MemoryContextSwitchTo(oldcontext);
		CurrentResourceOwner = oldowner;
		/*
		 * AtEOSubXact_SPI() should not have popped any SPI context,
		 * but just in case it did, make sure we remain connected.
		 */
		SPI_restore_connection();
	}
	PG_CATCH();
	{
		ErrorData  *edata;
		
		free(qdesc-> argtypes);
		free(qdesc-> arginfuncs);
		free(qdesc-> argtypioparams);
		free(qdesc);

		/* Save error info */
		MemoryContextSwitchTo(oldcontext);
		edata = CopyErrorData();
		FlushErrorState();

		/* Abort the inner transaction */
		RollbackAndReleaseCurrentSubTransaction();
		MemoryContextSwitchTo(oldcontext);
		CurrentResourceOwner = oldowner;

		/*
		 * If AtEOSubXact_SPI() popped any SPI context of the subxact,
		 * it will have left us in a disconnected state.  We need this
		 * hack to return to connected state.
		 */
		SPI_restore_connection();

		/* Punt the error to Perl */
		croak("%s", edata->message);

		/* Can't get here, but keep compiler quiet */
		return NULL;
	}
	PG_END_TRY();

	/************************************************************
	 * Insert a hashtable entry for the plan and return
	 * the key to the caller.
	 ************************************************************/
	hv_store( plperl_query_hash, qdesc->qname, strlen(qdesc->qname), newSVuv( PTR2UV( qdesc)), 0);

	return newSVpv( qdesc->qname, strlen(qdesc->qname));
}	

HV *
plperl_spi_exec_prepared(char* query, HV * attr, int argc, SV ** argv)
{
	HV		   *ret_hv;
	SV **sv;
	int i, limit, spi_rv;
	char * nulls;
	Datum	   *argvalues;
	plperl_query_desc *qdesc;

	/*
	 * Execute the query inside a sub-transaction, so we can cope with
	 * errors sanely
	 */
	MemoryContext oldcontext = CurrentMemoryContext;
	ResourceOwner oldowner = CurrentResourceOwner;

	BeginInternalSubTransaction(NULL);
	/* Want to run inside function's memory context */
	MemoryContextSwitchTo(oldcontext);

	PG_TRY();
	{
		/************************************************************
		 * Fetch the saved plan descriptor, see if it's o.k.
		 ************************************************************/
		sv = hv_fetch(plperl_query_hash, query, strlen(query), 0);
		if ( sv == NULL) 
			elog(ERROR, "spi_exec_prepared: Invalid prepared query passed");
		if ( *sv == NULL || !SvOK( *sv))
			elog(ERROR, "spi_exec_prepared: panic - plperl_query_hash value corrupted");

		qdesc = INT2PTR( plperl_query_desc *, SvUV(*sv));
		if ( qdesc == NULL)
			elog(ERROR, "spi_exec_prepared: panic - plperl_query_hash value vanished");

		if ( qdesc-> nargs != argc) 
			elog(ERROR, "spi_exec_prepared: expected %d argument(s), %d passed", 
				qdesc-> nargs, argc);
		
		/************************************************************
		 * Parse eventual attributes
		 ************************************************************/
		limit = 0;
		if ( attr != NULL) 
		{
			sv = hv_fetch( attr, "limit", 5, 0);
			if ( *sv && SvIOK( *sv))
				limit = SvIV( *sv);
		}
		/************************************************************
		 * Set up arguments
		 ************************************************************/
2152
		if (argc > 0) 
A
 
Andrew Dunstan 已提交
2153
		{
2154
			nulls = (char *) palloc(argc);
A
 
Andrew Dunstan 已提交
2155 2156 2157 2158 2159 2160 2161 2162
			argvalues = (Datum *) palloc(argc * sizeof(Datum));
		} 
		else 
		{
			nulls = NULL;
			argvalues = NULL;
		}

2163
		for (i = 0; i < argc; i++) 
A
 
Andrew Dunstan 已提交
2164
		{
2165
			if (SvTYPE(argv[i]) != SVt_NULL) 
A
 
Andrew Dunstan 已提交
2166
			{
2167 2168 2169 2170
				argvalues[i] = InputFunctionCall(&qdesc->arginfuncs[i],
												 SvPV(argv[i], PL_na),
												 qdesc->argtypioparams[i],
												 -1);
A
 
Andrew Dunstan 已提交
2171 2172 2173 2174
				nulls[i] = ' ';
			} 
			else 
			{
2175 2176 2177 2178
				argvalues[i] = InputFunctionCall(&qdesc->arginfuncs[i],
												 NULL,
												 qdesc->argtypioparams[i],
												 -1);
A
 
Andrew Dunstan 已提交
2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281
				nulls[i] = 'n';
			}
		}

		/************************************************************
		 * go
		 ************************************************************/
		spi_rv = SPI_execute_plan(qdesc-> plan, argvalues, nulls, 
							 current_call_data->prodesc->fn_readonly, limit);
		ret_hv = plperl_spi_execute_fetch_result(SPI_tuptable, SPI_processed,
												 spi_rv);
		if ( argc > 0) 
		{
			pfree( argvalues);
			pfree( nulls);
		}

		/* Commit the inner transaction, return to outer xact context */
		ReleaseCurrentSubTransaction();
		MemoryContextSwitchTo(oldcontext);
		CurrentResourceOwner = oldowner;
		/*
		 * AtEOSubXact_SPI() should not have popped any SPI context,
		 * but just in case it did, make sure we remain connected.
		 */
		SPI_restore_connection();
	}
	PG_CATCH();
	{
		ErrorData  *edata;

		/* Save error info */
		MemoryContextSwitchTo(oldcontext);
		edata = CopyErrorData();
		FlushErrorState();

		/* Abort the inner transaction */
		RollbackAndReleaseCurrentSubTransaction();
		MemoryContextSwitchTo(oldcontext);
		CurrentResourceOwner = oldowner;

		/*
		 * If AtEOSubXact_SPI() popped any SPI context of the subxact,
		 * it will have left us in a disconnected state.  We need this
		 * hack to return to connected state.
		 */
		SPI_restore_connection();

		/* Punt the error to Perl */
		croak("%s", edata->message);

		/* Can't get here, but keep compiler quiet */
		return NULL;
	}
	PG_END_TRY();

	return ret_hv;
}

SV *
plperl_spi_query_prepared(char* query, int argc, SV ** argv)
{
	SV **sv;
	int i;
	char * nulls;
	Datum	   *argvalues;
	plperl_query_desc *qdesc;
	SV *cursor;
	Portal portal = NULL;

	/*
	 * Execute the query inside a sub-transaction, so we can cope with
	 * errors sanely
	 */
	MemoryContext oldcontext = CurrentMemoryContext;
	ResourceOwner oldowner = CurrentResourceOwner;

	BeginInternalSubTransaction(NULL);
	/* Want to run inside function's memory context */
	MemoryContextSwitchTo(oldcontext);

	PG_TRY();
	{
		/************************************************************
		 * Fetch the saved plan descriptor, see if it's o.k.
		 ************************************************************/
		sv = hv_fetch(plperl_query_hash, query, strlen(query), 0);
		if ( sv == NULL) 
			elog(ERROR, "spi_query_prepared: Invalid prepared query passed");
		if ( *sv == NULL || !SvOK( *sv))
			elog(ERROR, "spi_query_prepared: panic - plperl_query_hash value corrupted");

		qdesc = INT2PTR( plperl_query_desc *, SvUV(*sv));
		if ( qdesc == NULL)
			elog(ERROR, "spi_query_prepared: panic - plperl_query_hash value vanished");

		if ( qdesc-> nargs != argc) 
			elog(ERROR, "spi_query_prepared: expected %d argument(s), %d passed", 
				qdesc-> nargs, argc);
		
		/************************************************************
		 * Set up arguments
		 ************************************************************/
2282
		if (argc > 0) 
A
 
Andrew Dunstan 已提交
2283
		{
2284
			nulls = (char *) palloc(argc);
A
 
Andrew Dunstan 已提交
2285 2286 2287 2288 2289 2290 2291 2292
			argvalues = (Datum *) palloc(argc * sizeof(Datum));
		} 
		else 
		{
			nulls = NULL;
			argvalues = NULL;
		}

2293
		for (i = 0; i < argc; i++) 
A
 
Andrew Dunstan 已提交
2294
		{
2295
			if (SvTYPE(argv[i]) != SVt_NULL) 
A
 
Andrew Dunstan 已提交
2296
			{
2297 2298 2299 2300
				argvalues[i] = InputFunctionCall(&qdesc->arginfuncs[i],
												 SvPV(argv[i], PL_na),
												 qdesc->argtypioparams[i],
												 -1);
A
 
Andrew Dunstan 已提交
2301 2302 2303 2304
				nulls[i] = ' ';
			} 
			else 
			{
2305 2306 2307 2308
				argvalues[i] = InputFunctionCall(&qdesc->arginfuncs[i],
												 NULL,
												 qdesc->argtypioparams[i],
												 -1);
A
 
Andrew Dunstan 已提交
2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399
				nulls[i] = 'n';
			}
		}

		/************************************************************
		 * go
		 ************************************************************/
		portal = SPI_cursor_open(NULL, qdesc-> plan, argvalues, nulls, 
							current_call_data->prodesc->fn_readonly);
		if ( argc > 0) 
		{
			pfree( argvalues);
			pfree( nulls);
		}
		if ( portal == NULL) 
			elog(ERROR, "SPI_cursor_open() failed:%s",
				SPI_result_code_string(SPI_result));

		cursor = newSVpv(portal->name, 0);

		/* Commit the inner transaction, return to outer xact context */
		ReleaseCurrentSubTransaction();
		MemoryContextSwitchTo(oldcontext);
		CurrentResourceOwner = oldowner;
		/*
		 * AtEOSubXact_SPI() should not have popped any SPI context,
		 * but just in case it did, make sure we remain connected.
		 */
		SPI_restore_connection();
	}
	PG_CATCH();
	{
		ErrorData  *edata;

		/* Save error info */
		MemoryContextSwitchTo(oldcontext);
		edata = CopyErrorData();
		FlushErrorState();

		/* Abort the inner transaction */
		RollbackAndReleaseCurrentSubTransaction();
		MemoryContextSwitchTo(oldcontext);
		CurrentResourceOwner = oldowner;

		/*
		 * If AtEOSubXact_SPI() popped any SPI context of the subxact,
		 * it will have left us in a disconnected state.  We need this
		 * hack to return to connected state.
		 */
		SPI_restore_connection();

		/* Punt the error to Perl */
		croak("%s", edata->message);

		/* Can't get here, but keep compiler quiet */
		return NULL;
	}
	PG_END_TRY();

	return cursor;
}

void
plperl_spi_freeplan(char *query)
{
	SV ** sv;
	void * plan;
	plperl_query_desc *qdesc;

	sv = hv_fetch(plperl_query_hash, query, strlen(query), 0);
	if ( sv == NULL) 
		elog(ERROR, "spi_exec_freeplan: Invalid prepared query passed");
	if ( *sv == NULL || !SvOK( *sv))
		elog(ERROR, "spi_exec_freeplan: panic - plperl_query_hash value corrupted");

	qdesc = INT2PTR( plperl_query_desc *, SvUV(*sv));
	if ( qdesc == NULL)
		elog(ERROR, "spi_exec_freeplan: panic - plperl_query_hash value vanished");

	/*
	*	free all memory before SPI_freeplan, so if it dies, nothing will be left over
	*/
	hv_delete(plperl_query_hash, query, strlen(query), G_DISCARD);
	plan = qdesc-> plan;
	free(qdesc-> argtypes);
	free(qdesc-> arginfuncs);
	free(qdesc-> argtypioparams);
	free(qdesc);

	SPI_freeplan( plan);
}
2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442

/*
 * If plerl result is hash and fce result is scalar, it's hash form of
 * out argument. Then, transform it to scalar
 */

static SV *
plperl_transform_result(plperl_proc_desc *prodesc, SV *result)
{
	bool        exactly_one_field = false;
	HV         *hvr;
	SV		   *val;
	char	   *key;
	I32			klen;


	if (prodesc->num_out_args == 1 && SvOK(result) 
		&& SvTYPE(result) == SVt_RV && SvTYPE(SvRV(result)) == SVt_PVHV)
	{
		hvr = (HV *) SvRV(result);
		hv_iterinit(hvr);

		while ((val = hv_iternextsv(hvr, &key, &klen)))
		{
			if (exactly_one_field)
				ereport(ERROR,
						(errcode(ERRCODE_UNDEFINED_COLUMN),
						 errmsg("Perl hash contains nonexistent column \"%s\"",
								key)));
			exactly_one_field = true;
			result = val;
		}

		if (!exactly_one_field)
			ereport(ERROR,
					(errcode(ERRCODE_UNDEFINED_COLUMN),
					 errmsg("Perl hash is empty")));
			
		hv_iterinit(hvr);
	}	    

	return result;
}