gooderp18绿色标准版
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

356 行
17KB

  1. <?xml version="1.0" encoding="UTF-8" standalone="no"?>
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><title>45.3. Data Values</title><link rel="stylesheet" type="text/css" href="stylesheet.css" /><link rev="made" href="pgsql-docs@lists.postgresql.org" /><meta name="generator" content="DocBook XSL Stylesheets V1.79.1" /><link rel="prev" href="plpython-funcs.html" title="45.2. PL/Python Functions" /><link rel="next" href="plpython-sharing.html" title="45.4. Sharing Data" /></head><body><div xmlns="http://www.w3.org/TR/xhtml1/transitional" class="navheader"><table width="100%" summary="Navigation header"><tr><th colspan="5" align="center">45.3. Data Values</th></tr><tr><td width="10%" align="left"><a accesskey="p" href="plpython-funcs.html" title="45.2. PL/Python Functions">Prev</a> </td><td width="10%" align="left"><a accesskey="u" href="plpython.html" title="Chapter 45. PL/Python - Python Procedural Language">Up</a></td><th width="60%" align="center">Chapter 45. PL/Python - Python Procedural Language</th><td width="10%" align="right"><a accesskey="h" href="index.html" title="PostgreSQL 12.4 Documentation">Home</a></td><td width="10%" align="right"> <a accesskey="n" href="plpython-sharing.html" title="45.4. Sharing Data">Next</a></td></tr></table><hr></hr></div><div class="sect1" id="PLPYTHON-DATA"><div class="titlepage"><div><div><h2 class="title" style="clear: both">45.3. Data Values</h2></div></div></div><div class="toc"><dl class="toc"><dt><span class="sect2"><a href="plpython-data.html#id-1.8.11.11.3">45.3.1. Data Type Mapping</a></span></dt><dt><span class="sect2"><a href="plpython-data.html#id-1.8.11.11.4">45.3.2. Null, None</a></span></dt><dt><span class="sect2"><a href="plpython-data.html#PLPYTHON-ARRAYS">45.3.3. Arrays, Lists</a></span></dt><dt><span class="sect2"><a href="plpython-data.html#id-1.8.11.11.6">45.3.4. Composite Types</a></span></dt><dt><span class="sect2"><a href="plpython-data.html#id-1.8.11.11.7">45.3.5. Set-Returning Functions</a></span></dt></dl></div><p>
  3. Generally speaking, the aim of PL/Python is to provide
  4. a <span class="quote">“<span class="quote">natural</span>”</span> mapping between the PostgreSQL and the
  5. Python worlds. This informs the data mapping rules described
  6. below.
  7. </p><div class="sect2" id="id-1.8.11.11.3"><div class="titlepage"><div><div><h3 class="title">45.3.1. Data Type Mapping</h3></div></div></div><p>
  8. When a PL/Python function is called, its arguments are converted from
  9. their PostgreSQL data type to a corresponding Python type:
  10. </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
  11. PostgreSQL <code class="type">boolean</code> is converted to Python <code class="type">bool</code>.
  12. </p></li><li class="listitem"><p>
  13. PostgreSQL <code class="type">smallint</code> and <code class="type">int</code> are
  14. converted to Python <code class="type">int</code>.
  15. PostgreSQL <code class="type">bigint</code> and <code class="type">oid</code> are converted
  16. to <code class="type">long</code> in Python 2 and to <code class="type">int</code> in
  17. Python 3.
  18. </p></li><li class="listitem"><p>
  19. PostgreSQL <code class="type">real</code> and <code class="type">double</code> are converted to
  20. Python <code class="type">float</code>.
  21. </p></li><li class="listitem"><p>
  22. PostgreSQL <code class="type">numeric</code> is converted to
  23. Python <code class="type">Decimal</code>. This type is imported from
  24. the <code class="literal">cdecimal</code> package if that is available.
  25. Otherwise,
  26. <code class="literal">decimal.Decimal</code> from the standard library will be
  27. used. <code class="literal">cdecimal</code> is significantly faster
  28. than <code class="literal">decimal</code>. In Python 3.3 and up,
  29. however, <code class="literal">cdecimal</code> has been integrated into the
  30. standard library under the name <code class="literal">decimal</code>, so there is
  31. no longer any difference.
  32. </p></li><li class="listitem"><p>
  33. PostgreSQL <code class="type">bytea</code> is converted to
  34. Python <code class="type">str</code> in Python 2 and to <code class="type">bytes</code>
  35. in Python 3. In Python 2, the string should be treated as a
  36. byte sequence without any character encoding.
  37. </p></li><li class="listitem"><p>
  38. All other data types, including the PostgreSQL character string
  39. types, are converted to a Python <code class="type">str</code>. In Python
  40. 2, this string will be in the PostgreSQL server encoding; in
  41. Python 3, it will be a Unicode string like all strings.
  42. </p></li><li class="listitem"><p>
  43. For nonscalar data types, see below.
  44. </p></li></ul></div><p>
  45. </p><p>
  46. When a PL/Python function returns, its return value is converted to the
  47. function's declared PostgreSQL return data type as follows:
  48. </p><div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem"><p>
  49. When the PostgreSQL return type is <code class="type">boolean</code>, the
  50. return value will be evaluated for truth according to the
  51. <span class="emphasis"><em>Python</em></span> rules. That is, 0 and empty string
  52. are false, but notably <code class="literal">'f'</code> is true.
  53. </p></li><li class="listitem"><p>
  54. When the PostgreSQL return type is <code class="type">bytea</code>, the
  55. return value will be converted to a string (Python 2) or bytes
  56. (Python 3) using the respective Python built-ins, with the
  57. result being converted to <code class="type">bytea</code>.
  58. </p></li><li class="listitem"><p>
  59. For all other PostgreSQL return types, the return value is converted
  60. to a string using the Python built-in <code class="literal">str</code>, and the
  61. result is passed to the input function of the PostgreSQL data type.
  62. (If the Python value is a <code class="type">float</code>, it is converted using
  63. the <code class="literal">repr</code> built-in instead of <code class="literal">str</code>, to
  64. avoid loss of precision.)
  65. </p><p>
  66. Strings in Python 2 are required to be in the PostgreSQL server
  67. encoding when they are passed to PostgreSQL. Strings that are
  68. not valid in the current server encoding will raise an error,
  69. but not all encoding mismatches can be detected, so garbage
  70. data can still result when this is not done correctly. Unicode
  71. strings are converted to the correct encoding automatically, so
  72. it can be safer and more convenient to use those. In Python 3,
  73. all strings are Unicode strings.
  74. </p></li><li class="listitem"><p>
  75. For nonscalar data types, see below.
  76. </p></li></ul></div><p>
  77. Note that logical mismatches between the declared PostgreSQL
  78. return type and the Python data type of the actual return object
  79. are not flagged; the value will be converted in any case.
  80. </p></div><div class="sect2" id="id-1.8.11.11.4"><div class="titlepage"><div><div><h3 class="title">45.3.2. Null, None</h3></div></div></div><p>
  81. If an SQL null value<a id="id-1.8.11.11.4.2.1" class="indexterm"></a> is passed to a
  82. function, the argument value will appear as <code class="symbol">None</code> in
  83. Python. For example, the function definition of <code class="function">pymax</code>
  84. shown in <a class="xref" href="plpython-funcs.html" title="45.2. PL/Python Functions">Section 45.2</a> will return the wrong answer for null
  85. inputs. We could add <code class="literal">STRICT</code> to the function definition
  86. to make <span class="productname">PostgreSQL</span> do something more reasonable:
  87. if a null value is passed, the function will not be called at all,
  88. but will just return a null result automatically. Alternatively,
  89. we could check for null inputs in the function body:
  90. </p><pre class="programlisting">
  91. CREATE FUNCTION pymax (a integer, b integer)
  92. RETURNS integer
  93. AS $$
  94. if (a is None) or (b is None):
  95. return None
  96. if a &gt; b:
  97. return a
  98. return b
  99. $$ LANGUAGE plpythonu;
  100. </pre><p>
  101. As shown above, to return an SQL null value from a PL/Python
  102. function, return the value <code class="symbol">None</code>. This can be done whether the
  103. function is strict or not.
  104. </p></div><div class="sect2" id="PLPYTHON-ARRAYS"><div class="titlepage"><div><div><h3 class="title">45.3.3. Arrays, Lists</h3></div></div></div><p>
  105. SQL array values are passed into PL/Python as a Python list. To
  106. return an SQL array value out of a PL/Python function, return a
  107. Python list:
  108. </p><pre class="programlisting">
  109. CREATE FUNCTION return_arr()
  110. RETURNS int[]
  111. AS $$
  112. return [1, 2, 3, 4, 5]
  113. $$ LANGUAGE plpythonu;
  114. SELECT return_arr();
  115. return_arr
  116. -------------
  117. {1,2,3,4,5}
  118. (1 row)
  119. </pre><p>
  120. Multidimensional arrays are passed into PL/Python as nested Python lists.
  121. A 2-dimensional array is a list of lists, for example. When returning
  122. a multi-dimensional SQL array out of a PL/Python function, the inner
  123. lists at each level must all be of the same size. For example:
  124. </p><pre class="programlisting">
  125. CREATE FUNCTION test_type_conversion_array_int4(x int4[]) RETURNS int4[] AS $$
  126. plpy.info(x, type(x))
  127. return x
  128. $$ LANGUAGE plpythonu;
  129. SELECT * FROM test_type_conversion_array_int4(ARRAY[[1,2,3],[4,5,6]]);
  130. INFO: ([[1, 2, 3], [4, 5, 6]], &lt;type 'list'&gt;)
  131. test_type_conversion_array_int4
  132. ---------------------------------
  133. {{1,2,3},{4,5,6}}
  134. (1 row)
  135. </pre><p>
  136. Other Python sequences, like tuples, are also accepted for
  137. backwards-compatibility with PostgreSQL versions 9.6 and below, when
  138. multi-dimensional arrays were not supported. However, they are always
  139. treated as one-dimensional arrays, because they are ambiguous with
  140. composite types. For the same reason, when a composite type is used in a
  141. multi-dimensional array, it must be represented by a tuple, rather than a
  142. list.
  143. </p><p>
  144. Note that in Python, strings are sequences, which can have
  145. undesirable effects that might be familiar to Python programmers:
  146. </p><pre class="programlisting">
  147. CREATE FUNCTION return_str_arr()
  148. RETURNS varchar[]
  149. AS $$
  150. return "hello"
  151. $$ LANGUAGE plpythonu;
  152. SELECT return_str_arr();
  153. return_str_arr
  154. ----------------
  155. {h,e,l,l,o}
  156. (1 row)
  157. </pre><p>
  158. </p></div><div class="sect2" id="id-1.8.11.11.6"><div class="titlepage"><div><div><h3 class="title">45.3.4. Composite Types</h3></div></div></div><p>
  159. Composite-type arguments are passed to the function as Python mappings. The
  160. element names of the mapping are the attribute names of the composite type.
  161. If an attribute in the passed row has the null value, it has the value
  162. <code class="symbol">None</code> in the mapping. Here is an example:
  163. </p><pre class="programlisting">
  164. CREATE TABLE employee (
  165. name text,
  166. salary integer,
  167. age integer
  168. );
  169. CREATE FUNCTION overpaid (e employee)
  170. RETURNS boolean
  171. AS $$
  172. if e["salary"] &gt; 200000:
  173. return True
  174. if (e["age"] &lt; 30) and (e["salary"] &gt; 100000):
  175. return True
  176. return False
  177. $$ LANGUAGE plpythonu;
  178. </pre><p>
  179. </p><p>
  180. There are multiple ways to return row or composite types from a Python
  181. function. The following examples assume we have:
  182. </p><pre class="programlisting">
  183. CREATE TYPE named_value AS (
  184. name text,
  185. value integer
  186. );
  187. </pre><p>
  188. A composite result can be returned as a:
  189. </p><div class="variablelist"><dl class="variablelist"><dt><span class="term">Sequence type (a tuple or list, but not a set because
  190. it is not indexable)</span></dt><dd><p>
  191. Returned sequence objects must have the same number of items as the
  192. composite result type has fields. The item with index 0 is assigned to
  193. the first field of the composite type, 1 to the second and so on. For
  194. example:
  195. </p><pre class="programlisting">
  196. CREATE FUNCTION make_pair (name text, value integer)
  197. RETURNS named_value
  198. AS $$
  199. return ( name, value )
  200. # or alternatively, as tuple: return [ name, value ]
  201. $$ LANGUAGE plpythonu;
  202. </pre><p>
  203. To return a SQL null for any column, insert <code class="symbol">None</code> at
  204. the corresponding position.
  205. </p><p>
  206. When an array of composite types is returned, it cannot be returned as a list,
  207. because it is ambiguous whether the Python list represents a composite type,
  208. or another array dimension.
  209. </p></dd><dt><span class="term">Mapping (dictionary)</span></dt><dd><p>
  210. The value for each result type column is retrieved from the mapping
  211. with the column name as key. Example:
  212. </p><pre class="programlisting">
  213. CREATE FUNCTION make_pair (name text, value integer)
  214. RETURNS named_value
  215. AS $$
  216. return { "name": name, "value": value }
  217. $$ LANGUAGE plpythonu;
  218. </pre><p>
  219. Any extra dictionary key/value pairs are ignored. Missing keys are
  220. treated as errors.
  221. To return a SQL null value for any column, insert
  222. <code class="symbol">None</code> with the corresponding column name as the key.
  223. </p></dd><dt><span class="term">Object (any object providing method <code class="literal">__getattr__</code>)</span></dt><dd><p>
  224. This works the same as a mapping.
  225. Example:
  226. </p><pre class="programlisting">
  227. CREATE FUNCTION make_pair (name text, value integer)
  228. RETURNS named_value
  229. AS $$
  230. class named_value:
  231. def __init__ (self, n, v):
  232. self.name = n
  233. self.value = v
  234. return named_value(name, value)
  235. # or simply
  236. class nv: pass
  237. nv.name = name
  238. nv.value = value
  239. return nv
  240. $$ LANGUAGE plpythonu;
  241. </pre><p>
  242. </p></dd></dl></div><p>
  243. </p><p>
  244. Functions with <code class="literal">OUT</code> parameters are also supported. For example:
  245. </p><pre class="programlisting">
  246. CREATE FUNCTION multiout_simple(OUT i integer, OUT j integer) AS $$
  247. return (1, 2)
  248. $$ LANGUAGE plpythonu;
  249. SELECT * FROM multiout_simple();
  250. </pre><p>
  251. </p><p>
  252. Output parameters of procedures are passed back the same way. For example:
  253. </p><pre class="programlisting">
  254. CREATE PROCEDURE python_triple(INOUT a integer, INOUT b integer) AS $$
  255. return (a * 3, b * 3)
  256. $$ LANGUAGE plpythonu;
  257. CALL python_triple(5, 10);
  258. </pre><p>
  259. </p></div><div class="sect2" id="id-1.8.11.11.7"><div class="titlepage"><div><div><h3 class="title">45.3.5. Set-Returning Functions</h3></div></div></div><p>
  260. A <span class="application">PL/Python</span> function can also return sets of
  261. scalar or composite types. There are several ways to achieve this because
  262. the returned object is internally turned into an iterator. The following
  263. examples assume we have composite type:
  264. </p><pre class="programlisting">
  265. CREATE TYPE greeting AS (
  266. how text,
  267. who text
  268. );
  269. </pre><p>
  270. A set result can be returned from a:
  271. </p><div class="variablelist"><dl class="variablelist"><dt><span class="term">Sequence type (tuple, list, set)</span></dt><dd><p>
  272. </p><pre class="programlisting">
  273. CREATE FUNCTION greet (how text)
  274. RETURNS SETOF greeting
  275. AS $$
  276. # return tuple containing lists as composite types
  277. # all other combinations work also
  278. return ( [ how, "World" ], [ how, "PostgreSQL" ], [ how, "PL/Python" ] )
  279. $$ LANGUAGE plpythonu;
  280. </pre><p>
  281. </p></dd><dt><span class="term">Iterator (any object providing <code class="symbol">__iter__</code> and
  282. <code class="symbol">next</code> methods)</span></dt><dd><p>
  283. </p><pre class="programlisting">
  284. CREATE FUNCTION greet (how text)
  285. RETURNS SETOF greeting
  286. AS $$
  287. class producer:
  288. def __init__ (self, how, who):
  289. self.how = how
  290. self.who = who
  291. self.ndx = -1
  292. def __iter__ (self):
  293. return self
  294. def next (self):
  295. self.ndx += 1
  296. if self.ndx == len(self.who):
  297. raise StopIteration
  298. return ( self.how, self.who[self.ndx] )
  299. return producer(how, [ "World", "PostgreSQL", "PL/Python" ])
  300. $$ LANGUAGE plpythonu;
  301. </pre><p>
  302. </p></dd><dt><span class="term">Generator (<code class="literal">yield</code>)</span></dt><dd><p>
  303. </p><pre class="programlisting">
  304. CREATE FUNCTION greet (how text)
  305. RETURNS SETOF greeting
  306. AS $$
  307. for who in [ "World", "PostgreSQL", "PL/Python" ]:
  308. yield ( how, who )
  309. $$ LANGUAGE plpythonu;
  310. </pre><p>
  311. </p></dd></dl></div><p>
  312. </p><p>
  313. Set-returning functions with <code class="literal">OUT</code> parameters
  314. (using <code class="literal">RETURNS SETOF record</code>) are also
  315. supported. For example:
  316. </p><pre class="programlisting">
  317. CREATE FUNCTION multiout_simple_setof(n integer, OUT integer, OUT integer) RETURNS SETOF record AS $$
  318. return [(1, 2)] * n
  319. $$ LANGUAGE plpythonu;
  320. SELECT * FROM multiout_simple_setof(3);
  321. </pre><p>
  322. </p></div></div><div class="navfooter"><hr /><table width="100%" summary="Navigation footer"><tr><td width="40%" align="left"><a accesskey="p" href="plpython-funcs.html">Prev</a> </td><td width="20%" align="center"><a accesskey="u" href="plpython.html">Up</a></td><td width="40%" align="right"> <a accesskey="n" href="plpython-sharing.html">Next</a></td></tr><tr><td width="40%" align="left" valign="top">45.2. PL/Python Functions </td><td width="20%" align="center"><a accesskey="h" href="index.html">Home</a></td><td width="40%" align="right" valign="top"> 45.4. Sharing Data</td></tr></table></div></body></html>
上海开阖软件有限公司 沪ICP备12045867号-1