]> granicus.if.org Git - postgresql/blob - doc/src/sgml/plpython.sgml
PL/Python: Clean up extended error reporting docs and tests
[postgresql] / doc / src / sgml / plpython.sgml
1 <!-- doc/src/sgml/plpython.sgml -->
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 language</ulink>.
13  </para>
14
15  <para>
16   To install PL/Python in a particular database, use
17   <literal>CREATE EXTENSION plpythonu</>, or from the shell command line use
18   <literal>createlang plpythonu <replaceable>dbname</></literal> (but
19   see also <xref linkend="plpython-python23">).
20  </para>
21
22   <tip>
23    <para>
24     If a language is installed into <literal>template1</>, all subsequently
25     created databases will have the language installed automatically.
26    </para>
27   </tip>
28
29  <para>
30   PL/Python is only available as an <quote>untrusted</> language, meaning
31   it does not offer any way of restricting what users can do in it and
32   is therefore named <literal>plpythonu</>.  A trusted
33   variant <literal>plpython</> might become available in the future
34   if a secure execution mechanism is developed in Python.  The
35   writer of a function in untrusted PL/Python must take care that the
36   function cannot be used to do anything unwanted, since it will be
37   able to do anything that could be done by a user logged in as the
38   database administrator.  Only superusers can create functions in
39   untrusted languages such as <literal>plpythonu</literal>.
40  </para>
41
42  <note>
43   <para>
44    Users of source packages must specially enable the build of
45    PL/Python during the installation process.  (Refer to the
46    installation instructions for more information.)  Users of binary
47    packages might find PL/Python in a separate subpackage.
48   </para>
49  </note>
50
51  <sect1 id="plpython-python23">
52   <title>Python 2 vs. Python 3</title>
53
54   <para>
55    PL/Python supports both the Python 2 and Python 3 language
56    variants.  (The PostgreSQL installation instructions might contain
57    more precise information about the exact supported minor versions
58    of Python.)  Because the Python 2 and Python 3 language variants
59    are incompatible in some important aspects, the following naming
60    and transitioning scheme is used by PL/Python to avoid mixing them:
61
62    <itemizedlist>
63     <listitem>
64      <para>
65       The PostgreSQL language named <literal>plpython2u</literal>
66       implements PL/Python based on the Python 2 language variant.
67      </para>
68     </listitem>
69
70     <listitem>
71      <para>
72       The PostgreSQL language named <literal>plpython3u</literal>
73       implements PL/Python based on the Python 3 language variant.
74      </para>
75     </listitem>
76
77     <listitem>
78      <para>
79       The language named <literal>plpythonu</literal> implements
80       PL/Python based on the default Python language variant, which is
81       currently Python 2.  (This default is independent of what any
82       local Python installations might consider to be
83       their <quote>default</quote>, for example,
84       what <filename>/usr/bin/python</filename> might be.)  The
85       default will probably be changed to Python 3 in a distant future
86       release of PostgreSQL, depending on the progress of the
87       migration to Python 3 in the Python community.
88      </para>
89     </listitem>
90    </itemizedlist>
91
92    This scheme is analogous to the recommendations in <ulink
93    url="http://www.python.org/dev/peps/pep-0394/">PEP 394</ulink> regarding the
94    naming and transitioning of the <command>python</command> command.
95   </para>
96
97   <para>
98    It depends on the build configuration or the installed packages
99    whether PL/Python for Python 2 or Python 3 or both are available.
100   </para>
101
102   <tip>
103    <para>
104     The built variant depends on which Python version was found during
105     the installation or which version was explicitly set using
106     the <envar>PYTHON</envar> environment variable;
107     see <xref linkend="install-procedure">.  To make both variants of
108     PL/Python available in one installation, the source tree has to be
109     configured and built twice.
110    </para>
111   </tip>
112
113   <para>
114    This results in the following usage and migration strategy:
115
116    <itemizedlist>
117     <listitem>
118      <para>
119       Existing users and users who are currently not interested in
120       Python 3 use the language name <literal>plpythonu</literal> and
121       don't have to change anything for the foreseeable future.  It is
122       recommended to gradually <quote>future-proof</quote> the code
123       via migration to Python 2.6/2.7 to simplify the eventual
124       migration to Python 3.
125      </para>
126
127      <para>
128       In practice, many PL/Python functions will migrate to Python 3
129       with few or no changes.
130      </para>
131     </listitem>
132
133     <listitem>
134      <para>
135       Users who know that they have heavily Python 2 dependent code
136       and don't plan to ever change it can make use of
137       the <literal>plpython2u</literal> language name.  This will
138       continue to work into the very distant future, until Python 2
139       support might be completely dropped by PostgreSQL.
140      </para>
141     </listitem>
142
143     <listitem>
144      <para>
145       Users who want to dive into Python 3 can use
146       the <literal>plpython3u</literal> language name, which will keep
147       working forever by today's standards.  In the distant future,
148       when Python 3 might become the default, they might like to
149       remove the <quote>3</quote> for aesthetic reasons.
150      </para>
151     </listitem>
152
153     <listitem>
154      <para>
155       Daredevils, who want to build a Python-3-only operating system
156       environment, can change the contents of
157       <link linkend="catalog-pg-pltemplate"><structname>pg_pltemplate</structname></link>
158       to make <literal>plpythonu</literal> be equivalent
159       to <literal>plpython3u</literal>, keeping in mind that this
160       would make their installation incompatible with most of the rest
161       of the world.
162      </para>
163     </listitem>
164    </itemizedlist>
165   </para>
166
167   <para>
168    See also the
169    document <ulink url="http://docs.python.org/py3k/whatsnew/3.0.html">What's
170    New In Python 3.0</ulink> for more information about porting to
171    Python 3.
172   </para>
173
174   <para>
175    It is not allowed to use PL/Python based on Python 2 and PL/Python
176    based on Python 3 in the same session, because the symbols in the
177    dynamic modules would clash, which could result in crashes of the
178    PostgreSQL server process.  There is a check that prevents mixing
179    Python major versions in a session, which will abort the session if
180    a mismatch is detected.  It is possible, however, to use both
181    PL/Python variants in the same database, from separate sessions.
182   </para>
183  </sect1>
184
185  <sect1 id="plpython-funcs">
186   <title>PL/Python Functions</title>
187
188   <para>
189    Functions in PL/Python are declared via the
190    standard <xref linkend="sql-createfunction"> syntax:
191
192 <programlisting>
193 CREATE FUNCTION <replaceable>funcname</replaceable> (<replaceable>argument-list</replaceable>)
194   RETURNS <replaceable>return-type</replaceable>
195 AS $$
196   # PL/Python function body
197 $$ LANGUAGE plpythonu;
198 </programlisting>
199   </para>
200
201   <para>
202    The body of a function is simply a Python script. When the function
203    is called, its arguments are passed as elements of the list
204    <varname>args</varname>; named arguments are also passed as
205    ordinary variables to the Python script.  Use of named arguments is
206    usually more readable.  The result is returned from the Python code
207    in the usual way, with <literal>return</literal> or
208    <literal>yield</literal> (in case of a result-set statement).  If
209    you do not provide a return value, Python returns the default
210    <symbol>None</symbol>. <application>PL/Python</application> translates
211    Python's <symbol>None</symbol> into the SQL null value.
212   </para>
213
214   <para>
215    For example, a function to return the greater of two integers can be
216    defined as:
217
218 <programlisting>
219 CREATE FUNCTION pymax (a integer, b integer)
220   RETURNS integer
221 AS $$
222   if a &gt; b:
223     return a
224   return b
225 $$ LANGUAGE plpythonu;
226 </programlisting>
227
228    The Python code that is given as the body of the function definition
229    is transformed into a Python function. For example, the above results in:
230
231 <programlisting>
232 def __plpython_procedure_pymax_23456():
233   if a &gt; b:
234     return a
235   return b
236 </programlisting>
237
238    assuming that 23456 is the OID assigned to the function by
239    <productname>PostgreSQL</productname>.
240   </para>
241
242   <para>
243    The arguments are set as global variables.  Because of the scoping
244    rules of Python, this has the subtle consequence that an argument
245    variable cannot be reassigned inside the function to the value of
246    an expression that involves the variable name itself, unless the
247    variable is redeclared as global in the block.  For example, the
248    following won't work:
249 <programlisting>
250 CREATE FUNCTION pystrip(x text)
251   RETURNS text
252 AS $$
253   x = x.strip()  # error
254   return x
255 $$ LANGUAGE plpythonu;
256 </programlisting>
257    because assigning to <varname>x</varname>
258    makes <varname>x</varname> a local variable for the entire block,
259    and so the <varname>x</varname> on the right-hand side of the
260    assignment refers to a not-yet-assigned local
261    variable <varname>x</varname>, not the PL/Python function
262    parameter.  Using the <literal>global</literal> statement, this can
263    be made to work:
264 <programlisting>
265 CREATE FUNCTION pystrip(x text)
266   RETURNS text
267 AS $$
268   global x
269   x = x.strip()  # ok now
270   return x
271 $$ LANGUAGE plpythonu;
272 </programlisting>
273    But it is advisable not to rely on this implementation detail of
274    PL/Python.  It is better to treat the function parameters as
275    read-only.
276   </para>
277  </sect1>
278
279  <sect1 id="plpython-data">
280   <title>Data Values</title>
281   <para>
282    Generally speaking, the aim of PL/Python is to provide
283    a <quote>natural</quote> mapping between the PostgreSQL and the
284    Python worlds.  This informs the data mapping rules described
285    below.
286   </para>
287
288   <sect2>
289    <title>Data Type Mapping</title>
290    <para>
291     When a PL/Python function is called, its arguments are converted from
292     their PostgreSQL data type to a corresponding Python type:
293
294     <itemizedlist>
295      <listitem>
296       <para>
297        PostgreSQL <type>boolean</type> is converted to Python <type>bool</type>.
298       </para>
299      </listitem>
300
301      <listitem>
302       <para>
303        PostgreSQL <type>smallint</type> and <type>int</type> are
304        converted to Python <type>int</type>.
305        PostgreSQL <type>bigint</type> and <type>oid</type> are converted
306        to <type>long</type> in Python 2 and to <type>int</type> in
307        Python 3.
308       </para>
309      </listitem>
310
311      <listitem>
312       <para>
313        PostgreSQL <type>real</type> and <type>double</type> are converted to
314        Python <type>float</type>.
315       </para>
316      </listitem>
317
318      <listitem>
319       <para>
320        PostgreSQL <type>numeric</type> is converted to
321        Python <type>Decimal</type>.  This type is imported from
322        the <literal>cdecimal</literal> package if that is available.
323        Otherwise,
324        <literal>decimal.Decimal</literal> from the standard library will be
325        used.  <literal>cdecimal</literal> is significantly faster
326        than <literal>decimal</literal>.  In Python 3.3 and up,
327        however, <literal>cdecimal</literal> has been integrated into the
328        standard library under the name <literal>decimal</literal>, so there is
329        no longer any difference.
330       </para>
331      </listitem>
332
333      <listitem>
334       <para>
335        PostgreSQL <type>bytea</type> is converted to
336        Python <type>str</type> in Python 2 and to <type>bytes</type>
337        in Python 3.  In Python 2, the string should be treated as a
338        byte sequence without any character encoding.
339       </para>
340      </listitem>
341
342      <listitem>
343       <para>
344        All other data types, including the PostgreSQL character string
345        types, are converted to a Python <type>str</type>.  In Python
346        2, this string will be in the PostgreSQL server encoding; in
347        Python 3, it will be a Unicode string like all strings.
348       </para>
349      </listitem>
350
351      <listitem>
352       <para>
353        For nonscalar data types, see below.
354       </para>
355      </listitem>
356     </itemizedlist>
357    </para>
358
359    <para>
360     When a PL/Python function returns, its return value is converted to the
361     function's declared PostgreSQL return data type as follows:
362
363     <itemizedlist>
364      <listitem>
365       <para>
366        When the PostgreSQL return type is <type>boolean</type>, the
367        return value will be evaluated for truth according to the
368        <emphasis>Python</emphasis> rules.  That is, 0 and empty string
369        are false, but notably <literal>'f'</literal> is true.
370       </para>
371      </listitem>
372
373      <listitem>
374       <para>
375        When the PostgreSQL return type is <type>bytea</type>, the
376        return value will be converted to a string (Python 2) or bytes
377        (Python 3) using the respective Python built-ins, with the
378        result being converted to <type>bytea</type>.
379       </para>
380      </listitem>
381
382      <listitem>
383       <para>
384        For all other PostgreSQL return types, the return value is converted
385        to a string using the Python built-in <literal>str</literal>, and the
386        result is passed to the input function of the PostgreSQL data type.
387        (If the Python value is a <type>float</>, it is converted using
388        the <literal>repr</> built-in instead of <literal>str</literal>, to
389        avoid loss of precision.)
390       </para>
391
392       <para>
393        Strings in Python 2 are required to be in the PostgreSQL server
394        encoding when they are passed to PostgreSQL.  Strings that are
395        not valid in the current server encoding will raise an error,
396        but not all encoding mismatches can be detected, so garbage
397        data can still result when this is not done correctly.  Unicode
398        strings are converted to the correct encoding automatically, so
399        it can be safer and more convenient to use those.  In Python 3,
400        all strings are Unicode strings.
401       </para>
402      </listitem>
403
404      <listitem>
405       <para>
406        For nonscalar data types, see below.
407       </para>
408      </listitem>
409     </itemizedlist>
410
411     Note that logical mismatches between the declared PostgreSQL
412     return type and the Python data type of the actual return object
413     are not flagged; the value will be converted in any case.
414    </para>
415   </sect2>
416
417   <sect2>
418    <title>Null, None</title>
419   <para>
420    If an SQL null value<indexterm><primary>null value</primary><secondary
421    sortas="PL/Python">in PL/Python</secondary></indexterm> is passed to a
422    function, the argument value will appear as <symbol>None</symbol> in
423    Python. For example, the function definition of <function>pymax</function>
424    shown in <xref linkend="plpython-funcs"> will return the wrong answer for null
425    inputs. We could add <literal>STRICT</literal> to the function definition
426    to make <productname>PostgreSQL</productname> do something more reasonable:
427    if a null value is passed, the function will not be called at all,
428    but will just return a null result automatically. Alternatively,
429    we could check for null inputs in the function body:
430
431 <programlisting>
432 CREATE FUNCTION pymax (a integer, b integer)
433   RETURNS integer
434 AS $$
435   if (a is None) or (b is None):
436     return None
437   if a &gt; b:
438     return a
439   return b
440 $$ LANGUAGE plpythonu;
441 </programlisting>
442
443    As shown above, to return an SQL null value from a PL/Python
444    function, return the value <symbol>None</symbol>. This can be done whether the
445    function is strict or not.
446   </para>
447   </sect2>
448
449   <sect2 id="plpython-arrays">
450    <title>Arrays, Lists</title>
451   <para>
452    SQL array values are passed into PL/Python as a Python list.  To
453    return an SQL array value out of a PL/Python function, return a
454    Python sequence, for example a list or tuple:
455
456 <programlisting>
457 CREATE FUNCTION return_arr()
458   RETURNS int[]
459 AS $$
460 return (1, 2, 3, 4, 5)
461 $$ LANGUAGE plpythonu;
462
463 SELECT return_arr();
464  return_arr  
465 -------------
466  {1,2,3,4,5}
467 (1 row)
468 </programlisting>
469
470    Note that in Python, strings are sequences, which can have
471    undesirable effects that might be familiar to Python programmers:
472
473 <programlisting>
474 CREATE FUNCTION return_str_arr()
475   RETURNS varchar[]
476 AS $$
477 return "hello"
478 $$ LANGUAGE plpythonu;
479
480 SELECT return_str_arr();
481  return_str_arr
482 ----------------
483  {h,e,l,l,o}
484 (1 row)
485 </programlisting>
486   </para>
487   </sect2>
488
489   <sect2>
490    <title>Composite Types</title>
491   <para>
492    Composite-type arguments are passed to the function as Python mappings. The
493    element names of the mapping are the attribute names of the composite type.
494    If an attribute in the passed row has the null value, it has the value
495    <symbol>None</symbol> in the mapping. Here is an example:
496
497 <programlisting>
498 CREATE TABLE employee (
499   name text,
500   salary integer,
501   age integer
502 );
503
504 CREATE FUNCTION overpaid (e employee)
505   RETURNS boolean
506 AS $$
507   if e["salary"] &gt; 200000:
508     return True
509   if (e["age"] &lt; 30) and (e["salary"] &gt; 100000):
510     return True
511   return False
512 $$ LANGUAGE plpythonu;
513 </programlisting>
514   </para>
515
516   <para>
517    There are multiple ways to return row or composite types from a Python
518    function. The following examples assume we have:
519
520 <programlisting>
521 CREATE TYPE named_value AS (
522   name   text,
523   value  integer
524 );
525 </programlisting>
526
527    A composite result can be returned as a:
528
529    <variablelist>
530     <varlistentry>
531      <term>Sequence type (a tuple or list, but not a set because
532      it is not indexable)</term>
533      <listitem>
534       <para>
535        Returned sequence objects must have the same number of items as the
536        composite result type has fields. The item with index 0 is assigned to
537        the first field of the composite type, 1 to the second and so on. For
538        example:
539
540 <programlisting>
541 CREATE FUNCTION make_pair (name text, value integer)
542   RETURNS named_value
543 AS $$
544   return [ name, value ]
545   # or alternatively, as tuple: return ( name, value )
546 $$ LANGUAGE plpythonu;
547 </programlisting>
548
549        To return a SQL null for any column, insert <symbol>None</symbol> at
550        the corresponding position.
551       </para>
552      </listitem>
553     </varlistentry>
554
555     <varlistentry>
556      <term>Mapping (dictionary)</term>
557      <listitem>
558       <para>
559        The value for each result type column is retrieved from the mapping
560        with the column name as key. Example:
561
562 <programlisting>
563 CREATE FUNCTION make_pair (name text, value integer)
564   RETURNS named_value
565 AS $$
566   return { "name": name, "value": value }
567 $$ LANGUAGE plpythonu;
568 </programlisting>
569
570        Any extra dictionary key/value pairs are ignored. Missing keys are
571        treated as errors.
572        To return a SQL null value for any column, insert
573        <symbol>None</symbol> with the corresponding column name as the key.
574       </para>
575      </listitem>
576     </varlistentry>
577
578     <varlistentry>
579      <term>Object (any object providing method <literal>__getattr__</literal>)</term>
580      <listitem>
581       <para>
582        This works the same as a mapping.
583        Example:
584
585 <programlisting>
586 CREATE FUNCTION make_pair (name text, value integer)
587   RETURNS named_value
588 AS $$
589   class named_value:
590     def __init__ (self, n, v):
591       self.name = n
592       self.value = v
593   return named_value(name, value)
594
595   # or simply
596   class nv: pass
597   nv.name = name
598   nv.value = value
599   return nv
600 $$ LANGUAGE plpythonu;
601 </programlisting>
602       </para>
603      </listitem>
604     </varlistentry>
605    </variablelist>
606   </para>
607
608    <para>
609     Functions with <literal>OUT</literal> parameters are also supported.  For example:
610 <programlisting>
611 CREATE FUNCTION multiout_simple(OUT i integer, OUT j integer) AS $$
612 return (1, 2)
613 $$ LANGUAGE plpythonu;
614
615 SELECT * FROM multiout_simple();
616 </programlisting>
617    </para>
618   </sect2>
619
620   <sect2>
621    <title>Set-returning Functions</title>
622   <para>
623    A <application>PL/Python</application> function can also return sets of
624    scalar or composite types. There are several ways to achieve this because
625    the returned object is internally turned into an iterator. The following
626    examples assume we have composite type:
627
628 <programlisting>
629 CREATE TYPE greeting AS (
630   how text,
631   who text
632 );
633 </programlisting>
634
635    A set result can be returned from a:
636
637    <variablelist>
638     <varlistentry>
639      <term>Sequence type (tuple, list, set)</term>
640      <listitem>
641       <para>
642 <programlisting>
643 CREATE FUNCTION greet (how text)
644   RETURNS SETOF greeting
645 AS $$
646   # return tuple containing lists as composite types
647   # all other combinations work also
648   return ( [ how, "World" ], [ how, "PostgreSQL" ], [ how, "PL/Python" ] )
649 $$ LANGUAGE plpythonu;
650 </programlisting>
651       </para>
652      </listitem>
653     </varlistentry>
654
655     <varlistentry>
656      <term>Iterator (any object providing <symbol>__iter__</symbol> and
657       <symbol>next</symbol> methods)</term>
658      <listitem>
659       <para>
660 <programlisting>
661 CREATE FUNCTION greet (how text)
662   RETURNS SETOF greeting
663 AS $$
664   class producer:
665     def __init__ (self, how, who):
666       self.how = how
667       self.who = who
668       self.ndx = -1
669
670     def __iter__ (self):
671       return self
672
673     def next (self):
674       self.ndx += 1
675       if self.ndx == len(self.who):
676         raise StopIteration
677       return ( self.how, self.who[self.ndx] )
678
679   return producer(how, [ "World", "PostgreSQL", "PL/Python" ])
680 $$ LANGUAGE plpythonu;
681 </programlisting>
682       </para>
683      </listitem>
684     </varlistentry>
685
686     <varlistentry>
687      <term>Generator (<literal>yield</literal>)</term>
688      <listitem>
689       <para>
690 <programlisting>
691 CREATE FUNCTION greet (how text)
692   RETURNS SETOF greeting
693 AS $$
694   for who in [ "World", "PostgreSQL", "PL/Python" ]:
695     yield ( how, who )
696 $$ LANGUAGE plpythonu;
697 </programlisting>
698
699        <warning>
700         <para>
701          Due to Python
702          <ulink url="http://bugs.python.org/issue1483133">bug #1483133</ulink>,
703          some debug versions of Python 2.4
704          (configured and compiled with option <literal>--with-pydebug</literal>)
705          are known to crash the <productname>PostgreSQL</productname> server
706          when using an iterator to return a set result.
707          Unpatched versions of Fedora 4 contain this bug.
708          It does not happen in production versions of Python or on patched
709          versions of Fedora 4.
710         </para>
711        </warning>
712       </para>
713      </listitem>
714     </varlistentry>
715    </variablelist>
716   </para>
717
718    <para>
719     Set-returning functions with <literal>OUT</literal> parameters
720     (using <literal>RETURNS SETOF record</literal>) are also
721     supported.  For example:
722 <programlisting>
723 CREATE FUNCTION multiout_simple_setof(n integer, OUT integer, OUT integer) RETURNS SETOF record AS $$
724 return [(1, 2)] * n
725 $$ LANGUAGE plpythonu;
726
727 SELECT * FROM multiout_simple_setof(3);
728 </programlisting>
729    </para>
730   </sect2>
731  </sect1>
732
733  <sect1 id="plpython-sharing">
734   <title>Sharing Data</title>
735   <para>
736    The global dictionary <varname>SD</varname> is available to store
737    data between function calls.  This variable is private static data.
738    The global dictionary <varname>GD</varname> is public data,
739    available to all Python functions within a session.  Use with
740    care.<indexterm><primary>global data</>
741    <secondary>in PL/Python</></indexterm>
742   </para>
743
744   <para>
745    Each function gets its own execution environment in the
746    Python interpreter, so that global data and function arguments from
747    <function>myfunc</function> are not available to
748    <function>myfunc2</function>.  The exception is the data in the
749    <varname>GD</varname> dictionary, as mentioned above.
750   </para>
751  </sect1>
752
753  <sect1 id="plpython-do">
754   <title>Anonymous Code Blocks</title>
755
756   <para>
757    PL/Python also supports anonymous code blocks called with the
758    <xref linkend="sql-do"> statement:
759
760 <programlisting>
761 DO $$
762     # PL/Python code
763 $$ LANGUAGE plpythonu;
764 </programlisting>
765
766    An anonymous code block receives no arguments, and whatever value it
767    might return is discarded.  Otherwise it behaves just like a function.
768   </para>
769  </sect1>
770
771  <sect1 id="plpython-trigger">
772   <title>Trigger Functions</title>
773
774   <indexterm zone="plpython-trigger">
775    <primary>trigger</primary>
776    <secondary>in PL/Python</secondary>
777   </indexterm>
778
779   <para>
780    When a function is used as a trigger, the dictionary
781    <literal>TD</literal> contains trigger-related values:
782    <variablelist>
783     <varlistentry>
784      <term><literal>TD["event"]</></term>
785      <listitem>
786       <para>
787        contains the event as a string:
788        <literal>INSERT</>, <literal>UPDATE</>,
789        <literal>DELETE</>, or <literal>TRUNCATE</>.
790       </para>
791      </listitem>
792     </varlistentry>
793
794     <varlistentry>
795      <term><literal>TD["when"]</></term>
796      <listitem>
797       <para>
798        contains one of <literal>BEFORE</>, <literal>AFTER</>, or
799        <literal>INSTEAD OF</>.
800       </para>
801      </listitem>
802     </varlistentry>
803
804     <varlistentry>
805      <term><literal>TD["level"]</></term>
806      <listitem>
807       <para>
808        contains <literal>ROW</> or <literal>STATEMENT</>.
809       </para>
810      </listitem>
811     </varlistentry>
812
813     <varlistentry>
814      <term><literal>TD["new"]</></term>
815      <term><literal>TD["old"]</></term>
816      <listitem>
817       <para>
818        For a row-level trigger, one or both of these fields contain
819        the respective trigger rows, depending on the trigger event.
820       </para>
821      </listitem>
822     </varlistentry>
823
824     <varlistentry>
825      <term><literal>TD["name"]</></term>
826      <listitem>
827       <para>
828        contains the trigger name.
829       </para>
830      </listitem>
831     </varlistentry>
832
833     <varlistentry>
834      <term><literal>TD["table_name"]</></term>
835      <listitem>
836       <para>
837        contains the name of the table on which the trigger occurred.
838       </para>
839      </listitem>
840     </varlistentry>
841
842     <varlistentry>
843      <term><literal>TD["table_schema"]</></term>
844      <listitem>
845       <para>
846        contains the schema of the table on which the trigger occurred.
847       </para>
848      </listitem>
849     </varlistentry>
850
851     <varlistentry>
852      <term><literal>TD["relid"]</></term>
853      <listitem>
854       <para>
855        contains the OID of the table on which the trigger occurred.
856       </para>
857      </listitem>
858     </varlistentry>
859
860     <varlistentry>
861      <term><literal>TD["args"]</></term>
862      <listitem>
863       <para>
864        If the <command>CREATE TRIGGER</> command
865        included arguments, they are available in <literal>TD["args"][0]</> to
866        <literal>TD["args"][<replaceable>n</>-1]</>.
867       </para>
868      </listitem>
869     </varlistentry>
870    </variablelist>
871   </para>
872
873   <para>
874    If <literal>TD["when"]</literal> is <literal>BEFORE</> or
875    <literal>INSTEAD OF</> and
876    <literal>TD["level"]</literal> is <literal>ROW</>, you can
877    return <literal>None</literal> or <literal>"OK"</literal> from the
878    Python function to indicate the row is unmodified,
879    <literal>"SKIP"</> to abort the event, or if <literal>TD["event"]</>
880    is <command>INSERT</> or <command>UPDATE</> you can return
881    <literal>"MODIFY"</> to indicate you've modified the new row.
882    Otherwise the return value is ignored.
883   </para>
884  </sect1>
885
886  <sect1 id="plpython-database">
887   <title>Database Access</title>
888
889   <para>
890    The PL/Python language module automatically imports a Python module
891    called <literal>plpy</literal>.  The functions and constants in
892    this module are available to you in the Python code as
893    <literal>plpy.<replaceable>foo</replaceable></literal>.
894   </para>
895
896   <sect2>
897     <title>Database Access Functions</title>
898
899   <para>
900    The <literal>plpy</literal> module provides several functions to execute
901    database commands:
902   </para>
903
904   <variablelist>
905    <varlistentry>
906     <term><literal>plpy.<function>execute</function>(<replaceable>query</replaceable> [, <replaceable>max-rows</replaceable>])</literal></term>
907     <listitem>
908      <para>
909       Calling <function>plpy.execute</function> with a query string and an
910       optional row limit argument causes that query to be run and the result to
911       be returned in a result object.
912      </para>
913
914      <para>
915       The result object emulates a list or dictionary object.  The result
916       object can be accessed by row number and column name.  For example:
917 <programlisting>
918 rv = plpy.execute("SELECT * FROM my_table", 5)
919 </programlisting>
920       returns up to 5 rows from <literal>my_table</literal>.  If
921       <literal>my_table</literal> has a column
922       <literal>my_column</literal>, it would be accessed as:
923 <programlisting>
924 foo = rv[i]["my_column"]
925 </programlisting>
926       The number of rows returned can be obtained using the built-in
927       <function>len</function> function.
928      </para>
929
930      <para>
931       The result object has these additional methods:
932       <variablelist>
933        <varlistentry>
934         <term><literal><function>nrows</function>()</literal></term>
935         <listitem>
936          <para>
937           Returns the number of rows processed by the command.  Note that this
938           is not necessarily the same as the number of rows returned.  For
939           example, an <command>UPDATE</command> command will set this value but
940           won't return any rows (unless <literal>RETURNING</literal> is used).
941          </para>
942         </listitem>
943        </varlistentry>
944
945        <varlistentry>
946         <term><literal><function>status</function>()</literal></term>
947         <listitem>
948          <para>
949           The <function>SPI_execute()</function> return value.
950          </para>
951         </listitem>
952        </varlistentry>
953
954        <varlistentry>
955         <term><literal><function>colnames</function>()</literal></term>
956         <term><literal><function>coltypes</function>()</literal></term>
957         <term><literal><function>coltypmods</function>()</literal></term>
958         <listitem>
959          <para>
960           Return a list of column names, list of column type OIDs, and list of
961           type-specific type modifiers for the columns, respectively.
962          </para>
963
964          <para>
965           These methods raise an exception when called on a result object from
966           a command that did not produce a result set, e.g.,
967           <command>UPDATE</command> without <literal>RETURNING</literal>, or
968           <command>DROP TABLE</command>.  But it is OK to use these methods on
969           a result set containing zero rows.
970          </para>
971         </listitem>
972        </varlistentry>
973
974        <varlistentry>
975         <term><literal><function>__str__</function>()</literal></term>
976         <listitem>
977          <para>
978           The standard <literal>__str__</literal> method is defined so that it
979           is possible for example to debug query execution results
980           using <literal>plpy.debug(rv)</literal>.
981          </para>
982         </listitem>
983        </varlistentry>
984       </variablelist>
985      </para>
986
987      <para>
988       The result object can be modified.
989      </para>
990
991      <para>
992       Note that calling <literal>plpy.execute</literal> will cause the entire
993       result set to be read into memory.  Only use that function when you are
994       sure that the result set will be relatively small.  If you don't want to
995       risk excessive memory usage when fetching large results,
996       use <literal>plpy.cursor</literal> rather
997       than <literal>plpy.execute</literal>.
998      </para>
999     </listitem>
1000    </varlistentry>
1001
1002    <varlistentry>
1003     <term><literal>plpy.<function>prepare</function>(<replaceable>query</replaceable> [, <replaceable>argtypes</replaceable>])</literal></term>
1004     <term><literal>plpy.<function>execute</function>(<replaceable>plan</replaceable> [, <replaceable>arguments</replaceable> [, <replaceable>max-rows</replaceable>]])</literal></term>
1005     <listitem>
1006      <para>
1007       <indexterm><primary>preparing a query</><secondary>in PL/Python</></indexterm>
1008       <function>plpy.prepare</function> prepares the execution plan for a
1009       query.  It is called with a query string and a list of parameter types,
1010       if you have parameter references in the query.  For example:
1011 <programlisting>
1012 plan = plpy.prepare("SELECT last_name FROM my_users WHERE first_name = $1", ["text"])
1013 </programlisting>
1014       <literal>text</literal> is the type of the variable you will be passing
1015       for <literal>$1</literal>.  The second argument is optional if you don't
1016       want to pass any parameters to the query.
1017      </para>
1018      <para>
1019       After preparing a statement, you use a variant of the
1020       function <function>plpy.execute</function> to run it:
1021 <programlisting>
1022 rv = plpy.execute(plan, ["name"], 5)
1023 </programlisting>
1024       Pass the plan as the first argument (instead of the query string), and a
1025       list of values to substitute into the query as the second argument.  The
1026       second argument is optional if the query does not expect any parameters.
1027       The third argument is the optional row limit as before.
1028      </para>
1029
1030      <para>
1031       Query parameters and result row fields are converted between PostgreSQL
1032       and Python data types as described in <xref linkend="plpython-data">.
1033      </para>
1034
1035      <para>
1036       When you prepare a plan using the PL/Python module it is automatically
1037       saved.  Read the SPI documentation (<xref linkend="spi">) for a
1038       description of what this means.  In order to make effective use of this
1039       across function calls one needs to use one of the persistent storage
1040       dictionaries <literal>SD</literal> or <literal>GD</literal> (see
1041       <xref linkend="plpython-sharing">). For example:
1042 <programlisting>
1043 CREATE FUNCTION usesavedplan() RETURNS trigger AS $$
1044     if "plan" in SD:
1045         plan = SD["plan"]
1046     else:
1047         plan = plpy.prepare("SELECT 1")
1048         SD["plan"] = plan
1049     # rest of function
1050 $$ LANGUAGE plpythonu;
1051 </programlisting>
1052      </para>
1053     </listitem>
1054    </varlistentry>
1055
1056    <varlistentry>
1057     <term><literal>plpy.<function>cursor</function>(<replaceable>query</replaceable>)</literal></term>
1058     <term><literal>plpy.<function>cursor</function>(<replaceable>plan</replaceable> [, <replaceable>arguments</replaceable>])</literal></term>
1059     <listitem>
1060      <para>
1061       The <literal>plpy.cursor</literal> function accepts the same arguments
1062       as <literal>plpy.execute</literal> (except for the row limit) and returns
1063       a cursor object, which allows you to process large result sets in smaller
1064       chunks.  As with <literal>plpy.execute</literal>, either a query string
1065       or a plan object along with a list of arguments can be used.
1066      </para>
1067
1068      <para>
1069       The cursor object provides a <literal>fetch</literal> method that accepts
1070       an integer parameter and returns a result object.  Each time you
1071       call <literal>fetch</literal>, the returned object will contain the next
1072       batch of rows, never larger than the parameter value.  Once all rows are
1073       exhausted, <literal>fetch</literal> starts returning an empty result
1074       object.  Cursor objects also provide an
1075       <ulink url="http://docs.python.org/library/stdtypes.html#iterator-types">iterator
1076       interface</ulink>, yielding one row at a time until all rows are
1077       exhausted.  Data fetched that way is not returned as result objects, but
1078       rather as dictionaries, each dictionary corresponding to a single result
1079       row.
1080      </para>
1081
1082      <para>
1083       An example of two ways of processing data from a large table is:
1084 <programlisting>
1085 CREATE FUNCTION count_odd_iterator() RETURNS integer AS $$
1086 odd = 0
1087 for row in plpy.cursor("select num from largetable"):
1088     if row['num'] % 2:
1089          odd += 1
1090 return odd
1091 $$ LANGUAGE plpythonu;
1092
1093 CREATE FUNCTION count_odd_fetch(batch_size integer) RETURNS integer AS $$
1094 odd = 0
1095 cursor = plpy.cursor("select num from largetable")
1096 while True:
1097     rows = cursor.fetch(batch_size)
1098     if not rows:
1099         break
1100     for row in rows:
1101         if row['num'] % 2:
1102             odd += 1
1103 return odd
1104 $$ LANGUAGE plpythonu;
1105
1106 CREATE FUNCTION count_odd_prepared() RETURNS integer AS $$
1107 odd = 0
1108 plan = plpy.prepare("select num from largetable where num % $1 &lt;&gt; 0", ["integer"])
1109 rows = list(plpy.cursor(plan, [2]))
1110
1111 return len(rows)
1112 $$ LANGUAGE plpythonu;
1113 </programlisting>
1114      </para>
1115
1116      <para>
1117       Cursors are automatically disposed of.  But if you want to explicitly
1118       release all resources held by a cursor, use the <literal>close</literal>
1119       method.  Once closed, a cursor cannot be fetched from anymore.
1120      </para>
1121
1122      <tip>
1123       <para>
1124         Do not confuse objects created by <literal>plpy.cursor</literal> with
1125         DB-API cursors as defined by
1126         the <ulink url="http://www.python.org/dev/peps/pep-0249/">Python
1127         Database API specification</ulink>.  They don't have anything in common
1128         except for the name.
1129       </para>
1130      </tip>
1131     </listitem>
1132    </varlistentry>
1133   </variablelist>
1134
1135   </sect2>
1136
1137   <sect2 id="plpython-trapping">
1138    <title>Trapping Errors</title>
1139
1140    <para>
1141     Functions accessing the database might encounter errors, which
1142     will cause them to abort and raise an exception.  Both
1143     <function>plpy.execute</function> and
1144     <function>plpy.prepare</function> can raise an instance of a subclass of
1145     <literal>plpy.SPIError</literal>, which by default will terminate
1146     the function.  This error can be handled just like any other
1147     Python exception, by using the <literal>try/except</literal>
1148     construct.  For example:
1149 <programlisting>
1150 CREATE FUNCTION try_adding_joe() RETURNS text AS $$
1151     try:
1152         plpy.execute("INSERT INTO users(username) VALUES ('joe')")
1153     except plpy.SPIError:
1154         return "something went wrong"
1155     else:
1156         return "Joe added"
1157 $$ LANGUAGE plpythonu;
1158 </programlisting>
1159    </para>
1160
1161    <para>
1162     The actual class of the exception being raised corresponds to the
1163     specific condition that caused the error.  Refer
1164     to <xref linkend="errcodes-table"> for a list of possible
1165     conditions.  The module
1166     <literal>plpy.spiexceptions</literal> defines an exception class
1167     for each <productname>PostgreSQL</productname> condition, deriving
1168     their names from the condition name.  For
1169     instance, <literal>division_by_zero</literal>
1170     becomes <literal>DivisionByZero</literal>, <literal>unique_violation</literal>
1171     becomes <literal>UniqueViolation</literal>, <literal>fdw_error</literal>
1172     becomes <literal>FdwError</literal>, and so on.  Each of these
1173     exception classes inherits from <literal>SPIError</literal>.  This
1174     separation makes it easier to handle specific errors, for
1175     instance:
1176 <programlisting>
1177 CREATE FUNCTION insert_fraction(numerator int, denominator int) RETURNS text AS $$
1178 from plpy import spiexceptions
1179 try:
1180     plan = plpy.prepare("INSERT INTO fractions (frac) VALUES ($1 / $2)", ["int", "int"])
1181     plpy.execute(plan, [numerator, denominator])
1182 except spiexceptions.DivisionByZero:
1183     return "denominator cannot equal zero"
1184 except spiexceptions.UniqueViolation:
1185     return "already have that fraction"
1186 except plpy.SPIError, e:
1187     return "other error, SQLSTATE %s" % e.sqlstate
1188 else:
1189     return "fraction inserted"
1190 $$ LANGUAGE plpythonu;
1191 </programlisting>
1192     Note that because all exceptions from
1193     the <literal>plpy.spiexceptions</literal> module inherit
1194     from <literal>SPIError</literal>, an <literal>except</literal>
1195     clause handling it will catch any database access error.
1196    </para>
1197
1198    <para>
1199     As an alternative way of handling different error conditions, you
1200     can catch the <literal>SPIError</literal> exception and determine
1201     the specific error condition inside the <literal>except</literal>
1202     block by looking at the <literal>sqlstate</literal> attribute of
1203     the exception object.  This attribute is a string value containing
1204     the <quote>SQLSTATE</quote> error code.  This approach provides
1205     approximately the same functionality
1206    </para>
1207   </sect2>
1208  </sect1>
1209
1210  <sect1 id="plpython-subtransaction">
1211   <title>Explicit Subtransactions</title>
1212
1213   <para>
1214    Recovering from errors caused by database access as described in
1215    <xref linkend="plpython-trapping"> can lead to an undesirable
1216    situation where some operations succeed before one of them fails,
1217    and after recovering from that error the data is left in an
1218    inconsistent state.  PL/Python offers a solution to this problem in
1219    the form of explicit subtransactions.
1220   </para>
1221
1222   <sect2>
1223    <title>Subtransaction Context Managers</title>
1224
1225    <para>
1226     Consider a function that implements a transfer between two
1227     accounts:
1228 <programlisting>
1229 CREATE FUNCTION transfer_funds() RETURNS void AS $$
1230 try:
1231     plpy.execute("UPDATE accounts SET balance = balance - 100 WHERE account_name = 'joe'")
1232     plpy.execute("UPDATE accounts SET balance = balance + 100 WHERE account_name = 'mary'")
1233 except plpy.SPIError, e:
1234     result = "error transferring funds: %s" % e.args
1235 else:
1236     result = "funds transferred correctly"
1237 plan = plpy.prepare("INSERT INTO operations (result) VALUES ($1)", ["text"])
1238 plpy.execute(plan, [result])
1239 $$ LANGUAGE plpythonu;
1240 </programlisting>
1241     If the second <literal>UPDATE</literal> statement results in an
1242     exception being raised, this function will report the error, but
1243     the result of the first <literal>UPDATE</literal> will
1244     nevertheless be committed.  In other words, the funds will be
1245     withdrawn from Joe's account, but will not be transferred to
1246     Mary's account.
1247    </para>
1248
1249    <para>
1250     To avoid such issues, you can wrap your
1251     <literal>plpy.execute</literal> calls in an explicit
1252     subtransaction.  The <literal>plpy</literal> module provides a
1253     helper object to manage explicit subtransactions that gets created
1254     with the <literal>plpy.subtransaction()</literal> function.
1255     Objects created by this function implement the
1256     <ulink url="http://docs.python.org/library/stdtypes.html#context-manager-types">
1257     context manager interface</ulink>.  Using explicit subtransactions
1258     we can rewrite our function as:
1259 <programlisting>
1260 CREATE FUNCTION transfer_funds2() RETURNS void AS $$
1261 try:
1262     with plpy.subtransaction():
1263         plpy.execute("UPDATE accounts SET balance = balance - 100 WHERE account_name = 'joe'")
1264         plpy.execute("UPDATE accounts SET balance = balance + 100 WHERE account_name = 'mary'")
1265 except plpy.SPIError, e:
1266     result = "error transferring funds: %s" % e.args
1267 else:
1268     result = "funds transferred correctly"
1269 plan = plpy.prepare("INSERT INTO operations (result) VALUES ($1)", ["text"])
1270 plpy.execute(plan, [result])
1271 $$ LANGUAGE plpythonu;
1272 </programlisting>
1273     Note that the use of <literal>try/catch</literal> is still
1274     required.  Otherwise the exception would propagate to the top of
1275     the Python stack and would cause the whole function to abort with
1276     a <productname>PostgreSQL</productname> error, so that the
1277     <literal>operations</literal> table would not have any row
1278     inserted into it.  The subtransaction context manager does not
1279     trap errors, it only assures that all database operations executed
1280     inside its scope will be atomically committed or rolled back.  A
1281     rollback of the subtransaction block occurs on any kind of
1282     exception exit, not only ones caused by errors originating from
1283     database access.  A regular Python exception raised inside an
1284     explicit subtransaction block would also cause the subtransaction
1285     to be rolled back.
1286    </para>
1287   </sect2>
1288
1289   <sect2>
1290    <title>Older Python Versions</title>
1291
1292    <para>
1293     Context managers syntax using the <literal>with</literal> keyword
1294     is available by default in Python 2.6.  If using PL/Python with an
1295     older Python version, it is still possible to use explicit
1296     subtransactions, although not as transparently.  You can call the
1297     subtransaction manager's <literal>__enter__</literal> and
1298     <literal>__exit__</literal> functions using the
1299     <literal>enter</literal> and <literal>exit</literal> convenience
1300     aliases.  The example function that transfers funds could be
1301     written as:
1302 <programlisting>
1303 CREATE FUNCTION transfer_funds_old() RETURNS void AS $$
1304 try:
1305     subxact = plpy.subtransaction()
1306     subxact.enter()
1307     try:
1308         plpy.execute("UPDATE accounts SET balance = balance - 100 WHERE account_name = 'joe'")
1309         plpy.execute("UPDATE accounts SET balance = balance + 100 WHERE account_name = 'mary'")
1310     except:
1311         import sys
1312         subxact.exit(*sys.exc_info())
1313         raise
1314     else:
1315         subxact.exit(None, None, None)
1316 except plpy.SPIError, e:
1317     result = "error transferring funds: %s" % e.args
1318 else:
1319     result = "funds transferred correctly"
1320
1321 plan = plpy.prepare("INSERT INTO operations (result) VALUES ($1)", ["text"])
1322 plpy.execute(plan, [result])
1323 $$ LANGUAGE plpythonu;
1324 </programlisting>
1325    </para>
1326
1327    <note>
1328     <para>
1329      Although context managers were implemented in Python 2.5, to use
1330      the <literal>with</literal> syntax in that version you need to
1331      use a <ulink
1332      url="http://docs.python.org/release/2.5/ref/future.html">future
1333      statement</ulink>.  Because of implementation details, however,
1334      you cannot use future statements in PL/Python functions.
1335     </para>
1336    </note>
1337   </sect2>
1338  </sect1>
1339
1340  <sect1 id="plpython-util">
1341   <title>Utility Functions</title>
1342   <para>
1343    The <literal>plpy</literal> module also provides the functions
1344    <simplelist>
1345     <member><literal>plpy.debug(<replaceable>msg, **kwargs</>)</literal></member>
1346     <member><literal>plpy.log(<replaceable>msg, **kwargs</>)</literal></member>
1347     <member><literal>plpy.info(<replaceable>msg, **kwargs</>)</literal></member>
1348     <member><literal>plpy.notice(<replaceable>msg, **kwargs</>)</literal></member>
1349     <member><literal>plpy.warning(<replaceable>msg, **kwargs</>)</literal></member>
1350     <member><literal>plpy.error(<replaceable>msg, **kwargs</>)</literal></member>
1351     <member><literal>plpy.fatal(<replaceable>msg, **kwargs</>)</literal></member>
1352    </simplelist>
1353    <indexterm><primary>elog</><secondary>in PL/Python</></indexterm>
1354    <function>plpy.error</function> and <function>plpy.fatal</function>
1355    actually raise a Python exception which, if uncaught, propagates out to
1356    the calling query, causing the current transaction or subtransaction to
1357    be aborted.  <literal>raise plpy.Error(<replaceable>msg</>)</literal> and
1358    <literal>raise plpy.Fatal(<replaceable>msg</>)</literal> are
1359    equivalent to calling <literal>plpy.error(<replaceable>msg</>)</literal> and
1360    <literal>plpy.fatal(<replaceable>msg</>)</literal>, respectively but
1361    the <literal>raise</literal> form does not allow passing keyword arguments.
1362    The other functions only generate messages of different priority levels.
1363    Whether messages of a particular priority are reported to the client,
1364    written to the server log, or both is controlled by the
1365    <xref linkend="guc-log-min-messages"> and
1366    <xref linkend="guc-client-min-messages"> configuration
1367    variables. See <xref linkend="runtime-config"> for more information.
1368   </para>
1369
1370   <para>
1371    The <replaceable>msg</> argument is given as a positional argument.  For
1372    backward compatibility, more than one positional argument can be given. In
1373    that case, the string representation of the tuple of positional arguments
1374    becomes the message reported to the client.
1375   </para>
1376
1377   <para>
1378    The following keyword-only arguments are accepted:
1379    <simplelist>
1380     <member><literal>detail</literal></member>
1381     <member><literal>hint</literal></member>
1382     <member><literal>sqlstate</literal></member>
1383     <member><literal>schema_name</literal></member>
1384     <member><literal>table_name</literal></member>
1385     <member><literal>column_name</literal></member>
1386     <member><literal>datatype_name</literal></member>
1387     <member><literal>constraint_name</literal></member>
1388    </simplelist>
1389    The string representation of the objects passed as keyword-only arguments
1390    is used to enrich the messages reported to the client. For example:
1391
1392 <programlisting>
1393 CREATE FUNCTION raise_custom_exception() RETURNS void AS $$
1394 plpy.error("custom exception message",
1395            detail="some info about exception",
1396            hint="hint for users")
1397 $$ LANGUAGE plpythonu;
1398
1399 =# SELECT raise_custom_exception();
1400 ERROR:  plpy.Error: custom exception message
1401 DETAIL:  some info about exception
1402 HINT:  hint for users
1403 CONTEXT:  Traceback (most recent call last):
1404   PL/Python function "raise_custom_exception", line 4, in &lt;module&gt;
1405     hint="hint for users")
1406 PL/Python function "raise_custom_exception"
1407 </programlisting>
1408   </para>
1409
1410   <para>
1411    Another set of utility functions are
1412    <literal>plpy.quote_literal(<replaceable>string</>)</literal>,
1413    <literal>plpy.quote_nullable(<replaceable>string</>)</literal>, and
1414    <literal>plpy.quote_ident(<replaceable>string</>)</literal>.  They
1415    are equivalent to the built-in quoting functions described in <xref
1416    linkend="functions-string">.  They are useful when constructing
1417    ad-hoc queries.  A PL/Python equivalent of dynamic SQL from <xref
1418    linkend="plpgsql-quote-literal-example"> would be:
1419 <programlisting>
1420 plpy.execute("UPDATE tbl SET %s = %s WHERE key = %s" % (
1421     plpy.quote_ident(colname),
1422     plpy.quote_nullable(newvalue),
1423     plpy.quote_literal(keyvalue)))
1424 </programlisting>
1425   </para>
1426  </sect1>
1427
1428  <sect1 id="plpython-envar">
1429   <title>Environment Variables</title>
1430
1431   <para>
1432    Some of the environment variables that are accepted by the Python
1433    interpreter can also be used to affect PL/Python behavior.  They
1434    would need to be set in the environment of the main PostgreSQL
1435    server process, for example in a start script.  The available
1436    environment variables depend on the version of Python; see the
1437    Python documentation for details.  At the time of this writing, the
1438    following environment variables have an affect on PL/Python,
1439    assuming an adequate Python version:
1440    <itemizedlist>
1441     <listitem>
1442      <para><envar>PYTHONHOME</envar></para>
1443     </listitem>
1444
1445     <listitem>
1446      <para><envar>PYTHONPATH</envar></para>
1447     </listitem>
1448
1449     <listitem>
1450      <para><envar>PYTHONY2K</envar></para>
1451     </listitem>
1452
1453     <listitem>
1454      <para><envar>PYTHONOPTIMIZE</envar></para>
1455     </listitem>
1456
1457     <listitem>
1458      <para><envar>PYTHONDEBUG</envar></para>
1459     </listitem>
1460
1461     <listitem>
1462      <para><envar>PYTHONVERBOSE</envar></para>
1463     </listitem>
1464
1465     <listitem>
1466      <para><envar>PYTHONCASEOK</envar></para>
1467     </listitem>
1468
1469     <listitem>
1470      <para><envar>PYTHONDONTWRITEBYTECODE</envar></para>
1471     </listitem>
1472
1473     <listitem>
1474      <para><envar>PYTHONIOENCODING</envar></para>
1475     </listitem>
1476
1477     <listitem>
1478      <para><envar>PYTHONUSERBASE</envar></para>
1479     </listitem>
1480
1481     <listitem>
1482      <para><envar>PYTHONHASHSEED</envar></para>
1483     </listitem>
1484    </itemizedlist>
1485
1486    (It appears to be a Python implementation detail beyond the control
1487    of PL/Python that some of the environment variables listed on
1488    the <command>python</command> man page are only effective in a
1489    command-line interpreter and not an embedded Python interpreter.)
1490   </para>
1491  </sect1>
1492 </chapter>