Skip to content

Instantly share code, notes, and snippets.

@rturowicz
Last active February 2, 2019 20:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save rturowicz/5232050 to your computer and use it in GitHub Desktop.
Save rturowicz/5232050 to your computer and use it in GitHub Desktop.
postgresql: example use of python procedural language
-- query with stored plan
CREATE or replace FUNCTION pybench1(id int) RETURNS text AS '
if (SD.has_key("plan")):
plan = SD["plan"]
else:
plan = plpy.prepare("SELECT * FROM pagetimer pt, pagebrowser pb WHERE pt.idtimer = $1 and pt.idtimer = pb.idtimer", ["int4"])
SD["plan"] = plan
rec = plpy.execute(plan, [id])
if (rec.nrows() > 0):
return rec[0]["parent"]
else:
return "b.d."
' LANGUAGE plpythonu SECURITY DEFINER;
-- simple query
CREATE or replace FUNCTION pybench2(id int) RETURNS text AS '
rec = plpy.execute("SELECT * FROM pagetimer pt, pagebrowser pb WHERE pt.idtimer = "+str(id)+" and pt.idtimer = pb.idtimer")
if (rec.nrows() > 0):
return rec[0]["parent"]
else:
return "b.d."
' LANGUAGE plpythonu SECURITY DEFINER;
-- private dictionary (for function calls in one session)
CREATE or replace FUNCTION testpy() RETURNS int AS '
if SD.has_key("tmp"):
SD["tmp"] = SD["tmp"] + 1
else:
SD["tmp"] = 1
return SD["tmp"]
' LANGUAGE plpythonu SECURITY DEFINER;
-- global dictionary (for all functions in one session)
CREATE or replace FUNCTION testpy2() RETURNS int AS '
if GD.has_key("tmp"):
GD["tmp"] = GD["tmp"] + 1
else:
GD["tmp"] = 1
return GD["tmp"]
' LANGUAGE plpythonu SECURITY DEFINER;
-- logging
CREATE or replace FUNCTION testpy3() returns int AS '
plpy.debug("test debug")
plpy.log("test log")
plpy.info("test info")
plpy.notice("test notice")
plpy.warning("test warning")
return 1
' LANGUAGE plpythonu SECURITY DEFINER;
-- function with variable parameters list
CREATE or replace FUNCTION testpy4(keys text, vals text) returns int AS '
params = dict(zip(keys.split(","), vals.split(",")))
for p in params.keys():
plpy.info(params[p])
return 1
' LANGUAGE plpythonu SECURITY DEFINER;
select testpy4('p1,p2,p3', 'v1,v''2'',?v3&ee=2&ss')
@javadba
Copy link

javadba commented Dec 29, 2018

What are SD and GD? Are these dictionaries in your own python program or are these dictionaries built in to plpythonu ? If the former, what are the requirements/restrictions to use arbitrary global objects within plpythonu ?

Update: OK found answer:

The global dictionary SD is available to store data between function calls. This variable is private static data. The global dictionary GD is public data, available to all Python functions within a session. Use with care.

https://www.postgresql.org/docs/8.2/plpython-funcs.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment