Created
October 2, 2021 11:21
-
-
Save CodyKochmann/b6f6b5907f9a93008f388132a4836c2d to your computer and use it in GitHub Desktop.
stateful embedded postgres python functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# 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