Commit 1d2fe56e authored by Tom Lane's avatar Tom Lane

Fix PL/Python for recursion and interleaved set-returning functions.

PL/Python failed if a PL/Python function was invoked recursively via SPI,
since arguments are passed to the function in its global dictionary
(a horrible decision that's far too ancient to undo) and it would delete
those dictionary entries on function exit, leaving the outer recursion
level(s) without any arguments.  Not deleting them would be little better,
since the outer levels would then see the innermost level's arguments.

Since PL/Python uses ValuePerCall mode for evaluating set-returning
functions, it's possible for multiple executions of the same SRF to be
interleaved within a query.  PL/Python failed in such a case, because
it stored only one iterator per function, directly in the function's
PLyProcedure struct.  Moreover, one interleaved instance of the SRF
would see argument values that should belong to another.

Hence, invent code for saving and restoring the argument entries.  To fix
the recursion case, we only need to save at recursive entry and restore
at recursive exit, so the overhead in non-recursive cases is negligible.
To fix the SRF case, we have to save when suspending a SRF and restore
when resuming it, which is potentially not negligible; but fortunately
this is mostly a matter of manipulating Python object refcounts and
should not involve much physical data copying.

Also, store the Python iterator and saved argument values in a structure
associated with the SRF call site rather than the function itself.  This
requires adding a memory context deletion callback to ensure that the SRF
state is cleaned up if the calling query exits before running the SRF to
completion.  Without that we'd leak a refcount to the iterator object in
such a case, resulting in session-lifespan memory leakage.  (In the
pre-existing code, there was no memory leak because there was only one
iterator pointer, but what would happen is that the previous iterator
would be resumed by the next query attempting to use the SRF.  Hardly the
semantics we want.)

We can buy back some of whatever overhead we've added by getting rid of
PLy_function_delete_args(), which seems a useless activity: there is no
need to delete argument entries from the global dictionary on exit,
since the next time anyone would see the global dict is on the next
fresh call of the PL/Python function, at which time we'd overwrite those
entries with new arg values anyway.

Also clean up some really ugly coding in the SRF implementation, including
such gems as returning directly out of a PG_TRY block.  (The only reason
that failed to crash hard was that all existing call sites immediately
exited their own PG_TRY blocks, popping the dangling longjmp pointer before
there was any chance of it being used.)

In principle this is a bug fix; but it seems a bit too invasive relative to
its value for a back-patch, and besides the fix depends on memory context
callbacks so it could not go back further than 9.5 anyway.

Alexey Grishchenko and Tom Lane
parent 11c8669c
......@@ -124,6 +124,35 @@ SELECT test_setof_spi_in_iterator();
World
(4 rows)
-- set-returning function that modifies its parameters
CREATE OR REPLACE FUNCTION ugly(x int, lim int) RETURNS SETOF int AS $$
global x
while x <= lim:
yield x
x = x + 1
$$ LANGUAGE plpythonu;
SELECT ugly(1, 5);
ugly
------
1
2
3
4
5
(5 rows)
-- interleaved execution of such a function
SELECT ugly(1,3), ugly(7,8);
ugly | ugly
------+------
1 | 7
2 | 8
3 | 7
1 | 8
2 | 7
3 | 8
(6 rows)
-- returns set of named-composite-type tuples
CREATE OR REPLACE FUNCTION get_user_records()
RETURNS SETOF users
......
......@@ -57,6 +57,15 @@ for r in rv:
return seq
'
LANGUAGE plpythonu;
CREATE FUNCTION spi_recursive_sum(a int) RETURNS int
AS
'r = 0
if a > 1:
r = plpy.execute("SELECT spi_recursive_sum(%d) as a" % (a-1))[0]["a"]
return a + r
'
LANGUAGE plpythonu;
--
-- spi and nested calls
--
select nested_call_one('pass this along');
......@@ -112,6 +121,12 @@ SELECT join_sequences(sequences) FROM sequences
----------------
(0 rows)
SELECT spi_recursive_sum(10);
spi_recursive_sum
-------------------
55
(1 row)
--
-- plan and result objects
--
......
This diff is collapsed.
......@@ -188,10 +188,11 @@ PLy_procedure_create(HeapTuple procTup, Oid fn_oid, bool is_trigger)
proc->pyname = pstrdup(procName);
proc->fn_xmin = HeapTupleHeaderGetRawXmin(procTup->t_data);
proc->fn_tid = procTup->t_self;
/* Remember if function is STABLE/IMMUTABLE */
proc->fn_readonly =
(procStruct->provolatile != PROVOLATILE_VOLATILE);
proc->fn_readonly = (procStruct->provolatile != PROVOLATILE_VOLATILE);
proc->is_setof = procStruct->proretset;
PLy_typeinfo_init(&proc->result, proc->mcxt);
proc->src = NULL;
proc->argnames = NULL;
for (i = 0; i < FUNC_MAX_ARGS; i++)
PLy_typeinfo_init(&proc->args[i], proc->mcxt);
proc->nargs = 0;
......@@ -200,12 +201,11 @@ PLy_procedure_create(HeapTuple procTup, Oid fn_oid, bool is_trigger)
Anum_pg_proc_protrftypes,
&isnull);
proc->trftypes = isnull ? NIL : oid_array_to_list(protrftypes_datum);
proc->code = proc->statics = NULL;
proc->code = NULL;
proc->statics = NULL;
proc->globals = NULL;
proc->is_setof = procStruct->proretset;
proc->setof = NULL;
proc->src = NULL;
proc->argnames = NULL;
proc->calldepth = 0;
proc->argstack = NULL;
/*
* get information required for output conversion of the return value,
......
......@@ -11,6 +11,15 @@
extern void init_procedure_caches(void);
/* saved arguments for outer recursion level or set-returning function */
typedef struct PLySavedArgs
{
struct PLySavedArgs *next; /* linked-list pointer */
PyObject *args; /* "args" element of globals dict */
int nargs; /* length of namedargs array */
PyObject *namedargs[FLEXIBLE_ARRAY_MEMBER]; /* named args */
} PLySavedArgs;
/* cached procedure data */
typedef struct PLyProcedure
{
......@@ -21,10 +30,9 @@ typedef struct PLyProcedure
TransactionId fn_xmin;
ItemPointerData fn_tid;
bool fn_readonly;
bool is_setof; /* true, if procedure returns result set */
PLyTypeInfo result; /* also used to store info for trigger tuple
* type */
bool is_setof; /* true, if procedure returns result set */
PyObject *setof; /* contents of result set. */
char *src; /* textual procedure code, after mangling */
char **argnames; /* Argument names */
PLyTypeInfo args[FUNC_MAX_ARGS];
......@@ -34,6 +42,8 @@ typedef struct PLyProcedure
PyObject *code; /* compiled procedure code */
PyObject *statics; /* data saved across calls, local scope */
PyObject *globals; /* data saved across calls, global scope */
long calldepth; /* depth of recursive calls of function */
PLySavedArgs *argstack; /* stack of outer-level call arguments */
} PLyProcedure;
/* the procedure cache key */
......
......@@ -63,6 +63,18 @@ SELECT test_setof_as_iterator(2, null);
SELECT test_setof_spi_in_iterator();
-- set-returning function that modifies its parameters
CREATE OR REPLACE FUNCTION ugly(x int, lim int) RETURNS SETOF int AS $$
global x
while x <= lim:
yield x
x = x + 1
$$ LANGUAGE plpythonu;
SELECT ugly(1, 5);
-- interleaved execution of such a function
SELECT ugly(1,3), ugly(7,8);
-- returns set of named-composite-type tuples
CREATE OR REPLACE FUNCTION get_user_records()
......
......@@ -52,9 +52,6 @@ return None
'
LANGUAGE plpythonu;
CREATE FUNCTION join_sequences(s sequences) RETURNS text
AS
'if not s["multipart"]:
......@@ -68,10 +65,16 @@ return seq
'
LANGUAGE plpythonu;
CREATE FUNCTION spi_recursive_sum(a int) RETURNS int
AS
'r = 0
if a > 1:
r = plpy.execute("SELECT spi_recursive_sum(%d) as a" % (a-1))[0]["a"]
return a + r
'
LANGUAGE plpythonu;
--
-- spi and nested calls
--
select nested_call_one('pass this along');
......@@ -79,15 +82,13 @@ select spi_prepared_plan_test_one('doe');
select spi_prepared_plan_test_one('smith');
select spi_prepared_plan_test_nested('smith');
SELECT join_sequences(sequences) FROM sequences;
SELECT join_sequences(sequences) FROM sequences
WHERE join_sequences(sequences) ~* '^A';
SELECT join_sequences(sequences) FROM sequences
WHERE join_sequences(sequences) ~* '^B';
SELECT spi_recursive_sum(10);
--
-- plan and result objects
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment