1 <!-- $Header: /cvsroot/pgsql/doc/src/sgml/plpython.sgml,v 1.17 2003/06/30 18:31:41 tgl Exp $ -->
3 <chapter id="plpython">
4 <title>PL/Python - Python Procedural Language</title>
6 <indexterm zone="plpython"><primary>PL/Python</></>
7 <indexterm zone="plpython"><primary>Python</></>
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.
16 To install PL/Python in a particular database, use
17 <literal>createlang plpythonu <replaceable>dbname</></literal>.
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
34 If a language is installed into <literal>template1</>, all subsequently
35 created databases will have the language installed automatically.
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.
48 <sect1 id="plpython-funcs">
49 <title>PL/Python Functions</title>
52 The Python code you write gets transformed into a Python function. E.g.,
54 CREATE FUNCTION myfunc(text) RETURNS text
62 def __plpython_procedure_myfunc_23456():
66 where 23456 is the OID of the function.
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
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.
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.
93 <!-- NOT CORRECT ANYMORE, IS IT?
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.
107 <sect1 id="plpython-trigger">
108 <title>Trigger Functions</title>
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)]</>.
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.
137 <sect1 id="plpython-database">
138 <title>Database Access</title>
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.
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
184 rv = plpy.execute("SELECT * FROM my_table", 5)
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
190 foo = rv[i]["my_column"]
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
200 plan = plpy.prepare("SELECT last_name FROM my_users WHERE first_name = $1", [ "text" ])
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:
206 rv = plpy.execute(plan, [ "name" ], 5)
208 The third argument is the limit and is optional.
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
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:
231 CREATE FUNCTION usesavedplan() RETURNS trigger AS '
232 if SD.has_key("plan"):
235 plan = plpy.prepare("SELECT 1")
238 ' LANGUAGE plpythonu;
243 <!-- NOT CURRENTLY SUPPORTED
245 <sect1 id="plpython-trusted">
246 <title>Restricted Environment</title>
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