]> granicus.if.org Git - postgresql/blob - doc/src/sgml/plpython.sgml
Fix busted markup.
[postgresql] / doc / src / sgml / plpython.sgml
1 <!-- $Header: /cvsroot/pgsql/doc/src/sgml/plpython.sgml,v 1.13 2002/09/22 18:47:24 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 plpython <replaceable>dbname</></literal>.
18  </para>
19
20  <note>
21   <para>
22    Users of source packages must specially enable the build of
23    PL/Python during the installation process (refer to the
24    installation instructions for more information).  Users of binary
25    packages might find PL/Python in a separate subpackage.
26   </para>
27  </note>
28
29  <sect1 id="plpython-funcs">
30   <title>PL/Python Functions</title>
31
32   <para>
33    The Python code you write gets transformed into a function.  E.g.,
34 <programlisting>
35 CREATE FUNCTION myfunc(text) RETURNS text
36     AS 'return args[0]'
37     LANGUAGE 'plpython';
38 </programlisting>
39
40    gets transformed into
41
42 <programlisting>
43 def __plpython_procedure_myfunc_23456():
44         return args[0]
45 </programlisting>
46
47    where 23456 is the OID of the function.
48   </para>
49
50   <para>
51    If you do not provide a return value, Python returns the default
52    <symbol>None</symbol> which may or may not be what you want.  The
53    language module translates Python's <symbol>None</symbol> into the
54    SQL null value.
55   </para>
56
57   <para>
58    The <productname>PostgreSQL</> function parameters are available in
59    the global <varname>args</varname> list.  In the
60    <function>myfunc</function> example, <varname>args[0]</> contains
61    whatever was passed in as the text argument.  For
62    <literal>myfunc2(text, integer)</literal>, <varname>args[0]</>
63    would contain the <type>text</type> variable and
64    <varname>args[1]</varname> the <type>integer</type> variable.
65   </para>
66
67   <para>
68    The global dictionary <varname>SD</varname> is available to store
69    data between function calls.  This variable is private static data.
70    The global dictionary <varname>GD</varname> is public data,
71    available to all Python functions within a session.  Use with care.
72   </para>
73
74   <para>
75    Each function gets its own restricted execution object in the
76    Python interpreter, so that global data and function arguments from
77    <function>myfunc</function> are not available to
78    <function>myfunc2</function>.  The exception is the data in the
79    <varname>GD</varname> dictionary, as mentioned above.
80   </para>
81  </sect1>
82
83  <sect1 id="plpython-trigger">
84   <title>Trigger Functions</title>
85
86   <para>
87    When a function is used in a trigger, the dictionary
88    <literal>TD</literal> contains trigger-related values.  The trigger
89    rows are in <literal>TD["new"]</> and/or <literal>TD["old"]</>
90    depending on the trigger event.  <literal>TD["event"]</> contains
91    the event as a string (<literal>INSERT</>, <literal>UPDATE</>,
92    <literal>DELETE</>, or <literal>UNKNOWN</>).
93    <literal>TD["when"]</> contains one of <literal>BEFORE</>,
94    <literal>AFTER</>, and <literal>UNKNOWN</>.
95    <literal>TD["level"]</> contains one of <literal>ROW</>,
96    <literal>STATEMENT</>, and <literal>UNKNOWN</>.
97    <literal>TD["name"]</> contains the trigger name, and
98    <literal>TD["relid"]</> contains the relation ID of the table on
99    which the trigger occurred.  If the trigger was called with
100    arguments they are available in <literal>TD["args"][0]</> to
101    <literal>TD["args"][(n-1)]</>.
102   </para>
103
104   <para>
105    If the <literal>TD["when"]</literal> is <literal>BEFORE</>, you may
106    return <literal>None</literal> or <literal>"OK"</literal> from the
107    Python function to indicate the row is unmodified,
108    <literal>"SKIP"</> to abort the event, or <literal>"MODIFIED"</> to
109    indicate you've modified the row.
110   </para>
111  </sect1>
112
113  <sect1 id="plpython-database">
114   <title>Database Access</title>
115
116   <para>
117    The PL/Python language module automatically imports a Python module
118    called <literal>plpy</literal>.  The functions and constants in
119    this module are available to you in the Python code as
120    <literal>plpy.<replaceable>foo</replaceable></literal>.  At present
121    <literal>plpy</literal> implements the functions
122    <literal>plpy.debug("msg")</literal>,
123    <literal>plpy.log("msg")</literal>,
124    <literal>plpy.info("msg")</literal>,
125    <literal>plpy.notice("msg")</literal>,
126    <literal>plpy.warning("msg")</literal>,
127    <literal>plpy.error("msg")</literal>, and
128    <literal>plpy.fatal("msg")</literal>.  They are mostly equivalent
129    to calling <literal>elog(<replaceable>LEVEL</>, "msg")</literal>
130    from C code.  <function>plpy.error</function> and
131    <function>plpy.fatal</function> actually raise a Python exception
132    which, if uncaught, causes the PL/Python module to call
133    <literal>elog(ERROR, msg)</literal> when the function handler
134    returns from the Python interpreter.  Long-jumping out of the
135    Python interpreter is probably not good.  <literal>raise
136    plpy.ERROR("msg")</literal> and <literal>raise
137    plpy.FATAL("msg")</literal> are equivalent to calling
138    <function>plpy.error</function> and
139    <function>plpy.fatal</function>, respectively.
140   </para>
141
142   <para>
143    Additionally, the <literal>plpy</literal> module provides two
144    functions called <function>execute</function> and
145    <function>prepare</function>.  Calling
146    <function>plpy.execute</function> with a query string and an
147    optional limit argument causes that query to be run and the result
148    to be returned in a result object.  The result object emulates a
149    list or dictionary object.  The result object can be accessed by
150    row number and field name.  It has these additional methods:
151    <function>nrows()</function> which returns the number of rows
152    returned by the query, and <function>status</function> which is the
153    <function>SPI_exec</function> return variable.  The result object
154    can be modified.
155   </para>
156
157   <para>
158    For example,
159 <programlisting>
160 rv = plpy.execute("SELECT * FROM my_table", 5)
161 </programlisting>
162    returns up to 5 rows from <literal>my_table</literal>.  If
163    <literal>my_table</literal> has a column
164    <literal>my_field</literal>, it would be accessed as
165 <programlisting>
166 foo = rv[i]["my_field"]
167 </programlisting>
168   </para>
169
170   <para>
171    The second function <function>plpy.prepare</function> is called
172    with a query string and a list of argument types if you have bind
173    variables in the query.  For example:
174 <programlisting>
175 plan = plpy.prepare("SELECT last_name FROM my_users WHERE first_name = $1", [ "text" ])
176 </programlisting>
177    <literal>text</literal> is the type of the variable you will be
178    passing as <literal>$1</literal>.  After preparing a statement, you
179    use the function <function>plpy.execute</function> to run it:
180 <programlisting>
181 rv = plpy.execute(plan, [ "name" ], 5)
182 </programlisting>
183    The limit argument is optional in the call to
184    <function>plpy.execute</function>.
185   </para>
186
187   <para>
188    In the current version, any database error encountered while
189    running a <application>PL/Python</application> function will result
190    in the immediate termination of that function by the server; it is
191    not possible to trap error conditions using Python <literal>try
192    ... catch</literal> constructs.  For example, a syntax error in an
193    SQL statement passed to the <literal>plpy.execute()</literal> call
194    will terminate the function.  This behavior may be changed in a
195    future release.
196   </para>
197
198   <para>
199    When you prepare a plan using the PL/Python module it is
200    automatically saved.  Read the SPI documentation (<xref
201    linkend="spi">) for a description of what this means.  The take
202    home message is if you do
203 <programlisting>
204 plan = plpy.prepare("SOME QUERY")
205 plan = plpy.prepare("SOME OTHER QUERY")
206 </programlisting>
207    you are leaking memory, as I know of no way to free a saved plan.
208    The alternative of using unsaved plans it even more painful (for
209    me).
210   </para>
211  </sect1>
212
213  <sect1 id="plpython-trusted">
214   <title>Restricted Environment</title>
215
216   <para>
217    The current version of <application>PL/Python</application>
218    functions as a trusted language only; access to the file system and
219    other local resources is disabled.  Specifically,
220    <application>PL/Python</application> uses the Python restricted
221    execution environment, further restricts it to prevent the use of
222    the file <function>open</> call, and allows only modules from a
223    specific list to be imported.  Presently, that list includes:
224    <literal>array</>, <literal>bisect</>, <literal>binascii</>,
225    <literal>calendar</>, <literal>cmath</>, <literal>codecs</>,
226    <literal>errno</>, <literal>marshal</>, <literal>math</>, <literal>md5</>,
227    <literal>mpz</>, <literal>operator</>, <literal>pcre</>,
228    <literal>pickle</>, <literal>random</>, <literal>re</>, <literal>regex</>,
229    <literal>sre</>, <literal>sha</>, <literal>string</>, <literal>StringIO</>,
230    <literal>struct</>, <literal>time</>, <literal>whrandom</>, and
231    <literal>zlib</>.
232   </para>
233  </sect1>
234
235 </chapter>