Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
stateful embedded postgres python functions
#
# description: demo of shared data in plpython functions
# by: Cody Kochmann
# date: 2021-10-02
#
testdb=> -- pg has two magic vars for plpython3u functions
testdb=> -- SD | dict | per function memory
testsb=> -- GD | dict | global shared function memory
testdb=> CREATE FUNCTION state_test (t TEXT)
RETURNS TEXT[]
AS $$
SD["data"] = SD["data"] + [t] if "data" in SD else [t]
return SD["data"]
$$ LANGUAGE plpython3u;
CREATE FUNCTION
testdb=> SELECT state_test('waffles');
state_test
------------
{waffles}
(1 row)
testdb=> SELECT state_test('are');
state_test
---------------
{waffles,are}
(1 row)
testdb=> SELECT state_test('better');
state_test
----------------------
{waffles,are,better}
(1 row)
testdb=> SELECT state_test('than');
state_test
---------------------------
{waffles,are,better,than}
(1 row)
testdb=> SELECT state_test('pancakes');
state_test
------------------------------------
{waffles,are,better,than,pancakes}
(1 row)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment