]> granicus.if.org Git - postgresql/blob - doc/src/sgml/plpython.sgml
Rename plpython to plpythonu, and update documentation to reflect its
[postgresql] / doc / src / sgml / plpython.sgml
1 <!-- $Header: /cvsroot/pgsql/doc/src/sgml/plpython.sgml,v 1.17 2003/06/30 18:31:41 tgl Exp $ -->
2
3 <chapter id="plpython">
4  <title>PL/Python - Python Procedural Language</title>
5
6  <indexterm zone="plpython"><primary>PL/Python</></>
7  <indexterm zone="plpython"><primary>Python</></>
8
9  <para>
10   The <application>PL/Python</application> procedural language allows
11   <productname>PostgreSQL</productname> functions to be written in the
12   <ulink url="http://www.python.org">Python</ulink> language.
13  </para>
14
15  <para>
16   To install PL/Python in a particular database, use
17   <literal>createlang plpythonu <replaceable>dbname</></literal>.
18  </para>
19
20  <note>
21   <para>
22    As of <productname>PostgreSQL</productname> 7.4,
23    PL/Python is only available as an <quote>untrusted</> language
24    (meaning it does not offer any way of restricting what users
25    can do in it).  It has therefore been renamed to <literal>plpythonu</>.
26    The trusted variant <literal>plpython</> may become available again in
27    future, if a new secure execution mechanism is developed by the Python
28    community.
29   </para>
30  </note>
31
32   <tip>
33    <para>
34     If a language is installed into <literal>template1</>, all subsequently
35     created databases will have the language installed automatically.
36    </para>
37   </tip>
38
39  <note>
40   <para>
41    Users of source packages must specially enable the build of
42    PL/Python during the installation process.  (Refer to the
43    installation instructions for more information.)  Users of binary
44    packages might find PL/Python in a separate subpackage.
45   </para>
46  </note>
47
48  <sect1 id="plpython-funcs">
49   <title>PL/Python Functions</title>
50
51   <para>
52    The Python code you write gets transformed into a Python function.  E.g.,
53 <programlisting>
54 CREATE FUNCTION myfunc(text) RETURNS text
55     AS 'return args[0]'
56     LANGUAGE plpythonu;
57 </programlisting>
58
59    gets transformed into
60
61 <programlisting>
62 def __plpython_procedure_myfunc_23456():
63         return args[0]
64 </programlisting>
65
66    where 23456 is the OID of the function.
67   </para>
68
69   <para>
70    If you do not provide a return value, Python returns the default
71    <symbol>None</symbol>. The
72    language module translates Python's <symbol>None</symbol> into the
73    SQL null value.
74   </para>
75
76   <para>
77    The <productname>PostgreSQL</> function parameters are available in
78    the global <varname>args</varname> list.  In the
79    <function>myfunc</function> example, <varname>args[0]</> contains
80    whatever was passed in as the text argument.  For
81    <literal>myfunc2(text, integer)</literal>, <varname>args[0]</>
82    would contain the <type>text</type> argument and
83    <varname>args[1]</varname> the <type>integer</type> argument.
84   </para>
85
86   <para>
87    The global dictionary <varname>SD</varname> is available to store
88    data between function calls.  This variable is private static data.
89    The global dictionary <varname>GD</varname> is public data,
90    available to all Python functions within a session.  Use with care.
91   </para>
92
93 <!-- NOT CORRECT ANYMORE, IS IT?
94
95   <para>
96    Each function gets its own restricted execution object in the
97    Python interpreter, so that global data and function arguments from
98    <function>myfunc</function> are not available to
99    <function>myfunc2</function>.  The exception is the data in the
100    <varname>GD</varname> dictionary, as mentioned above.
101   </para>
102
103 -->
104
105  </sect1>
106
107  <sect1 id="plpython-trigger">
108   <title>Trigger Functions</title>
109
110   <para>
111    When a function is used in a trigger, the dictionary
112    <literal>TD</literal> contains trigger-related values.  The trigger
113    rows are in <literal>TD["new"]</> and/or <literal>TD["old"]</>
114    depending on the trigger event.  <literal>TD["event"]</> contains
115    the event as a string (<literal>INSERT</>, <literal>UPDATE</>,
116    <literal>DELETE</>, or <literal>UNKNOWN</>).
117    <literal>TD["when"]</> contains one of <literal>BEFORE</>,
118    <literal>AFTER</>, and <literal>UNKNOWN</>.
119    <literal>TD["level"]</> contains one of <literal>ROW</>,
120    <literal>STATEMENT</>, and <literal>UNKNOWN</>.
121    <literal>TD["name"]</> contains the trigger name, and
122    <literal>TD["relid"]</> contains the OID of the table on
123    which the trigger occurred.  If the trigger was called with
124    arguments they are available in <literal>TD["args"][0]</> to
125    <literal>TD["args"][(n-1)]</>.
126   </para>
127
128   <para>
129    If <literal>TD["when"]</literal> is <literal>BEFORE</>, you may
130    return <literal>None</literal> or <literal>"OK"</literal> from the
131    Python function to indicate the row is unmodified,
132    <literal>"SKIP"</> to abort the event, or <literal>"MODIFY"</> to
133    indicate you've modified the row.
134   </para>
135  </sect1>
136
137  <sect1 id="plpython-database">
138   <title>Database Access</title>
139
140   <para>
141    The PL/Python language module automatically imports a Python module
142    called <literal>plpy</literal>.  The functions and constants in
143    this module are available to you in the Python code as
144    <literal>plpy.<replaceable>foo</replaceable></literal>.  At present
145    <literal>plpy</literal> implements the functions
146    <literal>plpy.debug("msg")</literal>,
147    <literal>plpy.log("msg")</literal>,
148    <literal>plpy.info("msg")</literal>,
149    <literal>plpy.notice("msg")</literal>,
150    <literal>plpy.warning("msg")</literal>,
151    <literal>plpy.error("msg")</literal>, and
152    <literal>plpy.fatal("msg")</literal>.  They are mostly equivalent
153    to calling <literal>elog(<replaceable>LEVEL</>, "msg")</literal>
154    from C code.  <function>plpy.error</function> and
155    <function>plpy.fatal</function> actually raise a Python exception
156    which, if uncaught, causes the PL/Python module to call
157    <literal>elog(ERROR, msg)</literal> when the function handler
158    returns from the Python interpreter.  Long-jumping out of the
159    Python interpreter is probably not good.  <literal>raise
160    plpy.ERROR("msg")</literal> and <literal>raise
161    plpy.FATAL("msg")</literal> are equivalent to calling
162    <function>plpy.error</function> and
163    <function>plpy.fatal</function>, respectively.
164   </para>
165
166   <para>
167    Additionally, the <literal>plpy</literal> module provides two
168    functions called <function>execute</function> and
169    <function>prepare</function>.  Calling
170    <function>plpy.execute</function> with a query string and an
171    optional limit argument causes that query to be run and the result
172    to be returned in a result object.  The result object emulates a
173    list or dictionary object.  The result object can be accessed by
174    row number and column name.  It has these additional methods:
175    <function>nrows</function> which returns the number of rows
176    returned by the query, and <function>status</function> which is the
177    <function>SPI_exec()</function> return value.  The result object
178    can be modified.
179   </para>
180
181   <para>
182    For example,
183 <programlisting>
184 rv = plpy.execute("SELECT * FROM my_table", 5)
185 </programlisting>
186    returns up to 5 rows from <literal>my_table</literal>.  If
187    <literal>my_table</literal> has a column
188    <literal>my_column</literal>, it would be accessed as
189 <programlisting>
190 foo = rv[i]["my_column"]
191 </programlisting>
192   </para>
193
194   <para>
195    The second function, <function>plpy.prepare</function>, prepares the
196    execution plan for a query.  It is called with a query string and a
197    list of parameter types, if you have parameter references in the
198    query.  For example:
199 <programlisting>
200 plan = plpy.prepare("SELECT last_name FROM my_users WHERE first_name = $1", [ "text" ])
201 </programlisting>
202    <literal>text</literal> is the type of the variable you will be
203    passing for <literal>$1</literal>.  After preparing a statement, you
204    use the function <function>plpy.execute</function> to run it:
205 <programlisting>
206 rv = plpy.execute(plan, [ "name" ], 5)
207 </programlisting>
208    The third argument is the limit and is optional.
209   </para>
210
211   <para>
212    In the current version, any database error encountered while
213    running a <application>PL/Python</application> function will result
214    in the immediate termination of that function by the server; it is
215    not possible to trap error conditions using Python <literal>try
216    ... catch</literal> constructs.  For example, a syntax error in an
217    SQL statement passed to the <literal>plpy.execute</literal> call
218    will terminate the function.  This behavior may be changed in a
219    future release.
220   </para>
221
222   <para>
223    When you prepare a plan using the PL/Python module it is
224    automatically saved.  Read the SPI documentation (<xref
225    linkend="spi">) for a description of what this means.
226    In order to make effective use of this across function calls
227    one needs to use one of the persistent storage dictionaries
228    <literal>SD</literal> or <literal>GD</literal> (see
229    <xref linkend="plpython-funcs">). For example:
230 <programlisting>
231 CREATE FUNCTION usesavedplan() RETURNS trigger AS '
232     if SD.has_key("plan"):
233         plan = SD["plan"]
234     else:
235         plan = plpy.prepare("SELECT 1")
236         SD["plan"] = plan
237     # rest of function
238 ' LANGUAGE plpythonu;
239 </programlisting>
240   </para>
241  </sect1>
242
243 <!-- NOT CURRENTLY SUPPORTED 
244
245  <sect1 id="plpython-trusted">
246   <title>Restricted Environment</title>
247
248   <para>
249    The current version of <application>PL/Python</application>
250    functions as a trusted language only; access to the file system and
251    other local resources is disabled.  Specifically,
252    <application>PL/Python</application> uses the Python restricted
253    execution environment, further restricts it to prevent the use of
254    the file <function>open</> call, and allows only modules from a
255    specific list to be imported.  Presently, that list includes:
256    <literal>array</>, <literal>bisect</>, <literal>binascii</>,
257    <literal>calendar</>, <literal>cmath</>, <literal>codecs</>,
258    <literal>errno</>, <literal>marshal</>, <literal>math</>, <literal>md5</>,
259    <literal>mpz</>, <literal>operator</>, <literal>pcre</>,
260    <literal>pickle</>, <literal>random</>, <literal>re</>, <literal>regex</>,
261    <literal>sre</>, <literal>sha</>, <literal>string</>, <literal>StringIO</>,
262    <literal>struct</>, <literal>time</>, <literal>whrandom</>, and
263    <literal>zlib</>.
264   </para>
265  </sect1>
266
267 -->
268
269 </chapter>