]> begriffs open source - ai-pg/blob - full-docs/txt/plpython-data.txt
Convert HTML docs to more streamlined TXT
[ai-pg] / full-docs / txt / plpython-data.txt
1
2 44.2. Data Values #
3
4    44.2.1. Data Type Mapping
5    44.2.2. Null, None
6    44.2.3. Arrays, Lists
7    44.2.4. Composite Types
8    44.2.5. Set-Returning Functions
9
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.
13
14 44.2.1. Data Type Mapping #
15
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
20        int.
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
31        strings).
32      * For nonscalar data types, see below.
33
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.
50
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.
54
55 44.2.2. Null, None #
56
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)
65   RETURNS integer
66 AS $$
67   if (a is None) or (b is None):
68     return None
69   if a > b:
70     return a
71   return b
72 $$ LANGUAGE plpython3u;
73
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
76    or not.
77
78 44.2.3. Arrays, Lists #
79
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()
83   RETURNS int[]
84 AS $$
85 return [1, 2, 3, 4, 5]
86 $$ LANGUAGE plpython3u;
87
88 SELECT return_arr();
89  return_arr
90 -------------
91  {1,2,3,4,5}
92 (1 row)
93
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
98    example:
99 CREATE FUNCTION test_type_conversion_array_int4(x int4[]) RETURNS int4[] AS $$
100 plpy.info(x, type(x))
101 return x
102 $$ LANGUAGE plpython3u;
103
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 ---------------------------------
108  {{1,2,3},{4,5,6}}
109 (1 row)
110
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
117    than a list.
118
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()
122   RETURNS varchar[]
123 AS $$
124 return "hello"
125 $$ LANGUAGE plpython3u;
126
127 SELECT return_str_arr();
128  return_str_arr
129 ----------------
130  {h,e,l,l,o}
131 (1 row)
132
133 44.2.4. Composite Types #
134
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 (
140   name text,
141   salary integer,
142   age integer
143 );
144
145 CREATE FUNCTION overpaid (e employee)
146   RETURNS boolean
147 AS $$
148   if e["salary"] > 200000:
149     return True
150   if (e["age"] < 30) and (e["salary"] > 100000):
151     return True
152   return False
153 $$ LANGUAGE plpython3u;
154
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 (
158   name   text,
159   value  integer
160 );
161
162    A composite result can be returned as a:
163
164    Sequence type (a tuple or list, but not a set because it is not
165           indexable)
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:
170
171 CREATE FUNCTION make_pair (name text, value integer)
172   RETURNS named_value
173 AS $$
174   return ( name, value )
175   # or alternatively, as list: return [ name, value ]
176 $$ LANGUAGE plpython3u;
177
178           To return an SQL null for any column, insert None at the
179           corresponding position.
180
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.
184
185    Mapping (dictionary)
186           The value for each result type column is retrieved from the
187           mapping with the column name as key. Example:
188
189 CREATE FUNCTION make_pair (name text, value integer)
190   RETURNS named_value
191 AS $$
192   return { "name": name, "value": value }
193 $$ LANGUAGE plpython3u;
194
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
198           key.
199
200    Object (any object providing method __getattr__)
201           This works the same as a mapping. Example:
202
203 CREATE FUNCTION make_pair (name text, value integer)
204   RETURNS named_value
205 AS $$
206   class named_value:
207     def __init__ (self, n, v):
208       self.name = n
209       self.value = v
210   return named_value(name, value)
211
212   # or simply
213   class nv: pass
214   nv.name = name
215   nv.value = value
216   return nv
217 $$ LANGUAGE plpython3u;
218
219    Functions with OUT parameters are also supported. For example:
220 CREATE FUNCTION multiout_simple(OUT i integer, OUT j integer) AS $$
221 return (1, 2)
222 $$ LANGUAGE plpython3u;
223
224 SELECT * FROM multiout_simple();
225
226    Output parameters of procedures are passed back the same way. For
227    example:
228 CREATE PROCEDURE python_triple(INOUT a integer, INOUT b integer) AS $$
229 return (a * 3, b * 3)
230 $$ LANGUAGE plpython3u;
231
232 CALL python_triple(5, 10);
233
234 44.2.5. Set-Returning Functions #
235
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
239    have composite type:
240 CREATE TYPE greeting AS (
241   how text,
242   who text
243 );
244
245    A set result can be returned from a:
246
247    Sequence type (tuple, list, set)
248
249 CREATE FUNCTION greet (how text)
250   RETURNS SETOF greeting
251 AS $$
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;
256
257    Iterator (any object providing __iter__ and __next__ methods)
258
259 CREATE FUNCTION greet (how text)
260   RETURNS SETOF greeting
261 AS $$
262   class producer:
263     def __init__ (self, how, who):
264       self.how = how
265       self.who = who
266       self.ndx = -1
267
268     def __iter__ (self):
269       return self
270
271     def __next__(self):
272       self.ndx += 1
273       if self.ndx == len(self.who):
274         raise StopIteration
275       return ( self.how, self.who[self.ndx] )
276
277   return producer(how, [ "World", "PostgreSQL", "PL/Python" ])
278 $$ LANGUAGE plpython3u;
279
280    Generator (yield)
281
282 CREATE FUNCTION greet (how text)
283   RETURNS SETOF greeting
284 AS $$
285   for who in [ "World", "PostgreSQL", "PL/Python" ]:
286     yield ( how, who )
287 $$ LANGUAGE plpython3u;
288
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 $$
293 return [(1, 2)] * n
294 $$ LANGUAGE plpython3u;
295
296 SELECT * FROM multiout_simple_setof(3);