4 44.2.1. Data Type Mapping
7 44.2.4. Composite Types
8 44.2.5. Set-Returning Functions
10 Generally speaking, the aim of PL/Python is to provide a “natural”
11 mapping between the PostgreSQL and the Python worlds. This informs the
12 data mapping rules described below.
14 44.2.1. Data Type Mapping #
16 When a PL/Python function is called, its arguments are converted from
17 their PostgreSQL data type to a corresponding Python type:
18 * PostgreSQL boolean is converted to Python bool.
19 * PostgreSQL smallint, int, bigint and oid are converted to Python
21 * PostgreSQL real and double are converted to Python float.
22 * PostgreSQL numeric is converted to Python Decimal. This type is
23 imported from the cdecimal package if that is available. Otherwise,
24 decimal.Decimal from the standard library will be used. cdecimal is
25 significantly faster than decimal. In Python 3.3 and up, however,
26 cdecimal has been integrated into the standard library under the
27 name decimal, so there is no longer any difference.
28 * PostgreSQL bytea is converted to Python bytes.
29 * All other data types, including the PostgreSQL character string
30 types, are converted to a Python str (in Unicode like all Python
32 * For nonscalar data types, see below.
34 When a PL/Python function returns, its return value is converted to the
35 function's declared PostgreSQL return data type as follows:
36 * When the PostgreSQL return type is boolean, the return value will
37 be evaluated for truth according to the Python rules. That is, 0
38 and empty string are false, but notably 'f' is true.
39 * When the PostgreSQL return type is bytea, the return value will be
40 converted to Python bytes using the respective Python built-ins,
41 with the result being converted to bytea.
42 * For all other PostgreSQL return types, the return value is
43 converted to a string using the Python built-in str, and the result
44 is passed to the input function of the PostgreSQL data type. (If
45 the Python value is a float, it is converted using the repr
46 built-in instead of str, to avoid loss of precision.)
47 Strings are automatically converted to the PostgreSQL server
48 encoding when they are passed to PostgreSQL.
49 * For nonscalar data types, see below.
51 Note that logical mismatches between the declared PostgreSQL return
52 type and the Python data type of the actual return object are not
53 flagged; the value will be converted in any case.
57 If an SQL null value is passed to a function, the argument value will
58 appear as None in Python. For example, the function definition of pymax
59 shown in Section 44.1 will return the wrong answer for null inputs. We
60 could add STRICT to the function definition to make PostgreSQL do
61 something more reasonable: if a null value is passed, the function will
62 not be called at all, but will just return a null result automatically.
63 Alternatively, we could check for null inputs in the function body:
64 CREATE FUNCTION pymax (a integer, b integer)
67 if (a is None) or (b is None):
72 $$ LANGUAGE plpython3u;
74 As shown above, to return an SQL null value from a PL/Python function,
75 return the value None. This can be done whether the function is strict
78 44.2.3. Arrays, Lists #
80 SQL array values are passed into PL/Python as a Python list. To return
81 an SQL array value out of a PL/Python function, return a Python list:
82 CREATE FUNCTION return_arr()
85 return [1, 2, 3, 4, 5]
86 $$ LANGUAGE plpython3u;
94 Multidimensional arrays are passed into PL/Python as nested Python
95 lists. A 2-dimensional array is a list of lists, for example. When
96 returning a multi-dimensional SQL array out of a PL/Python function,
97 the inner lists at each level must all be of the same size. For
99 CREATE FUNCTION test_type_conversion_array_int4(x int4[]) RETURNS int4[] AS $$
100 plpy.info(x, type(x))
102 $$ LANGUAGE plpython3u;
104 SELECT * FROM test_type_conversion_array_int4(ARRAY[[1,2,3],[4,5,6]]);
105 INFO: ([[1, 2, 3], [4, 5, 6]], <type 'list'>)
106 test_type_conversion_array_int4
107 ---------------------------------
111 Other Python sequences, like tuples, are also accepted for
112 backwards-compatibility with PostgreSQL versions 9.6 and below, when
113 multi-dimensional arrays were not supported. However, they are always
114 treated as one-dimensional arrays, because they are ambiguous with
115 composite types. For the same reason, when a composite type is used in
116 a multi-dimensional array, it must be represented by a tuple, rather
119 Note that in Python, strings are sequences, which can have undesirable
120 effects that might be familiar to Python programmers:
121 CREATE FUNCTION return_str_arr()
125 $$ LANGUAGE plpython3u;
127 SELECT return_str_arr();
133 44.2.4. Composite Types #
135 Composite-type arguments are passed to the function as Python mappings.
136 The element names of the mapping are the attribute names of the
137 composite type. If an attribute in the passed row has the null value,
138 it has the value None in the mapping. Here is an example:
139 CREATE TABLE employee (
145 CREATE FUNCTION overpaid (e employee)
148 if e["salary"] > 200000:
150 if (e["age"] < 30) and (e["salary"] > 100000):
153 $$ LANGUAGE plpython3u;
155 There are multiple ways to return row or composite types from a Python
156 function. The following examples assume we have:
157 CREATE TYPE named_value AS (
162 A composite result can be returned as a:
164 Sequence type (a tuple or list, but not a set because it is not
166 Returned sequence objects must have the same number of items as
167 the composite result type has fields. The item with index 0 is
168 assigned to the first field of the composite type, 1 to the
169 second and so on. For example:
171 CREATE FUNCTION make_pair (name text, value integer)
174 return ( name, value )
175 # or alternatively, as list: return [ name, value ]
176 $$ LANGUAGE plpython3u;
178 To return an SQL null for any column, insert None at the
179 corresponding position.
181 When an array of composite types is returned, it cannot be
182 returned as a list, because it is ambiguous whether the Python
183 list represents a composite type, or another array dimension.
186 The value for each result type column is retrieved from the
187 mapping with the column name as key. Example:
189 CREATE FUNCTION make_pair (name text, value integer)
192 return { "name": name, "value": value }
193 $$ LANGUAGE plpython3u;
195 Any extra dictionary key/value pairs are ignored. Missing keys
196 are treated as errors. To return an SQL null value for any
197 column, insert None with the corresponding column name as the
200 Object (any object providing method __getattr__)
201 This works the same as a mapping. Example:
203 CREATE FUNCTION make_pair (name text, value integer)
207 def __init__ (self, n, v):
210 return named_value(name, value)
217 $$ LANGUAGE plpython3u;
219 Functions with OUT parameters are also supported. For example:
220 CREATE FUNCTION multiout_simple(OUT i integer, OUT j integer) AS $$
222 $$ LANGUAGE plpython3u;
224 SELECT * FROM multiout_simple();
226 Output parameters of procedures are passed back the same way. For
228 CREATE PROCEDURE python_triple(INOUT a integer, INOUT b integer) AS $$
229 return (a * 3, b * 3)
230 $$ LANGUAGE plpython3u;
232 CALL python_triple(5, 10);
234 44.2.5. Set-Returning Functions #
236 A PL/Python function can also return sets of scalar or composite types.
237 There are several ways to achieve this because the returned object is
238 internally turned into an iterator. The following examples assume we
240 CREATE TYPE greeting AS (
245 A set result can be returned from a:
247 Sequence type (tuple, list, set)
249 CREATE FUNCTION greet (how text)
250 RETURNS SETOF greeting
252 # return tuple containing lists as composite types
253 # all other combinations work also
254 return ( [ how, "World" ], [ how, "PostgreSQL" ], [ how, "PL/Python" ] )
255 $$ LANGUAGE plpython3u;
257 Iterator (any object providing __iter__ and __next__ methods)
259 CREATE FUNCTION greet (how text)
260 RETURNS SETOF greeting
263 def __init__ (self, how, who):
273 if self.ndx == len(self.who):
275 return ( self.how, self.who[self.ndx] )
277 return producer(how, [ "World", "PostgreSQL", "PL/Python" ])
278 $$ LANGUAGE plpython3u;
282 CREATE FUNCTION greet (how text)
283 RETURNS SETOF greeting
285 for who in [ "World", "PostgreSQL", "PL/Python" ]:
287 $$ LANGUAGE plpython3u;
289 Set-returning functions with OUT parameters (using RETURNS SETOF
290 record) are also supported. For example:
291 CREATE FUNCTION multiout_simple_setof(n integer, OUT integer, OUT integer) RETUR
292 NS SETOF record AS $$
294 $$ LANGUAGE plpython3u;
296 SELECT * FROM multiout_simple_setof(3);