![]() | ![]() | ![]() | ![]() |
41.3. Database Access The PL/Python language module automatically imports a Python module
called plpy. The functions and constants in
this module are available to you in the Python code as
plpy.foo. At present
plpy implements the functions
plpy.debug(msg),
plpy.log(msg),
plpy.info(msg),
plpy.notice(msg),
plpy.warning(msg),
plpy.error(msg), and
plpy.fatal(msg).
Additionally, the plpy module provides two
functions called For example: rv = plpy.execute("SELECT * FROM my_table", 5)returns up to 5 rows from my_table. If my_table has a column my_column, it would be accessed as: foo = rv[i]["my_column"]
The second function, plan = plpy.prepare("SELECT last_name FROM my_users WHERE first_name = $1", [ "text" ])
text is the type of the variable you will be
passing for $1. After preparing a statement, you
use the function rv = plpy.execute(plan, [ "name" ], 5) The third argument is the limit and is optional. When you prepare a plan using the PL/Python module it is automatically saved. Read the SPI documentation (Chapter 42) for a description of what this means. In order to make effective use of this across function calls one needs to use one of the persistent storage dictionaries SD or GD (see Section 41.1). For example: CREATE FUNCTION usesavedplan() RETURNS trigger AS $$
if SD.has_key("plan"):
plan = SD["plan"]
else:
plan = plpy.prepare("SELECT 1")
SD["plan"] = plan
# rest of function
$$ LANGUAGE plpythonu;
|
||||||||||||