Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CodyKochmann/b6f6b5907f9a93008f388132a4836c2d to your computer and use it in GitHub Desktop.
Save CodyKochmann/b6f6b5907f9a93008f388132a4836c2d to your computer and use it in GitHub Desktop.
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