2 44.6. Database Access #
4 44.6.1. Database Access Functions
5 44.6.2. Trapping Errors
7 The PL/Python language module automatically imports a Python module
8 called plpy. The functions and constants in this module are available
9 to you in the Python code as plpy.foo.
11 44.6.1. Database Access Functions #
13 The plpy module provides several functions to execute database
16 plpy.execute(query [, limit])
17 Calling plpy.execute with a query string and an optional row
18 limit argument causes that query to be run and the result to be
19 returned in a result object.
21 If limit is specified and is greater than zero, then
22 plpy.execute retrieves at most limit rows, much as if the query
23 included a LIMIT clause. Omitting limit or specifying it as zero
24 results in no row limit.
26 The result object emulates a list or dictionary object. The
27 result object can be accessed by row number and column name. For
30 rv = plpy.execute("SELECT * FROM my_table", 5)
32 returns up to 5 rows from my_table. If my_table has a column
33 my_column, it would be accessed as:
35 foo = rv[i]["my_column"]
37 The number of rows returned can be obtained using the built-in
40 The result object has these additional methods:
43 Returns the number of rows processed by the command. Note
44 that this is not necessarily the same as the number of
45 rows returned. For example, an UPDATE command will set
46 this value but won't return any rows (unless RETURNING is
50 The SPI_execute() return value.
55 Return a list of column names, list of column type OIDs,
56 and list of type-specific type modifiers for the columns,
59 These methods raise an exception when called on a result
60 object from a command that did not produce a result set,
61 e.g., UPDATE without RETURNING, or DROP TABLE. But it is
62 OK to use these methods on a result set containing zero
66 The standard __str__ method is defined so that it is
67 possible for example to debug query execution results
70 The result object can be modified.
72 Note that calling plpy.execute will cause the entire result set
73 to be read into memory. Only use that function when you are sure
74 that the result set will be relatively small. If you don't want
75 to risk excessive memory usage when fetching large results, use
76 plpy.cursor rather than plpy.execute.
78 plpy.prepare(query [, argtypes])
79 plpy.execute(plan [, arguments [, limit]])
80 plpy.prepare prepares the execution plan for a query. It is
81 called with a query string and a list of parameter types, if you
82 have parameter references in the query. For example:
84 plan = plpy.prepare("SELECT last_name FROM my_users WHERE first_name = $1", ["te
87 text is the type of the variable you will be passing for $1. The
88 second argument is optional if you don't want to pass any
89 parameters to the query.
91 After preparing a statement, you use a variant of the function
92 plpy.execute to run it:
94 rv = plpy.execute(plan, ["name"], 5)
96 Pass the plan as the first argument (instead of the query
97 string), and a list of values to substitute into the query as
98 the second argument. The second argument is optional if the
99 query does not expect any parameters. The third argument is the
100 optional row limit as before.
102 Alternatively, you can call the execute method on the plan
105 rv = plan.execute(["name"], 5)
107 Query parameters and result row fields are converted between
108 PostgreSQL and Python data types as described in Section 44.2.
110 When you prepare a plan using the PL/Python module it is
111 automatically saved. Read the SPI documentation (Chapter 45) for
112 a description of what this means. In order to make effective use
113 of this across function calls one needs to use one of the
114 persistent storage dictionaries SD or GD (see Section 44.3). For
117 CREATE FUNCTION usesavedplan() RETURNS trigger AS $$
121 plan = plpy.prepare("SELECT 1")
124 $$ LANGUAGE plpython3u;
127 plpy.cursor(plan [, arguments])
128 The plpy.cursor function accepts the same arguments as
129 plpy.execute (except for the row limit) and returns a cursor
130 object, which allows you to process large result sets in smaller
131 chunks. As with plpy.execute, either a query string or a plan
132 object along with a list of arguments can be used, or the cursor
133 function can be called as a method of the plan object.
135 The cursor object provides a fetch method that accepts an
136 integer parameter and returns a result object. Each time you
137 call fetch, the returned object will contain the next batch of
138 rows, never larger than the parameter value. Once all rows are
139 exhausted, fetch starts returning an empty result object. Cursor
140 objects also provide an iterator interface, yielding one row at
141 a time until all rows are exhausted. Data fetched that way is
142 not returned as result objects, but rather as dictionaries, each
143 dictionary corresponding to a single result row.
145 An example of two ways of processing data from a large table is:
147 CREATE FUNCTION count_odd_iterator() RETURNS integer AS $$
149 for row in plpy.cursor("select num from largetable"):
153 $$ LANGUAGE plpython3u;
155 CREATE FUNCTION count_odd_fetch(batch_size integer) RETURNS integer AS $$
157 cursor = plpy.cursor("select num from largetable")
159 rows = cursor.fetch(batch_size)
166 $$ LANGUAGE plpython3u;
168 CREATE FUNCTION count_odd_prepared() RETURNS integer AS $$
170 plan = plpy.prepare("select num from largetable where num % $1 <> 0", ["integer"
172 rows = list(plpy.cursor(plan, [2])) # or: = list(plan.cursor([2]))
175 $$ LANGUAGE plpython3u;
177 Cursors are automatically disposed of. But if you want to
178 explicitly release all resources held by a cursor, use the close
179 method. Once closed, a cursor cannot be fetched from anymore.
183 Do not confuse objects created by plpy.cursor with DB-API
184 cursors as defined by the Python Database API specification.
185 They don't have anything in common except for the name.
187 44.6.2. Trapping Errors #
189 Functions accessing the database might encounter errors, which will
190 cause them to abort and raise an exception. Both plpy.execute and
191 plpy.prepare can raise an instance of a subclass of plpy.SPIError,
192 which by default will terminate the function. This error can be handled
193 just like any other Python exception, by using the try/except
194 construct. For example:
195 CREATE FUNCTION try_adding_joe() RETURNS text AS $$
197 plpy.execute("INSERT INTO users(username) VALUES ('joe')")
198 except plpy.SPIError:
199 return "something went wrong"
202 $$ LANGUAGE plpython3u;
204 The actual class of the exception being raised corresponds to the
205 specific condition that caused the error. Refer to Table A.1 for a list
206 of possible conditions. The module plpy.spiexceptions defines an
207 exception class for each PostgreSQL condition, deriving their names
208 from the condition name. For instance, division_by_zero becomes
209 DivisionByZero, unique_violation becomes UniqueViolation, fdw_error
210 becomes FdwError, and so on. Each of these exception classes inherits
211 from SPIError. This separation makes it easier to handle specific
212 errors, for instance:
213 CREATE FUNCTION insert_fraction(numerator int, denominator int) RETURNS text AS
215 from plpy import spiexceptions
217 plan = plpy.prepare("INSERT INTO fractions (frac) VALUES ($1 / $2)", ["int",
219 plpy.execute(plan, [numerator, denominator])
220 except spiexceptions.DivisionByZero:
221 return "denominator cannot equal zero"
222 except spiexceptions.UniqueViolation:
223 return "already have that fraction"
224 except plpy.SPIError as e:
225 return "other error, SQLSTATE %s" % e.sqlstate
227 return "fraction inserted"
228 $$ LANGUAGE plpython3u;
230 Note that because all exceptions from the plpy.spiexceptions module
231 inherit from SPIError, an except clause handling it will catch any
232 database access error.
234 As an alternative way of handling different error conditions, you can
235 catch the SPIError exception and determine the specific error condition
236 inside the except block by looking at the sqlstate attribute of the
237 exception object. This attribute is a string value containing the
238 “SQLSTATE” error code. This approach provides approximately the same