PostgreSQL 9.1.24 Documentation | ||||
---|---|---|---|---|
Prev | Up | Chapter 42. PL/Python - Python Procedural Language | Next |
The PL/Python language module automatically imports a Python module calledplpy. The functions and constants in this module are available to you in the Python code asplpy.foo.
Theplpy module provides two functions calledexecute
andprepare
. Callingplpy.execute
with a query string and an optional limit argument causes that query to be run and the result to be returned in a result object. The result object emulates a list or dictionary object. The result object can be accessed by row number and column name. It has these additional methods:nrows
which returns the number of rows returned by the query, andstatus
which is theSPI_execute()
return value. The result object can be modified.
For example:
rv = plpy.execute("SELECT * FROM my_table", 5)
returns up to 5 rows frommy_table. Ifmy_table has a columnmy_column, it would be accessed as:
foo = rv[i]["my_column"]
The second function,plpy.prepare
, prepares the execution plan for a query. It is called with a query string and a list of parameter types, if you have parameter references in the query. For example:
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 functionplpy.execute
to run it:
rv = plpy.execute(plan, [ "name" ], 5)
The third argument is the limit and is optional.
Query parameters and result row fields are converted between PostgreSQL and Python data types as described inSection 42.3. The exception is that composite types are currently not supported: They will be rejected as query parameters and are converted to strings when appearing in a query result. As a workaround for the latter problem, the query can sometimes be rewritten so that the composite type result appears as a result row rather than as a field of the result row. Alternatively, the resulting string could be parsed apart by hand, but this approach is not recommended because it is not future-proof.
When you prepare a plan using the PL/Python module it is automatically saved. Read the SPI documentation (Chapter 43) 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 dictionariesSD orGD (seeSection 42.4). 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;
Functions accessing the database might encounter errors, which will cause them to abort and raise an exception. Bothplpy.execute
andplpy.prepare
can raise an instance of a subclass ofplpy.SPIError, which by default will terminate the function. This error can be handled just like any other Python exception, by using thetry/except construct. For example:
CREATE FUNCTION try_adding_joe() RETURNS text AS $$ try: plpy.execute("INSERT INTO users(username) VALUES ('joe')") except plpy.SPIError: return "something went wrong" else: return "Joe added"$$ LANGUAGE plpythonu;
The actual class of the exception being raised corresponds to the specific condition that caused the error. Refer toTable A-1 for a list of possible conditions. The moduleplpy.spiexceptions defines an exception class for eachPostgreSQL condition, deriving their names from the condition name. For instance,division_by_zero becomesDivisionByZero,unique_violation becomesUniqueViolation,fdw_error becomesFdwError, and so on. Each of these exception classes inherits fromSPIError. This separation makes it easier to handle specific errors, for instance:
CREATE FUNCTION insert_fraction(numerator int, denominator int) RETURNS text AS $$from plpy import spiexceptionstry: plan = plpy.prepare("INSERT INTO fractions (frac) VALUES ($1 / $2)", ["int", "int"]) plpy.execute(plan, [numerator, denominator])except spiexceptions.DivisionByZero: return "denominator cannot equal zero"except spiexceptions.UniqueViolation: return "already have that fraction"except plpy.SPIError, e: return "other error, SQLSTATE %s" % e.sqlstateelse: return "fraction inserted"$$ LANGUAGE plpythonu;
Note that because all exceptions from theplpy.spiexceptions module inherit fromSPIError, anexcept clause handling it will catch any database access error.
As an alternative way of handling different error conditions, you can catch theSPIError exception and determine the specific error condition inside theexcept block by looking at thesqlstate attribute of the exception object. This attribute is a string value containing the"SQLSTATE" error code. This approach provides approximately the same functionality