Commit a8cb3368 authored by Peter Eisentraut's avatar Peter Eisentraut

General editing

parent cb1d036a
<!-- <!--
$Header: /cvsroot/pgsql/doc/src/sgml/datetime.sgml,v 2.30 2003/03/13 01:30:27 petere Exp $ $Header: /cvsroot/pgsql/doc/src/sgml/datetime.sgml,v 2.31 2003/04/07 01:29:25 petere Exp $
--> -->
<appendix id="datetime-appendix"> <appendix id="datetime-appendix">
...@@ -210,7 +210,7 @@ $Header: /cvsroot/pgsql/doc/src/sgml/datetime.sgml,v 2.30 2003/03/13 01:30:27 pe ...@@ -210,7 +210,7 @@ $Header: /cvsroot/pgsql/doc/src/sgml/datetime.sgml,v 2.30 2003/03/13 01:30:27 pe
</sect1> </sect1>
<sect1> <sect1 id="datetime-keywords">
<title>Date/Time Key Words</title> <title>Date/Time Key Words</title>
<para> <para>
......
<!-- <!--
$Header: /cvsroot/pgsql/doc/src/sgml/Attic/jdbc.sgml,v 1.43 2003/03/25 16:15:37 petere Exp $ $Header: /cvsroot/pgsql/doc/src/sgml/Attic/jdbc.sgml,v 1.44 2003/04/07 01:29:25 petere Exp $
--> -->
<chapter id="jdbc"> <chapter id="jdbc">
<title><acronym>JDBC</acronym> Interface</title> <title><acronym>JDBC</acronym> Interface</title>
<note>
<title>Author</title>
<para>
Originally written by Peter T. Mount (<email>peter@retep.org.uk</email>),
the original author of the <acronym>JDBC</acronym> driver.
</para>
</note>
<para> <para>
<acronym>JDBC</acronym> is a core <acronym>API</acronym> of Java 1.1 and later. <acronym>JDBC</acronym> is a core <acronym>API</acronym> of Java 1.1 and later.
It provides a standard set of It provides a standard set of
...@@ -21,7 +13,7 @@ $Header: /cvsroot/pgsql/doc/src/sgml/Attic/jdbc.sgml,v 1.43 2003/03/25 16:15:37 ...@@ -21,7 +13,7 @@ $Header: /cvsroot/pgsql/doc/src/sgml/Attic/jdbc.sgml,v 1.43 2003/03/25 16:15:37
<para> <para>
<productname>PostgreSQL</> provides a <firstterm>type <productname>PostgreSQL</> provides a <firstterm>type
4</firstterm> <acronym>JDBC</acronym> Driver. Type 4 indicates 4</firstterm> <acronym>JDBC</acronym> driver. Type 4 indicates
that the driver is written in Pure Java, and communicates in the that the driver is written in Pure Java, and communicates in the
database system's own network protocol. Because of this, the driver database system's own network protocol. Because of this, the driver
is platform independent; once compiled, the driver can be used on is platform independent; once compiled, the driver can be used on
...@@ -33,13 +25,17 @@ $Header: /cvsroot/pgsql/doc/src/sgml/Attic/jdbc.sgml,v 1.43 2003/03/25 16:15:37 ...@@ -33,13 +25,17 @@ $Header: /cvsroot/pgsql/doc/src/sgml/Attic/jdbc.sgml,v 1.43 2003/03/25 16:15:37
<acronym>JDBC</acronym> programming, but should help to get you <acronym>JDBC</acronym> programming, but should help to get you
started. For more information refer to the standard started. For more information refer to the standard
<acronym>JDBC</acronym> <acronym>API</acronym> documentation. <acronym>JDBC</acronym> <acronym>API</acronym> documentation.
Also, take a look at the examples included with the source. The Also, take a look at the examples included with the source.
basic example is used here.
</para> </para>
<sect1 id="jdbc-setup"> <sect1 id="jdbc-setup">
<title>Setting up the <acronym>JDBC</acronym> Driver</title> <title>Setting up the <acronym>JDBC</acronym> Driver</title>
<para>
This section describes the steps you need to take before you can
write or run programs that use the JDBC interface.
</para>
<sect2 id="jdbc-build"> <sect2 id="jdbc-build">
<title>Getting the Driver</title> <title>Getting the Driver</title>
...@@ -71,8 +67,8 @@ $Header: /cvsroot/pgsql/doc/src/sgml/Attic/jdbc.sgml,v 1.43 2003/03/25 16:15:37 ...@@ -71,8 +67,8 @@ $Header: /cvsroot/pgsql/doc/src/sgml/Attic/jdbc.sgml,v 1.43 2003/03/25 16:15:37
<para> <para>
To use the driver, the JAR archive (named To use the driver, the JAR archive (named
<filename>postgresql.jar</filename> if you built from source, otherwise <filename>postgresql.jar</filename> if you built from source, otherwise
it will likely be named <filename>jdbc7.2-1.1.jar</filename> or it will likely be named <filename>jdbc&majorversion;-1.1.jar</filename> or
<filename>jdbc7.2-1.2.jar</filename> for the JDBC 1 and JDBC 2 versions <filename>jdbc&majorversion;-1.2.jar</filename> for the JDBC 1 and JDBC 2 versions
respectively) respectively)
needs to be included in the needs to be included in the
class path, either by putting it in the <envar>CLASSPATH</envar> class path, either by putting it in the <envar>CLASSPATH</envar>
...@@ -80,26 +76,18 @@ $Header: /cvsroot/pgsql/doc/src/sgml/Attic/jdbc.sgml,v 1.43 2003/03/25 16:15:37 ...@@ -80,26 +76,18 @@ $Header: /cvsroot/pgsql/doc/src/sgml/Attic/jdbc.sgml,v 1.43 2003/03/25 16:15:37
<command>java</command> command line. <command>java</command> command line.
</para> </para>
<para> <para>
For instance, I have an application that uses the For instance, assume we have an application that uses the
<acronym>JDBC</acronym> driver to access a large database <acronym>JDBC</acronym> driver to access a database, and that
containing astronomical objects. I have the application and the application is installed as
<acronym>JDBC</acronym> driver installed in the <filename <filename>/usr/local/lib/myapp.jar</filename>. The PostgreSQL
class="directory">/usr/local/lib</filename> directory, and the JDBC driver installed as
Java <acronym>JDK</acronym> installed in <filename>/usr/local/pgsql/share/java/postgresql.jar</>. To run
<filename>/usr/local/jdk1.3.1</filename>. To run the the application, we would use:
application, I would use:
<programlisting> <programlisting>
export CLASSPATH=/usr/local/lib/finder.jar<co id="co.jdbc-finder">:/usr/local/pgsql/share/java/postgresql.jar:. export CLASSPATH=/usr/local/lib/myapp.jar:/usr/local/pgsql/share/java/postgresql.jar:.
java Finder java MyApp
</programlisting> </programlisting>
<calloutlist>
<callout arearefs="co.jdbc-finder">
<para>
<filename>finder.jar</filename> contains the Finder application.
</para>
</callout>
</calloutlist>
</para> </para>
<para> <para>
...@@ -109,7 +97,7 @@ java Finder ...@@ -109,7 +97,7 @@ java Finder
</sect2> </sect2>
<sect2 id="jdbc-prepare"> <sect2 id="jdbc-prepare">
<title>Preparing the Database for <acronym>JDBC</acronym></title> <title>Preparing the Database Server for <acronym>JDBC</acronym></title>
<para> <para>
Because Java only uses TCP/IP connections, the Because Java only uses TCP/IP connections, the
...@@ -125,14 +113,19 @@ java Finder ...@@ -125,14 +113,19 @@ java Finder
Also, the client authentication setup in the Also, the client authentication setup in the
<filename>pg_hba.conf</filename> file may need to be configured. <filename>pg_hba.conf</filename> file may need to be configured.
Refer to <xref linkend="client-authentication"> for details. The Refer to <xref linkend="client-authentication"> for details. The
<acronym>JDBC</acronym> Driver supports the trust, ident, <acronym>JDBC</acronym> driver supports the trust, ident,
password, md5, and crypt authentication methods. password, md5, and crypt authentication methods.
</para> </para>
</sect2> </sect2>
</sect1> </sect1>
<sect1 id="jdbc-use"> <sect1 id="jdbc-use">
<title>Using the Driver</title> <title>Initializing the Driver</title>
<para>
This section describes how to load and initialize the JDBC driver
in your programs.
</para>
<sect2 id="jdbc-import"> <sect2 id="jdbc-import">
<title>Importing <acronym>JDBC</acronym></title> <title>Importing <acronym>JDBC</acronym></title>
...@@ -144,15 +137,15 @@ java Finder ...@@ -144,15 +137,15 @@ java Finder
<programlisting> <programlisting>
import java.sql.*; import java.sql.*;
</programlisting> </programlisting>
</para>
<important> <note>
<para> <para>
Do not import the <literal>org.postgresql</literal> package. If Do not import the <literal>org.postgresql</literal> package. If
you do, your source will not compile, as you do, your source will not compile, as
<command>javac</command> will get confused. <command>javac</command> will get confused.
</para> </para>
</important> </note>
</para>
</sect2> </sect2>
<sect2 id="jdbc-load"> <sect2 id="jdbc-load">
...@@ -175,6 +168,7 @@ Class.forName("org.postgresql.Driver"); ...@@ -175,6 +168,7 @@ Class.forName("org.postgresql.Driver");
This will load the driver, and while loading, the driver will automatically This will load the driver, and while loading, the driver will automatically
register itself with <acronym>JDBC</acronym>. register itself with <acronym>JDBC</acronym>.
</para>
<note> <note>
<para> <para>
...@@ -183,7 +177,6 @@ Class.forName("org.postgresql.Driver"); ...@@ -183,7 +177,6 @@ Class.forName("org.postgresql.Driver");
not available. not available.
</para> </para>
</note> </note>
</para>
<para> <para>
This is the most common method to use, but restricts your code to This is the most common method to use, but restricts your code to
...@@ -250,7 +243,7 @@ jdbc:postgresql://<replaceable class="parameter">host</replaceable>:<replaceable ...@@ -250,7 +243,7 @@ jdbc:postgresql://<replaceable class="parameter">host</replaceable>:<replaceable
</listitem> </listitem>
</itemizedlist> </itemizedlist>
where: The parametes have the following meanings:
<variablelist> <variablelist>
<varlistentry> <varlistentry>
...@@ -292,7 +285,7 @@ jdbc:postgresql://<replaceable class="parameter">host</replaceable>:<replaceable ...@@ -292,7 +285,7 @@ jdbc:postgresql://<replaceable class="parameter">host</replaceable>:<replaceable
<para> <para>
To connect, you need to get a <classname>Connection</classname> instance from To connect, you need to get a <classname>Connection</classname> instance from
<acronym>JDBC</acronym>. To do this, <acronym>JDBC</acronym>. To do this,
you would use the <function>DriverManager.getConnection()</function> method: you use the <function>DriverManager.getConnection()</function> method:
<programlisting> <programlisting>
Connection db = DriverManager.getConnection(url, username, password); Connection db = DriverManager.getConnection(url, username, password);
...@@ -336,8 +329,8 @@ db.close(); ...@@ -336,8 +329,8 @@ db.close();
column of each row using a <classname>Statement</classname>. column of each row using a <classname>Statement</classname>.
<programlisting> <programlisting>
Statement st = db.createStatement(); Statement st = db.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM mytable where columnfoo = 500"); ResultSet rs = st.executeQuery("SELECT * FROM mytable WHERE columnfoo = 500");
while(rs.next()) { while (rs.next()) {
System.out.print("Column 1 returned "); System.out.print("Column 1 returned ");
System.out.println(rs.getString(1)); System.out.println(rs.getString(1));
} }
...@@ -347,15 +340,15 @@ st.close(); ...@@ -347,15 +340,15 @@ st.close();
</para> </para>
<para> <para>
This example will issue the same query as before using This example issues the same query as before but uses
a <classname>PreparedStatement</classname> a <classname>PreparedStatement</classname>
and a bind value in the query. and a bind value in the query.
<programlisting> <programlisting>
int foovalue = 500; int foovalue = 500;
PreparedStatement st = db.prepareStatement("SELECT * FROM mytable where columnfoo = ?"); PreparedStatement st = db.prepareStatement("SELECT * FROM mytable WHERE columnfoo = ?");
st.setInt(1, foovalue); st.setInt(1, foovalue);
ResultSet rs = st.executeQuery(); ResultSet rs = st.executeQuery();
while(rs.next()) { while (rs.next()) {
System.out.print("Column 1 returned "); System.out.print("Column 1 returned ");
System.out.println(rs.getString(1)); System.out.println(rs.getString(1));
} }
...@@ -366,8 +359,7 @@ st.close(); ...@@ -366,8 +359,7 @@ st.close();
</example> </example>
<sect2> <sect2>
<title>Using the <classname>Statement</classname> or <classname> <title>Using the <classname>Statement</classname> or <classname>PreparedStatement</classname> Interface</title>
PreparedStatement</classname> Interface</title>
<para> <para>
The following must be considered when using the The following must be considered when using the
...@@ -463,10 +455,10 @@ st.close(); ...@@ -463,10 +455,10 @@ st.close();
<para> <para>
<classname>ResultSet</classname> is currently read only. <classname>ResultSet</classname> is currently read only.
You can not update data through the <classname>ResultSet</classname>. You can not update data through the <classname>ResultSet</classname>.
If you want to update data you need to do it the old fashioned way If you want to update data you need to do it the normal way
by issuing a <acronym>SQL</acronym> update statement. This is by using the <acronym>SQL</acronym> statement <command>UPDATE</command>. This is
in conformance with the <acronym>JDBC</acronym> specification in conformance with the <acronym>JDBC</acronym> specification
which does not require drivers to provide this functionality. which does not require drivers to provide updatable result sets.
</para> </para>
</listitem> </listitem>
</itemizedlist> </itemizedlist>
...@@ -478,23 +470,25 @@ st.close(); ...@@ -478,23 +470,25 @@ st.close();
<title>Performing Updates</title> <title>Performing Updates</title>
<para> <para>
To change data (perform an insert, update, or delete) To change data (perform an <command>INSERT</command>,
you use the <function>executeUpdate()</function> method. <command>UPDATE</command>, or <command>DELETE</command>) you use
<function>executeUpdate()</function> is similar to the the <function>executeUpdate()</function> method. This method is
<function>executeQuery()</function> used to issue a select, similar to the method <function>executeQuery()</function> used to
however it doesn't return a <classname>ResultSet</classname>, issue a <command>SELECT</command> statement, but it doesn't return
instead it returns the number of records affected by the insert, a <classname>ResultSet</classname>; instead it returns the number
update, or delete statement. of rows affected by the <command>INSERT</command>,
<command>UPDATE</command>, or <command>DELETE</command> statement.
<xref linkend="jdbc-delete-example"> illustrates the usage.
</para> </para>
<example id="jdbc-delete-example"> <example id="jdbc-delete-example">
<title>Simple Delete Example</title> <title>Deleting Rows in <acronym>JDBC</acronym></title>
<para> <para>
This example will issue a simple delete and print out the number This example will issue a simple <command>DELETE</command>
of rows deleted. statement and print out the number of rows deleted.
<programlisting> <programlisting>
int foovalue = 500; int foovalue = 500;
PreparedStatement st = db.prepareStatement("DELETE FROM mytable where columnfoo = ?"); PreparedStatement st = db.prepareStatement("DELETE FROM mytable WHERE columnfoo = ?");
st.setInt(1, foovalue); st.setInt(1, foovalue);
int rowsDeleted = st.executeUpdate(); int rowsDeleted = st.executeUpdate();
System.out.println(rowsDeleted + " rows deleted"); System.out.println(rowsDeleted + " rows deleted");
...@@ -509,19 +503,19 @@ st.close(); ...@@ -509,19 +503,19 @@ st.close();
<para> <para>
To create, modify or drop a database object like a table or view To create, modify or drop a database object like a table or view
you use the <function>execute()</function> method. you use the <function>execute()</function> method. This method is
<function>execute</function> is similar to the similar to the method <function>executeQuery()</function>, but it
<function>executeQuery()</function> used to issue a select, doesn't return a result. <xref linkend="jdbc-drop-table-example">
however it doesn't return a result. illustrates the usage.
</para> </para>
<example id="jdbc-drop-table-example"> <example id="jdbc-drop-table-example">
<title>Drop Table Example</title> <title>Dropping a Table in JDBC</title>
<para> <para>
This example will drop a table. This example will drop a table.
<programlisting> <programlisting>
Statement st = db.createStatement(); Statement st = db.createStatement();
ResultSet rs = st.executeQuery("DROP TABLE mytable"); st.execute("DROP TABLE mytable");
st.close(); st.close();
</programlisting> </programlisting>
</para> </para>
...@@ -534,11 +528,10 @@ st.close(); ...@@ -534,11 +528,10 @@ st.close();
<para> <para>
<application>PostgreSQL</application> provides two distinct ways to <application>PostgreSQL</application> provides two distinct ways to
store binary data. Binary data can be stored in a table using store binary data. Binary data can be stored in a table using
<application>PostgreSQL's</application> binary data type the data type <type>bytea</type> or by using the Large Object
<type>bytea</type>, or by using the <firstterm>Large Object</firstterm>
feature which stores the binary data in a separate table in a special feature which stores the binary data in a separate table in a special
format, and refers to that table by storing a value of type format and refers to that table by storing a value of type
<type>OID</type> in your table. <type>oid</type> in your table.
</para> </para>
<para> <para>
...@@ -547,32 +540,32 @@ st.close(); ...@@ -547,32 +540,32 @@ st.close();
<type>bytea</type> data type is not well suited for storing very <type>bytea</type> data type is not well suited for storing very
large amounts of binary data. While a column of type large amounts of binary data. While a column of type
<type>bytea</type> can hold up to 1 GB of binary data, it would <type>bytea</type> can hold up to 1 GB of binary data, it would
require a huge amount of memory (<acronym>RAM</acronym>) to require a huge amount of memory to
process such a large value. The Large Object method for process such a large value. The Large Object method for
storing binary data is better suited to storing very large values, storing binary data is better suited to storing very large values,
but it has its own limitations. Specifically deleting a row but it has its own limitations. Specifically deleting a row
that contains a Large Object does not delete the Large Object. that contains a Large Object reference does not delete the Large Object.
Deleting the Large Object is a separate operation that needs to Deleting the Large Object is a separate operation that needs to
be performed. Large Objects also have some security be performed. Large Objects also have some security
issues since anyone connected to the database case view issues since anyone connected to the database cann view
and/or modify any Large Object, even if they don't have and/or modify any Large Object, even if they don't have
permissions to view/update the row containing the Large Object. permissions to view/update the row containing the Large Object reference.
</para> </para>
<para> <para>
7.2 is the first release of the <acronym>JDBC</acronym> Driver Version 7.2 was the first release of the <acronym>JDBC</acronym> driver
that supports the <type>bytea</type> data type. The introduction of that supports the <type>bytea</type> data type. The introduction of
this functionality in 7.2 has introduced a change in behavior this functionality in 7.2 has introduced a change in behavior
as compared to previous releases. In 7.2 the methods as compared to previous releases. Since 7.2, the methods
<function>getBytes()</function>, <function>setBytes()</function>, <function>getBytes()</function>, <function>setBytes()</function>,
<function>getBinaryStream()</function>, and <function>getBinaryStream()</function>, and
<function>setBinaryStream()</function> operate on <function>setBinaryStream()</function> operate on
the <type>bytea</type> data type. In 7.1 these methods operated the <type>bytea</type> data type. In 7.1 and earlier, these methods operated
on the <type>OID</type> data type associated with Large Objects. on the <type>oid</type> data type associated with Large Objects.
It is possible to revert the driver back to the old 7.1 behavior It is possible to revert the driver back to the old 7.1 behavior
by setting the <parameter>compatible</parameter> property on by setting the property <literal>compatible</literal> on
the <classname>Connection</classname> to a value of the <classname>Connection</classname> object to the value
<literal>7.1</literal> <literal>7.1</literal>.
</para> </para>
<para> <para>
...@@ -584,39 +577,44 @@ st.close(); ...@@ -584,39 +577,44 @@ st.close();
<para> <para>
To use the Large Object functionality you can use either the To use the Large Object functionality you can use either the
<classname>LargeObject</classname> <acronym>API</acronym> <classname>LargeObject</classname> class
provided by the <application>PostgreSQL</application> provided by the <application>PostgreSQL</application>
<acronym>JDBC</acronym> Driver, or by using the <acronym>JDBC</acronym> driver, or by using the
<function>getBLOB()</function> and <function>setBLOB()</function> <function>getBLOB()</function> and <function>setBLOB()</function>
methods. methods.
</para> </para>
<important> <important>
<para> <para>
For <application>PostgreSQL</application>, you must access Large You must access Large Objects within an <acronym>SQL</acronym>
Objects within an <acronym>SQL</acronym> transaction. You would transaction block. You can start a transaction block by calling
open a transaction by using the <function>setAutoCommit(false)</function>.
<function>setAutoCommit()</function> method with an input
parameter of <literal>false</literal>.
</para> </para>
</important> </important>
<note><para>In a future release of the <note>
<acronym>JDBC</acronym> Driver, the <function>getBLOB()</function> <para>
In a future release of the
<acronym>JDBC</acronym> driver, the <function>getBLOB()</function>
and <function>setBLOB()</function> methods may no longer and <function>setBLOB()</function> methods may no longer
interact with Large Objects and will instead work on interact with Large Objects and will instead work on the data type
<type>bytea</type> data types. So it is recommended that you <type>bytea</type>. So it is recommended that you
use the <classname>LargeObject</classname> <acronym>API</acronym> use the <classname>LargeObject</classname> <acronym>API</acronym>
if you intend to use Large Objects. if you intend to use Large Objects.
</para></note> </para>
</note>
<para>
<xref linkend="jdbc-binary-data-example"> contains some examples on
how to process binary data using the PostgreSQL JDBC driver.
</para>
<example id="jdbc-binary-data-example"> <example id="jdbc-binary-data-example">
<title>Binary Data Examples</title> <title>Processing Binary Data in JDBC</title>
<para> <para>
For example, suppose you have a table containing the file name of For example, suppose you have a table containing the file names of
an image and you also want to store the image in a <type>bytea</type> images and you also want to store the image in a <type>bytea</type>
column: column:
<programlisting> <programlisting>
CREATE TABLE images (imgname text, img bytea); CREATE TABLE images (imgname text, img bytea);
...@@ -649,13 +647,13 @@ fis.close(); ...@@ -649,13 +647,13 @@ fis.close();
<classname>Statement</classname> class can equally be used.) <classname>Statement</classname> class can equally be used.)
<programlisting> <programlisting>
PreparedStatement ps = con.prepareStatement("SELECT img FROM images WHERE imgname=?"); PreparedStatement ps = con.prepareStatement("SELECT img FROM images WHERE imgname = ?");
ps.setString(1, "myimage.gif"); ps.setString(1, "myimage.gif");
ResultSet rs = ps.executeQuery(); ResultSet rs = ps.executeQuery();
if (rs != null) { if (rs != null) {
while(rs.next()) { while (rs.next()) {
byte[] imgBytes = rs.getBytes(1); byte[] imgBytes = rs.getBytes(1);
// use the stream in some way here // use the data in some way here
} }
rs.close(); rs.close();
} }
...@@ -674,76 +672,76 @@ ps.close(); ...@@ -674,76 +672,76 @@ ps.close();
the <classname>LargeObject</classname> <acronym>API</acronym> to the <classname>LargeObject</classname> <acronym>API</acronym> to
store the file: store the file:
<programlisting> <programlisting>
CREATE TABLE imagesLO (imgname text, imgOID OID); CREATE TABLE imageslo (imgname text, imgoid oid);
</programlisting> </programlisting>
</para> </para>
<para> <para>
To insert an image, you would use: To insert an image, you would use:
<programlisting> <programlisting>
// All LargeObject API calls must be within a transaction // All LargeObject API calls must be within a transaction block
conn.setAutoCommit(false); conn.setAutoCommit(false);
// Get the Large Object Manager to perform operations with // Get the Large Object Manager to perform operations with
LargeObjectManager lobj = ((org.postgresql.PGConnection)conn).getLargeObjectAPI(); LargeObjectManager lobj = ((org.postgresql.PGConnection)conn).getLargeObjectAPI();
//create a new large object // Create a new large object
int oid = lobj.create(LargeObjectManager.READ | LargeObjectManager.WRITE); int oid = lobj.create(LargeObjectManager.READ | LargeObjectManager.WRITE);
//open the large object for write // Open the large object for writing
LargeObject obj = lobj.open(oid, LargeObjectManager.WRITE); LargeObject obj = lobj.open(oid, LargeObjectManager.WRITE);
// Now open the file // Now open the file
File file = new File("myimage.gif"); File file = new File("myimage.gif");
FileInputStream fis = new FileInputStream(file); FileInputStream fis = new FileInputStream(file);
// copy the data from the file to the large object // Copy the data from the file to the large object
byte buf[] = new byte[2048]; byte buf[] = new byte[2048];
int s, tl = 0; int s, tl = 0;
while ((s = fis.read(buf, 0, 2048)) > 0) while ((s = fis.read(buf, 0, 2048)) > 0) {
{ obj.write(buf, 0, s);
obj.write(buf, 0, s); tl += s;
tl += s;
} }
// Close the large object // Close the large object
obj.close(); obj.close();
//Now insert the row into imagesLO // Now insert the row into imageslo
PreparedStatement ps = conn.prepareStatement("INSERT INTO imagesLO VALUES (?, ?)"); PreparedStatement ps = conn.prepareStatement("INSERT INTO imageslo VALUES (?, ?)");
ps.setString(1, file.getName()); ps.setString(1, file.getName());
ps.setInt(2, oid); ps.setInt(2, oid);
ps.executeUpdate(); ps.executeUpdate();
ps.close(); ps.close();
fis.close(); fis.close();
</programlisting> </programlisting>
</para> </para>
<para> <para>
Retrieving the image from the Large Object: Retrieving the image from the Large Object:
<programlisting> <programlisting>
// All LargeObject API calls must be within a transaction // All LargeObject API calls must be within a transaction block
conn.setAutoCommit(false); conn.setAutoCommit(false);
// Get the Large Object Manager to perform operations with // Get the Large Object Manager to perform operations with
LargeObjectManager lobj = ((org.postgresql.PGConnection)conn).getLargeObjectAPI(); LargeObjectManager lobj = ((org.postgresql.PGConnection)conn).getLargeObjectAPI();
PreparedStatement ps = con.prepareStatement("SELECT imgOID FROM imagesLO WHERE imgname=?"); PreparedStatement ps = con.prepareStatement("SELECT imgoid FROM imageslo WHERE imgname = ?");
ps.setString(1, "myimage.gif"); ps.setString(1, "myimage.gif");
ResultSet rs = ps.executeQuery(); ResultSet rs = ps.executeQuery();
if (rs != null) { if (rs != null) {
while(rs.next()) { while (rs.next()) {
//open the large object for reading // Open the large object for reading
int oid = rs.getInt(1); int oid = rs.getInt(1);
LargeObject obj = lobj.open(oid, LargeObjectManager.READ); LargeObject obj = lobj.open(oid, LargeObjectManager.READ);
//read the data // Read the data
byte buf[] = new byte[obj.size()]; byte buf[] = new byte[obj.size()];
obj.read(buf, 0, obj.size()); obj.read(buf, 0, obj.size());
//do something with the data read here // Do something with the data read here
// Close the object // Close the object
obj.close(); obj.close();
} }
rs.close(); rs.close();
} }
...@@ -2441,93 +2439,78 @@ public void unlink(int oid) throws SQLException ...@@ -2441,93 +2439,78 @@ public void unlink(int oid) throws SQLException
<sect1 id="jdbc-thread"> <sect1 id="jdbc-thread">
<title>Using the driver in a multithreaded or a servlet environment</title> <title>Using the Driver in a Multithreaded or a Servlet Environment</title>
<para> <para>
A problem with many <acronym>JDBC</acronym> drivers is that only A problem with many <acronym>JDBC</acronym> drivers is that only
one thread can use a <classname>Connection</classname> at any one one thread can use a <classname>Connection</classname> at any one
time -- otherwise a thread could send a query while another one is time --- otherwise a thread could send a query while another one is
receiving results, and this would be a bad thing for the database receiving results, and this could cause severe confusion.
engine.
</para> </para>
<para> <para>
The <productname>PostgreSQL</productname> <acronym>JDBC</acronym> Driver The <productname>PostgreSQL</productname> <acronym>JDBC</acronym> driver
is thread safe. is thread safe.
Consequently, if your application uses multiple threads then you do Consequently, if your application uses multiple threads then you do
not have to worry about complex algorithms to ensure that only one not have to worry about complex algorithms to ensure that only one thread
uses the database at any time. uses the database at a time.
</para> </para>
<para> <para>
If a thread attempts to use the connection while another one is If a thread attempts to use the connection while another one is
using it, it will wait until the other thread has finished its using it, it will wait until the other thread has finished its
current operation. If it is a regular <acronym>SQL</acronym> current operation. If the operation is a regular <acronym>SQL</acronym>
statement, then the operation consists of sending the statement and statement, then the operation consists of sending the statement and
retrieving any <classname>ResultSet</classname> (in full). If it retrieving any <classname>ResultSet</classname> (in full). If it
is a <classname>Fastpath</classname> call (e.g., reading a block is a fast-path call (e.g., reading a block
from a <classname>LargeObject</classname>) then it is the time to from a large object) then it consists of
send and retrieve that block. sending and retrieving the respective data.
</para> </para>
<para> <para>
This is fine for applications and applets but can cause a This is fine for applications and applets but can cause a
performance problem with servlets. With servlets you can have a performance problem with servlets. If you have several threads
heavy load on the connection. If you have several threads performing queries then each but one will pause.
performing queries then each but one will pause, which may not be what To solve this, you are advised to create a pool of connections.
you are after. When ever a thread needs to use the database, it asks a manager
</para> class for a <classname>Connection</classname> object. The manager
hands a free connection to the thread and marks it as busy. If a
<para> free connection is not available, it opens one. Once the thread
To solve this, you would be advised to create a pool of has finished using the connection, it returns it to the manager
connections. When ever a thread needs to use the database, it asks which can then either close it or add it to the pool. The manager
a manager class for a <classname>Connection</classname>. The would also check that the connection is still alive and remove it
manager hands a free connection to the thread and marks it as from the pool if it is dead. The down side of a connection pool is
busy. If a free connection is not available, it opens one. Once that it increases the load on the server because a new session is
the thread has finished with it, it returns it to the manager who created for each <classname>Connection</classname> object. It is
can then either close it or add it to the pool. The manager would up to you and your applications' requirements.
also check that the connection is still alive and remove it from
the pool if it is dead.
</para>
<para>
So, with servlets, it is up to you to use either a single
connection, or a pool. The plus side for a pool is that threads
will not be hit by the bottle neck caused by a single network
connection. The down side is that it increases the load on the
server, as a backend process is created for each
<classname>Connection</classname>. It is up to you and your
applications requirements.
</para> </para>
</sect1> </sect1>
<sect1 id="jdbc-datasource"> <sect1 id="jdbc-datasource">
<title>Connection Pools And DataSources</title> <title>Connection Pools and Data Sources</title>
<sect2 id="jdbc-ds-version">
<title>JDBC, JDK Version Support</title>
<para> <para>
JDBC 2 introduced standard connection pooling features in an JDBC 2 introduced standard connection pooling features in an
add-on API known as the <acronym>JDBC</acronym> 2.0 Optional add-on API known as the <acronym>JDBC</acronym> 2.0 Optional
Package (also known as the <acronym>JDBC</acronym> 2.0 Package (also known as the <acronym>JDBC</acronym> 2.0
Standard Extension). These features have since been included in Standard Extension). These features have since been included in
the core JDBC 3 API. The <productname>PostgreSQL</productname> the core JDBC 3 API. The <productname>PostgreSQL</productname>
<acronym>JDBC</acronym> drivers support these features with <acronym>JDBC</acronym> drivers support these features if it has been compiled with
<acronym>JDK</acronym> 1.3.x in combination with the <acronym>JDK</acronym> 1.3.x in combination with the
<acronym>JDBC</acronym> 2.0 Optional Package <acronym>JDBC</acronym> 2.0 Optional Package
(<acronym>JDBC</acronym> 2), or with <acronym>JDK</acronym> 1.4+ (<acronym>JDBC</acronym> 2), or with <acronym>JDK</acronym> 1.4 or higher
(<acronym>JDBC</acronym> 3). Most application servers include (<acronym>JDBC</acronym> 3). Most application servers include
the <acronym>JDBC</acronym> 2.0 Optional Package, but it is the <acronym>JDBC</acronym> 2.0 Optional Package, but it is
also available separately from the Sun also available separately from the Sun
<ulink <ulink
url="http://java.sun.com/products/jdbc/download.html#spec"><acronym>JDBC</acronym> download site</ulink>. url="http://java.sun.com/products/jdbc/download.html#spec"><acronym>JDBC</acronym> download site</ulink>.
</para> </para>
</sect2>
<sect2 id="jdbc-ds-intro"> <sect2 id="jdbc-ds-intro">
<title>JDBC Connection Pooling API</title> <title>Overview</title>
<para>The <acronym>JDBC</acronym> API provides a client
<para>
The <acronym>JDBC</acronym> API provides a client
and a server interface for connection pooling. The client and a server interface for connection pooling. The client
interface is <literal>javax.sql.DataSource</literal>, interface is <literal>javax.sql.DataSource</literal>,
which is what application code will typically use to which is what application code will typically use to
...@@ -2535,16 +2518,22 @@ public void unlink(int oid) throws SQLException ...@@ -2535,16 +2518,22 @@ public void unlink(int oid) throws SQLException
is <literal>javax.sql.ConnectionPoolDataSource</literal>, is <literal>javax.sql.ConnectionPoolDataSource</literal>,
which is how most application servers will interface with which is how most application servers will interface with
the <productname>PostgreSQL</productname> <acronym>JDBC</acronym> the <productname>PostgreSQL</productname> <acronym>JDBC</acronym>
driver.</para> driver.
<para>In an application server environment, the </para>
<para>
In an application server environment, the
application server configuration will typically refer to application server configuration will typically refer to
the <productname>PostgreSQL</productname> the <productname>PostgreSQL</productname>
<literal>ConnectionPoolDataSource</literal> implementation, <literal>ConnectionPoolDataSource</literal> implementation,
while the application component code will typically acquire a while the application component code will typically acquire a
<literal>DataSource</literal> implementation provided by <literal>DataSource</literal> implementation provided by
the application server (not by the application server (not by
<productname>PostgreSQL</productname>).</para> <productname>PostgreSQL</productname>).
<para>In an environment without an application server, </para>
<para>
For an environment without an application server,
<productname>PostgreSQL</productname> provides two implementations <productname>PostgreSQL</productname> provides two implementations
of <literal>DataSource</literal> which an application can use of <literal>DataSource</literal> which an application can use
directly. One implementation performs connection pooling, directly. One implementation performs connection pooling,
...@@ -2553,19 +2542,23 @@ public void unlink(int oid) throws SQLException ...@@ -2553,19 +2542,23 @@ public void unlink(int oid) throws SQLException
any pooling. Again, these implementations should not be used any pooling. Again, these implementations should not be used
in an application server environment unless the application in an application server environment unless the application
server does not support the server does not support the
<literal>ConnectionPoolDataSource</literal> interface.</para> <literal>ConnectionPoolDataSource</literal> interface.
</para>
</sect2> </sect2>
<sect2 id="jdbc-ds-cpds"> <sect2 id="jdbc-ds-cpds">
<title>Application Servers: ConnectionPoolDataSource</title> <title>Application Servers: <classname>ConnectionPoolDataSource</classname></title>
<para><productname>PostgreSQL</productname> includes one
implementation of <literal>ConnectionPoolDataSource</literal> <para>
for <acronym>JDBC</acronym> 2, and one for <productname>PostgreSQL</productname> includes one implementation
<acronym>JDBC</acronym> 3:</para> of <classname>ConnectionPoolDataSource</classname> for
<acronym>JDBC</acronym> 2 and one for <acronym>JDBC</acronym> 3,
as shown in <xref linkend="jdbc-ds-cpds-imp-table">.
</para>
<table> <table id="jdbc-ds-cpds-imp-table">
<title>ConnectionPoolDataSource Implementations</title> <title><classname>ConnectionPoolDataSource</classname> Implementations</title>
<tgroup cols=2> <tgroup cols=2>
<thead> <thead>
...@@ -2587,15 +2580,18 @@ public void unlink(int oid) throws SQLException ...@@ -2587,15 +2580,18 @@ public void unlink(int oid) throws SQLException
</row> </row>
</tbody> </tbody>
</tgroup> </tgroup>
</table> </table>
<para>Both implementations use the same configuration scheme. <para>
<acronym>JDBC</acronym> requires that a Both implementations use the same configuration scheme.
<literal>ConnectionPoolDataSource</literal> be configured via <acronym>JDBC</acronym> requires that a
JavaBean properties, so there are get and set methods for each of <classname>ConnectionPoolDataSource</classname> be configured via
these properties:</para> JavaBean properties, shown in <xref linkend="jdbc-ds-cpds-props">,
<table> so there are get and set methods for each of these properties.
<title>ConnectionPoolDataSource Configuration Properties</title> </para>
<table id="jdbc-ds-cpds-props">
<title><classname>ConnectionPoolDataSource</> Configuration Properties</title>
<tgroup cols=3> <tgroup cols=3>
<thead> <thead>
...@@ -2608,97 +2604,98 @@ public void unlink(int oid) throws SQLException ...@@ -2608,97 +2604,98 @@ public void unlink(int oid) throws SQLException
<tbody> <tbody>
<row> <row>
<entry>serverName</entry> <entry><literal>serverName</literal></entry>
<entry><literal>String</literal></entry> <entry><type>String</type></entry>
<entry><productname>PostgreSQL</productname> database server <entry><productname>PostgreSQL</productname> database server
hostname</entry> host name</entry>
</row> </row>
<row> <row>
<entry>databaseName</entry> <entry><literal>databaseName</literal></entry>
<entry><literal>String</literal></entry> <entry><type>String</type></entry>
<entry><productname>PostgreSQL</productname> database name</entry> <entry><productname>PostgreSQL</productname> database name</entry>
</row> </row>
<row> <row>
<entry>portNumber</entry> <entry><literal>portNumber</literal></entry>
<entry><literal>int</literal></entry> <entry><type>int</type></entry>
<entry><acronym>TCP/IP</acronym> port which the <entry>
<productname>PostgreSQL</productname> database server is TCP port which the <productname>PostgreSQL</productname>
listening on (or 0 to use the default port)</entry> database server is listening on (or 0 to use the default port)
</entry>
</row> </row>
<row> <row>
<entry>user</entry> <entry><literal>user</literal></entry>
<entry><literal>String</literal></entry> <entry><type>String</type></entry>
<entry>User used to make database connections</entry> <entry>User used to make database connections</entry>
</row> </row>
<row> <row>
<entry>password</entry> <entry><literal>password</literal></entry>
<entry><literal>String</literal></entry> <entry><type>String</type></entry>
<entry>Password used to make database connections</entry> <entry>Password used to make database connections</entry>
</row> </row>
<row> <row>
<entry>defaultAutoCommit</entry> <entry><literal>defaultAutoCommit</literal></entry>
<entry><literal>boolean</literal></entry> <entry><type>boolean</type></entry>
<entry>Whether connections should have autoCommit <entry>
enabled or disabled when they are supplied to the Whether connections should have autocommit enabled or disabled
caller. The default is <literal>false</literal>, to when they are supplied to the caller. The default is
disable autoCommit.</entry> <literal>false</literal>, to disable autocommit.
</entry>
</row> </row>
</tbody> </tbody>
</tgroup> </tgroup>
</table> </table>
<para>Many application servers use a properties-style syntax to
configure these properties, so it would not be unusual to
enter properties as a block of text.</para>
<example id="jdbc-cpds-config"> <para>
<title><literal>ConnectionPoolDataSource</literal> Configuration Example</title> Many application servers use a properties-style syntax to
configure these properties, so it would not be unusual to enter
<para> properties as a block of text. If the application server provides
If the application server provides a single area to enter all a single area to enter all the properties, they might be listed
the properties, they might be listed like this: like this:
<programlisting> <programlisting>
serverName=localhost serverName=localhost
databaseName=test databaseName=test
user=testuser user=testuser
password=testpassword password=testpassword
</programlisting> </programlisting>
Or, separated by semicolons instead of newlines, like this: Or, if semicolons are used as separators instead of newlines, it
could look like this:
<programlisting> <programlisting>
serverName=localhost;databaseName=test;user=testuser;password=testpassword serverName=localhost;databaseName=test;user=testuser;password=testpassword
</programlisting> </programlisting>
</para> </para>
</example>
</sect2> </sect2>
<sect2 id="jdbc-ds-ds"> <sect2 id="jdbc-ds-ds">
<title>Applications: DataSource</title> <title>Applications: <classname>DataSource</></title>
<para><productname>PostgreSQL</productname> includes two <para><productname>PostgreSQL</productname> includes two
implementations of <literal>DataSource</literal> implementations of <literal>DataSource</literal>
for <acronym>JDBC</acronym> 2, and two for <acronym>JDBC</acronym> for <acronym>JDBC</acronym> 2 and two for <acronym>JDBC</acronym>
3. The pooling implementations do not actually close connections 3, as shown in <xref linkend="jdbc-ds-ds-imp">.
The pooling implementations do not actually close connections
when the client calls the <literal>close</literal> method, but when the client calls the <literal>close</literal> method, but
instead return the connections to a pool of available connections instead return the connections to a pool of available connections
for other clients to use. This avoids any overhead of repeatedly for other clients to use. This avoids any overhead of repeatedly
opening and closing connections, and allows a large number of opening and closing connections, and allows a large number of
clients to share a small number of database connections.</para> clients to share a small number of database connections.</para>
<para>The pooling datasource implementation provided here is not <para>The pooling data-source implementation provided here is not
the most feature-rich in the world. Among other things, the most feature-rich in the world. Among other things,
connections are never closed until the pool itself is closed; connections are never closed until the pool itself is closed;
there is no way to shrink the pool. As well, connections there is no way to shrink the pool. As well, connections
requested for users other than the default configured user are requested for users other than the default configured user are
not pooled. Many application servers not pooled. Many application servers
provide more advanced pooling features, and use the provide more advanced pooling features and use the
<literal>ConnectionPoolDataSource</literal> implementation <literal>ConnectionPoolDataSource</literal> implementation
instead.</para> instead.</para>
<table>
<title>DataSource Implementations</title> <table id="jdbc-ds-ds-imp">
<title><classname>DataSource</> Implementations</title>
<tgroup cols=3> <tgroup cols=3>
<thead> <thead>
...@@ -2738,14 +2735,16 @@ serverName=localhost;databaseName=test;user=testuser;password=testpassword ...@@ -2738,14 +2735,16 @@ serverName=localhost;databaseName=test;user=testuser;password=testpassword
</tgroup> </tgroup>
</table> </table>
<para>All the implementations use the same configuration scheme. <para>
All the implementations use the same configuration scheme.
<acronym>JDBC</acronym> requires that a <acronym>JDBC</acronym> requires that a
<literal>DataSource</literal> be configured via <literal>DataSource</literal> be configured via JavaBean
JavaBean properties, so there are get and set methods for each of properties, shown in <xref linkend="jdbc-ds-ds-props">, so there
these properties.</para> are get and set methods for each of these properties.
</para>
<table> <table id="jdbc-ds-ds-props">
<title>DataSource Configuration Properties</title> <title><classname>DataSource</> Configuration Properties</title>
<tgroup cols=3> <tgroup cols=3>
<thead> <thead>
...@@ -2758,35 +2757,35 @@ serverName=localhost;databaseName=test;user=testuser;password=testpassword ...@@ -2758,35 +2757,35 @@ serverName=localhost;databaseName=test;user=testuser;password=testpassword
<tbody> <tbody>
<row> <row>
<entry>serverName</entry> <entry><literal>serverName</literal></entry>
<entry><literal>String</literal></entry> <entry><type>String</type></entry>
<entry><productname>PostgreSQL</productname> database server <entry><productname>PostgreSQL</productname> database server
hostname</entry> host name</entry>
</row> </row>
<row> <row>
<entry>databaseName</entry> <entry><literal>databaseName</literal></entry>
<entry><literal>String</literal></entry> <entry><type>String</type></entry>
<entry><productname>PostgreSQL</productname> database name</entry> <entry><productname>PostgreSQL</productname> database name</entry>
</row> </row>
<row> <row>
<entry>portNumber</entry> <entry><literal>portNumber</literal></entry>
<entry><literal>int</literal></entry> <entry><type>int</type></entry>
<entry><acronym>TCP/IP</acronym> port which the <entry>TCP port which the
<productname>PostgreSQL</productname> database server is <productname>PostgreSQL</productname> database server is
listening on (or 0 to use the default port)</entry> listening on (or 0 to use the default port)</entry>
</row> </row>
<row> <row>
<entry>user</entry> <entry><literal>user</literal></entry>
<entry><literal>String</literal></entry> <entry><type>String</type></entry>
<entry>User used to make database connections</entry> <entry>User used to make database connections</entry>
</row> </row>
<row> <row>
<entry>password</entry> <entry><literal>password</literal></entry>
<entry><literal>String</literal></entry> <entry><type>String</type></entry>
<entry>Password used to make database connections</entry> <entry>Password used to make database connections</entry>
</row> </row>
</tbody> </tbody>
...@@ -2794,10 +2793,10 @@ serverName=localhost;databaseName=test;user=testuser;password=testpassword ...@@ -2794,10 +2793,10 @@ serverName=localhost;databaseName=test;user=testuser;password=testpassword
</table> </table>
<para>The pooling implementations require some additional <para>The pooling implementations require some additional
configuration properties:</para> configuration properties, which are shown in <xref linkend="jdbc-ds-ds-xprops">.</para>
<table> <table id="jdbc-ds-ds-xprops">
<title>Additional Pooling DataSource Configuration Properties</title> <title>Additional Pooling <classname>DataSource</> Configuration Properties</title>
<tgroup cols=3> <tgroup cols=3>
<thead> <thead>
...@@ -2810,22 +2809,22 @@ serverName=localhost;databaseName=test;user=testuser;password=testpassword ...@@ -2810,22 +2809,22 @@ serverName=localhost;databaseName=test;user=testuser;password=testpassword
<tbody> <tbody>
<row> <row>
<entry>dataSourceName</entry> <entry><literal>dataSourceName</literal></entry>
<entry><literal>String</literal></entry> <entry><type>String</type></entry>
<entry>Every pooling <literal>DataSource</literal> must have a <entry>Every pooling <literal>DataSource</literal> must have a
unique name</entry> unique name.</entry>
</row> </row>
<row> <row>
<entry>initialConnections</entry> <entry><literal>initialConnections</literal></entry>
<entry><literal>int</literal></entry> <entry><type>int</type></entry>
<entry>The number of database connections to be created <entry>The number of database connections to be created
when the pool is initialized.</entry> when the pool is initialized.</entry>
</row> </row>
<row> <row>
<entry>maxConnections</entry> <entry><literal>maxConnections</literal></entry>
<entry><literal>int</literal></entry> <entry><type>int</type></entry>
<entry>The maximum number of open database connections to <entry>The maximum number of open database connections to
allow. When more connections are requested, the caller allow. When more connections are requested, the caller
will hang until a connection is returned to the pool.</entry> will hang until a connection is returned to the pool.</entry>
...@@ -2834,14 +2833,14 @@ serverName=localhost;databaseName=test;user=testuser;password=testpassword ...@@ -2834,14 +2833,14 @@ serverName=localhost;databaseName=test;user=testuser;password=testpassword
</tgroup> </tgroup>
</table> </table>
<para>Here's an example of typical application code using a <para><xref linkend="jdbc-ds-example"> shows an example of typical application code using a
pooling <literal>DataSource</literal>:</para> pooling <literal>DataSource</literal>.</para>
<example id="jdbc-ds-code"> <example id="jdbc-ds-example">
<title><literal>DataSource</literal> Code Example</title> <title><literal>DataSource</literal> Code Example</title>
<para> <para>
Code to initialize a pooling DataSource might look like this: Code to initialize a pooling <classname>DataSource</classname> might look like this:
<programlisting> <programlisting>
Jdbc3PoolingDataSource source = new Jdbc3PoolingDataSource(); Jdbc3PoolingDataSource source = new Jdbc3PoolingDataSource();
source.setDataSourceName("A Data Source"); source.setDataSourceName("A Data Source");
...@@ -2853,18 +2852,18 @@ source.setMaxConnections(10); ...@@ -2853,18 +2852,18 @@ source.setMaxConnections(10);
</programlisting> </programlisting>
Then code to use a connection from the pool might look Then code to use a connection from the pool might look
like this. Note that it is critical that the connections like this. Note that it is critical that the connections
are closed, or else the pool will "leak" connections, and are eventually closed. Else the pool will <quote>leak</> connections and
eventually lock all the clients out. will eventually lock all the clients out.
<programlisting> <programlisting>
Connection con = null; Connection con = null;
try { try {
con = source.getConnection(); con = source.getConnection();
// use connection // use connection
} catch(SQLException e) { } catch (SQLException e) {
// log error // log error
} finally { } finally {
if(con != null) { if (con != null) {
try {con.close();}catch(SQLException e) {} try { con.close(); } catch (SQLException e) {}
} }
} }
</programlisting> </programlisting>
...@@ -2873,34 +2872,44 @@ try { ...@@ -2873,34 +2872,44 @@ try {
</sect2> </sect2>
<sect2 id="jdbc-jndi"> <sect2 id="jdbc-jndi">
<title>DataSources and <acronym>JNDI</acronym></title> <title>Data Sources and <acronym>JNDI</acronym></title>
<para>All the <literal>ConnectionPoolDataSource</literal> and
<para>
All the <literal>ConnectionPoolDataSource</literal> and
<literal>DataSource</literal> implementations can be stored <literal>DataSource</literal> implementations can be stored
in <acronym>JNDI</acronym>. In the case of the non-pooling in <acronym>JNDI</acronym>. In the case of the nonpooling
implementations, a new instance will be created every time the implementations, a new instance will be created every time the
object is retrieved from <acronym>JNDI</acronym>, with the object is retrieved from <acronym>JNDI</acronym>, with the
same settings as the instance which was stored. For the same settings as the instance that was stored. For the
pooling implementations, the same instance will be retrieved pooling implementations, the same instance will be retrieved
as long as it is available (e.g. not a different as long as it is available (e.g., not a different
<acronym>JVM</acronym> retrieving the pool from <acronym>JVM</acronym> retrieving the pool from
<acronym>JNDI</acronym>), or a new instance with the same <acronym>JNDI</acronym>), or a new instance with the same
settings created otherwise.</para> settings created otherwise.
<para>In the application server environment, typically the </para>
<para>
In the application server environment, typically the
application server's <literal>DataSource</literal> instance application server's <literal>DataSource</literal> instance
will be stored in <acronym>JNDI</acronym>, instead of the will be stored in <acronym>JNDI</acronym>, instead of the
<productname>PostgreSQL</productname> <productname>PostgreSQL</productname>
<literal>ConnectionPoolDataSource</literal> implementation. <literal>ConnectionPoolDataSource</literal> implementation.
</para> </para>
<para>In an application environment, the application may store
<para>
In an application environment, the application may store
the <literal>DataSource</literal> in <acronym>JNDI</acronym> the <literal>DataSource</literal> in <acronym>JNDI</acronym>
so that it doesn't have to make a reference to the so that it doesn't have to make a reference to the
<literal>DataSource</literal> available to all application <literal>DataSource</literal> available to all application
components that may need to use it:</para> components that may need to use it. An example of this is
shown in <xref linkend="jdbc-ds-jndi">.
</para>
<example id="jdbc-ds-jndi"> <example id="jdbc-ds-jndi">
<title><literal>DataSource</literal> <acronym>JNDI</acronym> Code Example</title> <title><classname>DataSource</classname> <acronym>JNDI</acronym> Code Example</title>
<para> <para>
Application code to initialize a pooling DataSource and add Application code to initialize a pooling <classname>DataSource</classname> and add
it to <acronym>JNDI</acronym> might look like this: it to <acronym>JNDI</acronym> might look like this:
<programlisting> <programlisting>
Jdbc3PoolingDataSource source = new Jdbc3PoolingDataSource(); Jdbc3PoolingDataSource source = new Jdbc3PoolingDataSource();
...@@ -2920,13 +2929,13 @@ try { ...@@ -2920,13 +2929,13 @@ try {
DataSource source = (DataSource)new InitialContext().lookup("DataSource"); DataSource source = (DataSource)new InitialContext().lookup("DataSource");
con = source.getConnection(); con = source.getConnection();
// use connection // use connection
} catch(SQLException e) { } catch (SQLException e) {
// log error // log error
} catch(NamingException e) { } catch (NamingException e) {
// DataSource wasn't found in JNDI // DataSource wasn't found in JNDI
} finally { } finally {
if(con != null) { if (con != null) {
try {con.close();}catch(SQLException e) {} try { con.close(); } catch (SQLException e) {}
} }
} }
</programlisting> </programlisting>
...@@ -2934,30 +2943,25 @@ try { ...@@ -2934,30 +2943,25 @@ try {
</example> </example>
</sect2> </sect2>
<sect2 id="jdbc-app-servers">
<title>Specific Application Server Configurations</title>
<para>Configuration examples for specific application servers
will be included here.</para>
</sect2>
</sect1> </sect1>
<sect1 id="jdbc-reading"> <sect1 id="jdbc-reading">
<title>Further Reading</title> <title>Further Reading</title>
<para> <para>
If you have not yet read it, I'd advise you read the If you have not yet read it, you are advised you read the
<acronym>JDBC</acronym> <acronym>API</acronym> Documentation <acronym>JDBC</acronym> <acronym>API</acronym> Documentation
(supplied with Sun's <acronym>JDK</acronym>), and the (supplied with Sun's <acronym>JDK</acronym>) and the
<acronym>JDBC</acronym> Specification. Both are available from <acronym>JDBC</acronym> Specification. Both are available from
<ulink <ulink
url="http://java.sun.com/products/jdbc/index.html">http://java.sun.com/products/jdbc/index.html</ulink>. url="http://java.sun.com/products/jdbc/index.html"></ulink>.
</para> </para>
<para> <para>
<ulink <ulink
url="http://jdbc.postgresql.org">http://jdbc.postgresql.org</ulink> url="http://jdbc.postgresql.org"></ulink>
contains updated information not included in this document, and contains updated information not included in this chapter and
also includes precompiled drivers. also offers precompiled drivers.
</para> </para>
</sect1> </sect1>
</chapter> </chapter>
......
<!-- <!--
$Header: /cvsroot/pgsql/doc/src/sgml/plperl.sgml,v 2.18 2002/09/21 18:32:53 petere Exp $ $Header: /cvsroot/pgsql/doc/src/sgml/plperl.sgml,v 2.19 2003/04/07 01:29:25 petere Exp $
--> -->
<chapter id="plperl"> <chapter id="plperl">
...@@ -34,8 +34,8 @@ $Header: /cvsroot/pgsql/doc/src/sgml/plperl.sgml,v 2.18 2002/09/21 18:32:53 pete ...@@ -34,8 +34,8 @@ $Header: /cvsroot/pgsql/doc/src/sgml/plperl.sgml,v 2.18 2002/09/21 18:32:53 pete
<note> <note>
<para> <para>
Users of source packages must specially enable the build of Users of source packages must specially enable the build of
PL/Perl during the installation process (refer to the installation PL/Perl during the installation process. (Refer to the installation
instructions for more information). Users of binary packages instructions for more information.) Users of binary packages
might find PL/Perl in a separate subpackage. might find PL/Perl in a separate subpackage.
</para> </para>
</note> </note>
...@@ -57,8 +57,12 @@ CREATE FUNCTION <replaceable>funcname</replaceable> (<replaceable>argument-types ...@@ -57,8 +57,12 @@ CREATE FUNCTION <replaceable>funcname</replaceable> (<replaceable>argument-types
Arguments and results are handled as in any other Perl subroutine: Arguments and results are handled as in any other Perl subroutine:
Arguments are passed in <varname>@_</varname>, and a result value Arguments are passed in <varname>@_</varname>, and a result value
is returned with <literal>return</> or as the last expression is returned with <literal>return</> or as the last expression
evaluated in the function. For example, a function returning the evaluated in the function.
greater of two integer values could be defined as: </para>
<para>
For example, a function returning the greater of two integer values
could be defined as:
<programlisting> <programlisting>
CREATE FUNCTION perl_max (integer, integer) RETURNS integer AS ' CREATE FUNCTION perl_max (integer, integer) RETURNS integer AS '
...@@ -145,7 +149,7 @@ SELECT name, empcomp(employee) FROM employee; ...@@ -145,7 +149,7 @@ SELECT name, empcomp(employee) FROM employee;
<title>Data Values in PL/Perl</title> <title>Data Values in PL/Perl</title>
<para> <para>
The argument values supplied to a PL/Perl function's script are The argument values supplied to a PL/Perl function's code are
simply the input arguments converted to text form (just as if they simply the input arguments converted to text form (just as if they
had been displayed by a <literal>SELECT</literal> statement). had been displayed by a <literal>SELECT</literal> statement).
Conversely, the <literal>return</> command will accept any string Conversely, the <literal>return</> command will accept any string
...@@ -206,8 +210,8 @@ SELECT name, empcomp(employee) FROM employee; ...@@ -206,8 +210,8 @@ SELECT name, empcomp(employee) FROM employee;
environment. This includes file handle operations, environment. This includes file handle operations,
<literal>require</literal>, and <literal>use</literal> (for <literal>require</literal>, and <literal>use</literal> (for
external modules). There is no way to access internals of the external modules). There is no way to access internals of the
database backend process or to gain OS-level access with the database server process or to gain OS-level access with the
permissions of the <productname>PostgreSQL</productname> user ID, permissions of the server process,
as a C function can do. Thus, any unprivileged database user may as a C function can do. Thus, any unprivileged database user may
be permitted to use this language. be permitted to use this language.
</para> </para>
...@@ -227,7 +231,7 @@ CREATE FUNCTION badfunc() RETURNS integer AS ' ...@@ -227,7 +231,7 @@ CREATE FUNCTION badfunc() RETURNS integer AS '
<para> <para>
Sometimes it is desirable to write Perl functions that are not Sometimes it is desirable to write Perl functions that are not
restricted --- for example, one might want a Perl function that restricted. For example, one might want a Perl function that
sends mail. To handle these cases, PL/Perl can also be installed sends mail. To handle these cases, PL/Perl can also be installed
as an <quote>untrusted</> language (usually called as an <quote>untrusted</> language (usually called
<application>PL/PerlU</application>). In this case the full Perl language is <application>PL/PerlU</application>). In this case the full Perl language is
...@@ -255,7 +259,7 @@ CREATE FUNCTION badfunc() RETURNS integer AS ' ...@@ -255,7 +259,7 @@ CREATE FUNCTION badfunc() RETURNS integer AS '
<para> <para>
The following features are currently missing from PL/Perl, but they The following features are currently missing from PL/Perl, but they
would make welcome contributions: would make welcome contributions.
<itemizedlist> <itemizedlist>
<listitem> <listitem>
......
This source diff could not be displayed because it is too large. You can view the blob instead.
<!-- $Header: /cvsroot/pgsql/doc/src/sgml/plpython.sgml,v 1.15 2002/10/21 20:34:09 momjian Exp $ --> <!-- $Header: /cvsroot/pgsql/doc/src/sgml/plpython.sgml,v 1.16 2003/04/07 01:29:25 petere Exp $ -->
<chapter id="plpython"> <chapter id="plpython">
<title>PL/Python - Python Procedural Language</title> <title>PL/Python - Python Procedural Language</title>
...@@ -17,11 +17,18 @@ ...@@ -17,11 +17,18 @@
<literal>createlang plpython <replaceable>dbname</></literal>. <literal>createlang plpython <replaceable>dbname</></literal>.
</para> </para>
<tip>
<para>
If a language is installed into <literal>template1</>, all subsequently
created databases will have the language installed automatically.
</para>
</tip>
<note> <note>
<para> <para>
Users of source packages must specially enable the build of Users of source packages must specially enable the build of
PL/Python during the installation process (refer to the PL/Python during the installation process. (Refer to the
installation instructions for more information). Users of binary installation instructions for more information.) Users of binary
packages might find PL/Python in a separate subpackage. packages might find PL/Python in a separate subpackage.
</para> </para>
</note> </note>
...@@ -30,11 +37,11 @@ ...@@ -30,11 +37,11 @@
<title>PL/Python Functions</title> <title>PL/Python Functions</title>
<para> <para>
The Python code you write gets transformed into a function. E.g., The Python code you write gets transformed into a Python function. E.g.,
<programlisting> <programlisting>
CREATE FUNCTION myfunc(text) RETURNS text CREATE FUNCTION myfunc(text) RETURNS text
AS 'return args[0]' AS 'return args[0]'
LANGUAGE 'plpython'; LANGUAGE plpython;
</programlisting> </programlisting>
gets transformed into gets transformed into
...@@ -49,7 +56,7 @@ def __plpython_procedure_myfunc_23456(): ...@@ -49,7 +56,7 @@ def __plpython_procedure_myfunc_23456():
<para> <para>
If you do not provide a return value, Python returns the default If you do not provide a return value, Python returns the default
<symbol>None</symbol> which may or may not be what you want. The <symbol>None</symbol>. The
language module translates Python's <symbol>None</symbol> into the language module translates Python's <symbol>None</symbol> into the
SQL null value. SQL null value.
</para> </para>
...@@ -60,8 +67,8 @@ def __plpython_procedure_myfunc_23456(): ...@@ -60,8 +67,8 @@ def __plpython_procedure_myfunc_23456():
<function>myfunc</function> example, <varname>args[0]</> contains <function>myfunc</function> example, <varname>args[0]</> contains
whatever was passed in as the text argument. For whatever was passed in as the text argument. For
<literal>myfunc2(text, integer)</literal>, <varname>args[0]</> <literal>myfunc2(text, integer)</literal>, <varname>args[0]</>
would contain the <type>text</type> variable and would contain the <type>text</type> argument and
<varname>args[1]</varname> the <type>integer</type> variable. <varname>args[1]</varname> the <type>integer</type> argument.
</para> </para>
<para> <para>
...@@ -95,14 +102,14 @@ def __plpython_procedure_myfunc_23456(): ...@@ -95,14 +102,14 @@ def __plpython_procedure_myfunc_23456():
<literal>TD["level"]</> contains one of <literal>ROW</>, <literal>TD["level"]</> contains one of <literal>ROW</>,
<literal>STATEMENT</>, and <literal>UNKNOWN</>. <literal>STATEMENT</>, and <literal>UNKNOWN</>.
<literal>TD["name"]</> contains the trigger name, and <literal>TD["name"]</> contains the trigger name, and
<literal>TD["relid"]</> contains the relation ID of the table on <literal>TD["relid"]</> contains the OID of the table on
which the trigger occurred. If the trigger was called with which the trigger occurred. If the trigger was called with
arguments they are available in <literal>TD["args"][0]</> to arguments they are available in <literal>TD["args"][0]</> to
<literal>TD["args"][(n-1)]</>. <literal>TD["args"][(n-1)]</>.
</para> </para>
<para> <para>
If the <literal>TD["when"]</literal> is <literal>BEFORE</>, you may If <literal>TD["when"]</literal> is <literal>BEFORE</>, you may
return <literal>None</literal> or <literal>"OK"</literal> from the return <literal>None</literal> or <literal>"OK"</literal> from the
Python function to indicate the row is unmodified, Python function to indicate the row is unmodified,
<literal>"SKIP"</> to abort the event, or <literal>"MODIFY"</> to <literal>"SKIP"</> to abort the event, or <literal>"MODIFY"</> to
...@@ -147,10 +154,10 @@ def __plpython_procedure_myfunc_23456(): ...@@ -147,10 +154,10 @@ def __plpython_procedure_myfunc_23456():
optional limit argument causes that query to be run and the result optional limit argument causes that query to be run and the result
to be returned in a result object. The result object emulates a to be returned in a result object. The result object emulates a
list or dictionary object. The result object can be accessed by list or dictionary object. The result object can be accessed by
row number and field name. It has these additional methods: row number and column name. It has these additional methods:
<function>nrows()</function> which returns the number of rows <function>nrows</function> which returns the number of rows
returned by the query, and <function>status</function> which is the returned by the query, and <function>status</function> which is the
<function>SPI_exec</function> return variable. The result object <function>SPI_exec()</function> return value. The result object
can be modified. can be modified.
</para> </para>
...@@ -161,27 +168,27 @@ rv = plpy.execute("SELECT * FROM my_table", 5) ...@@ -161,27 +168,27 @@ rv = plpy.execute("SELECT * FROM my_table", 5)
</programlisting> </programlisting>
returns up to 5 rows from <literal>my_table</literal>. If returns up to 5 rows from <literal>my_table</literal>. If
<literal>my_table</literal> has a column <literal>my_table</literal> has a column
<literal>my_field</literal>, it would be accessed as <literal>my_column</literal>, it would be accessed as
<programlisting> <programlisting>
foo = rv[i]["my_field"] foo = rv[i]["my_column"]
</programlisting> </programlisting>
</para> </para>
<para> <para>
The second function <function>plpy.prepare</function> is called The second function, <function>plpy.prepare</function>, prepares the
with a query string and a list of argument types if you have bind execution plan for a query. It is called with a query string and a
variables in the query. For example: list of parameter types, if you have parameter references in the
query. For example:
<programlisting> <programlisting>
plan = plpy.prepare("SELECT last_name FROM my_users WHERE first_name = $1", [ "text" ]) plan = plpy.prepare("SELECT last_name FROM my_users WHERE first_name = $1", [ "text" ])
</programlisting> </programlisting>
<literal>text</literal> is the type of the variable you will be <literal>text</literal> is the type of the variable you will be
passing as <literal>$1</literal>. After preparing a statement, you passing for <literal>$1</literal>. After preparing a statement, you
use the function <function>plpy.execute</function> to run it: use the function <function>plpy.execute</function> to run it:
<programlisting> <programlisting>
rv = plpy.execute(plan, [ "name" ], 5) rv = plpy.execute(plan, [ "name" ], 5)
</programlisting> </programlisting>
The limit argument is optional in the call to The third argument is the limit and is optional.
<function>plpy.execute</function>.
</para> </para>
<para> <para>
...@@ -190,7 +197,7 @@ rv = plpy.execute(plan, [ "name" ], 5) ...@@ -190,7 +197,7 @@ rv = plpy.execute(plan, [ "name" ], 5)
in the immediate termination of that function by the server; it is in the immediate termination of that function by the server; it is
not possible to trap error conditions using Python <literal>try not possible to trap error conditions using Python <literal>try
... catch</literal> constructs. For example, a syntax error in an ... catch</literal> constructs. For example, a syntax error in an
SQL statement passed to the <literal>plpy.execute()</literal> call SQL statement passed to the <literal>plpy.execute</literal> call
will terminate the function. This behavior may be changed in a will terminate the function. This behavior may be changed in a
future release. future release.
</para> </para>
...@@ -199,22 +206,19 @@ rv = plpy.execute(plan, [ "name" ], 5) ...@@ -199,22 +206,19 @@ rv = plpy.execute(plan, [ "name" ], 5)
When you prepare a plan using the PL/Python module it is When you prepare a plan using the PL/Python module it is
automatically saved. Read the SPI documentation (<xref automatically saved. Read the SPI documentation (<xref
linkend="spi">) for a description of what this means. linkend="spi">) for a description of what this means.
</para>
<para>
In order to make effective use of this across function calls In order to make effective use of this across function calls
one needs to use one of the persistent storage dictionaries one needs to use one of the persistent storage dictionaries
<literal>SD</literal> or <literal>GD</literal>, see <literal>SD</literal> or <literal>GD</literal> (see
<xref linkend="plpython-funcs">. For example: <xref linkend="plpython-funcs">). For example:
<programlisting> <programlisting>
CREATE FUNCTION usesavedplan ( ) RETURNS TRIGGER AS ' CREATE FUNCTION usesavedplan() RETURNS trigger AS '
if SD.has_key("plan"): if SD.has_key("plan"):
plan = SD["plan"] plan = SD["plan"]
else: else:
plan = plpy.prepare("SELECT 1") plan = plpy.prepare("SELECT 1")
SD["plan"] = plan SD["plan"] = plan
# rest of function # rest of function
' LANGUAGE 'plpython'; ' LANGUAGE plpython;
</programlisting> </programlisting>
</para> </para>
</sect1> </sect1>
......
<!-- <!--
$Header: /cvsroot/pgsql/doc/src/sgml/pltcl.sgml,v 2.22 2002/09/21 18:32:53 petere Exp $ $Header: /cvsroot/pgsql/doc/src/sgml/pltcl.sgml,v 2.23 2003/04/07 01:29:25 petere Exp $
--> -->
<chapter id="pltcl"> <chapter id="pltcl">
...@@ -20,10 +20,6 @@ $Header: /cvsroot/pgsql/doc/src/sgml/pltcl.sgml,v 2.22 2002/09/21 18:32:53 peter ...@@ -20,10 +20,6 @@ $Header: /cvsroot/pgsql/doc/src/sgml/pltcl.sgml,v 2.22 2002/09/21 18:32:53 peter
trigger procedures. trigger procedures.
</para> </para>
<para>
This package was originally written by Jan Wieck.
</para>
<!-- **** PL/Tcl overview **** --> <!-- **** PL/Tcl overview **** -->
<sect1 id="pltcl-overview"> <sect1 id="pltcl-overview">
...@@ -38,19 +34,19 @@ $Header: /cvsroot/pgsql/doc/src/sgml/pltcl.sgml,v 2.22 2002/09/21 18:32:53 peter ...@@ -38,19 +34,19 @@ $Header: /cvsroot/pgsql/doc/src/sgml/pltcl.sgml,v 2.22 2002/09/21 18:32:53 peter
Tcl interpreter. In addition to the limited command set of safe Tcl, only Tcl interpreter. In addition to the limited command set of safe Tcl, only
a few commands are available to access the database via SPI and to raise a few commands are available to access the database via SPI and to raise
messages via <function>elog()</>. There is no way to access internals of the messages via <function>elog()</>. There is no way to access internals of the
database backend or to gain OS-level access under the permissions of the database server or to gain OS-level access under the permissions of the
<productname>PostgreSQL</productname> user ID, as a C function can do. <productname>PostgreSQL</productname> server process, as a C function can do.
Thus, any unprivileged database user may be Thus, any unprivileged database user may be
permitted to use this language. permitted to use this language.
</para> </para>
<para> <para>
The other, implementation restriction is that Tcl procedures cannot The other, implementation restriction is that Tcl functions cannot
be used to create input/output functions for new data types. be used to create input/output functions for new data types.
</para> </para>
<para> <para>
Sometimes it is desirable to write Tcl functions that are not restricted Sometimes it is desirable to write Tcl functions that are not restricted
to safe Tcl --- for example, one might want a Tcl function that sends to safe Tcl. For example, one might want a Tcl function that sends
mail. To handle these cases, there is a variant of <application>PL/Tcl</> called <literal>PL/TclU</> email. To handle these cases, there is a variant of <application>PL/Tcl</> called <literal>PL/TclU</>
(for untrusted Tcl). This is the exact same language except that a full (for untrusted Tcl). This is the exact same language except that a full
Tcl interpreter is used. <emphasis>If <application>PL/TclU</> is used, it must be Tcl interpreter is used. <emphasis>If <application>PL/TclU</> is used, it must be
installed as an untrusted procedural language</emphasis> so that only installed as an untrusted procedural language</emphasis> so that only
...@@ -66,7 +62,7 @@ $Header: /cvsroot/pgsql/doc/src/sgml/pltcl.sgml,v 2.22 2002/09/21 18:32:53 peter ...@@ -66,7 +62,7 @@ $Header: /cvsroot/pgsql/doc/src/sgml/pltcl.sgml,v 2.22 2002/09/21 18:32:53 peter
library directory if Tcl/Tk support is specified library directory if Tcl/Tk support is specified
in the configuration step of the installation procedure. To install in the configuration step of the installation procedure. To install
<application>PL/Tcl</> and/or <application>PL/TclU</> in a particular database, use the <application>PL/Tcl</> and/or <application>PL/TclU</> in a particular database, use the
<filename>createlang</filename> script, for example <command>createlang</command> program, for example
<literal>createlang pltcl <replaceable>dbname</></literal> or <literal>createlang pltcl <replaceable>dbname</></literal> or
<literal>createlang pltclu <replaceable>dbname</></literal>. <literal>createlang pltclu <replaceable>dbname</></literal>.
</para> </para>
...@@ -74,58 +70,59 @@ $Header: /cvsroot/pgsql/doc/src/sgml/pltcl.sgml,v 2.22 2002/09/21 18:32:53 peter ...@@ -74,58 +70,59 @@ $Header: /cvsroot/pgsql/doc/src/sgml/pltcl.sgml,v 2.22 2002/09/21 18:32:53 peter
<!-- **** PL/Tcl description **** --> <!-- **** PL/Tcl description **** -->
<sect1 id="pltcl-description"> <sect1 id="pltcl-functions">
<title>Description</title>
<sect2>
<title>PL/Tcl Functions and Arguments</title> <title>PL/Tcl Functions and Arguments</title>
<para> <para>
To create a function in the <application>PL/Tcl</> language, use the standard syntax To create a function in the <application>PL/Tcl</> language, use the standard syntax:
<programlisting> <programlisting>
CREATE FUNCTION <replaceable>funcname</replaceable> (<replaceable>argument-types</replaceable>) RETURNS <replaceable>return-type</replaceable> AS ' CREATE FUNCTION <replaceable>funcname</replaceable> (<replaceable>argument-types</replaceable>) RETURNS <replaceable>return-type</replaceable> AS '
# PL/Tcl function body # PL/Tcl function body
' LANGUAGE 'pltcl'; ' LANGUAGE pltcl;
</programlisting> </programlisting>
<application>PL/TclU</> is the same, except that the language should be specified as <application>PL/TclU</> is the same, except that the language has to be specified as
<literal>pltclu</>. <literal>pltclu</>.
</para> </para>
<para> <para>
The body of the function is simply a piece of Tcl script. The body of the function is simply a piece of Tcl script.
When the function is called, the argument values are passed as When the function is called, the argument values are passed as
variables <literal>$1</literal> ... <literal>$n</literal> to the variables <literal>$1</literal> ... <literal>$<replaceable>n</replaceable></literal> to the
Tcl script. The result is returned Tcl script. The result is returned
from the Tcl code in the usual way, with a <literal>return</literal> from the Tcl code in the usual way, with a <literal>return</literal>
statement. For example, a function statement.
</para>
<para>
For example, a function
returning the greater of two integer values could be defined as: returning the greater of two integer values could be defined as:
<programlisting> <programlisting>
CREATE FUNCTION tcl_max (integer, integer) RETURNS integer AS ' CREATE FUNCTION tcl_max(integer, integer) RETURNS integer AS '
if {$1 > $2} {return $1} if {$1 > $2} {return $1}
return $2 return $2
' LANGUAGE 'pltcl' WITH (isStrict); ' LANGUAGE pltcl STRICT;
</programlisting> </programlisting>
Note the clause <literal>WITH (isStrict)</>, which saves us from Note the clause <literal>STRICT</>, which saves us from
having to think about NULL input values: if a NULL is passed, the having to think about null input values: if a null value is passed, the
function will not be called at all, but will just return a NULL function will not be called at all, but will just return a null
result automatically. result automatically.
</para> </para>
<para> <para>
In a non-strict function, In a nonstrict function,
if the actual value of an argument is NULL, the corresponding if the actual value of an argument is null, the corresponding
<literal>$n</literal> variable will be set to an empty string. <literal>$<replaceable>n</replaceable></literal> variable will be set to an empty string.
To detect whether a particular argument is NULL, use the function To detect whether a particular argument is null, use the function
<literal>argisnull</>. For example, suppose that we wanted <function>tcl_max</function> <literal>argisnull</>. For example, suppose that we wanted <function>tcl_max</function>
with one null and one non-null argument to return the non-null with one null and one nonnull argument to return the nonnull
argument, rather than NULL: argument, rather than null:
<programlisting> <programlisting>
CREATE FUNCTION tcl_max (integer, integer) RETURNS integer AS ' CREATE FUNCTION tcl_max(integer, integer) RETURNS integer AS '
if {[argisnull 1]} { if {[argisnull 1]} {
if {[argisnull 2]} { return_null } if {[argisnull 2]} { return_null }
return $2 return $2
...@@ -133,8 +130,8 @@ CREATE FUNCTION tcl_max (integer, integer) RETURNS integer AS ' ...@@ -133,8 +130,8 @@ CREATE FUNCTION tcl_max (integer, integer) RETURNS integer AS '
if {[argisnull 2]} { return $1 } if {[argisnull 2]} { return $1 }
if {$1 > $2} {return $1} if {$1 > $2} {return $1}
return $2 return $2
' LANGUAGE 'pltcl'; ' LANGUAGE pltcl;
</programlisting> </programlisting>
</para> </para>
<para> <para>
...@@ -145,15 +142,19 @@ CREATE FUNCTION tcl_max (integer, integer) RETURNS integer AS ' ...@@ -145,15 +142,19 @@ CREATE FUNCTION tcl_max (integer, integer) RETURNS integer AS '
</para> </para>
<para> <para>
Composite-type arguments are passed to the procedure as Tcl arrays. Composite-type arguments are passed to the function as Tcl
The element names of the array are the attribute names of the composite arrays. The element names of the array are the attribute names
type. If an attribute in the passed row of the composite type. If an attribute in the passed row has the
has the NULL value, it will not appear in the array! Here is null value, it will not appear in the array. Here is an example:
an example that defines the overpaid_2 function (as found in the
older <productname>PostgreSQL</productname> documentation) in PL/Tcl: <programlisting>
CREATE TABLE employee (
<programlisting> name text,
CREATE FUNCTION overpaid_2 (EMP) RETURNS bool AS ' salary integer,
age integer
);
CREATE FUNCTION overpaid(employee) RETURNS boolean AS '
if {200000.0 < $1(salary)} { if {200000.0 < $1(salary)} {
return "t" return "t"
} }
...@@ -161,110 +162,109 @@ CREATE FUNCTION overpaid_2 (EMP) RETURNS bool AS ' ...@@ -161,110 +162,109 @@ CREATE FUNCTION overpaid_2 (EMP) RETURNS bool AS '
return "t" return "t"
} }
return "f" return "f"
' LANGUAGE 'pltcl'; ' LANGUAGE pltcl;
</programlisting> </programlisting>
</para> </para>
<para> <para>
There is not currently any support for returning a composite-type There is currently no support for returning a composite-type
result value. result value.
</para> </para>
</sect2> </sect1>
<sect2> <sect1 id="pltcl-data">
<title>Data Values in PL/Tcl</title> <title>Data Values in PL/Tcl</title>
<para> <para>
The argument values supplied to a PL/Tcl function's script are simply The argument values supplied to a PL/Tcl function's code are simply
the input arguments converted to text form (just as if they had been the input arguments converted to text form (just as if they had been
displayed by a SELECT statement). Conversely, the <literal>return</> displayed by a <command>SELECT</> statement). Conversely, the <literal>return</>
command will accept any string that is acceptable input format for command will accept any string that is acceptable input format for
the function's declared return type. So, the PL/Tcl programmer can the function's declared return type. So, the PL/Tcl programmer can
manipulate data values as if they were just text. manipulate data values as if they were just text.
</para> </para>
</sect2> </sect1>
<sect2> <sect1 id="pltcl-global">
<title>Global Data in PL/Tcl</title> <title>Global Data in PL/Tcl</title>
<para> <para>
Sometimes it Sometimes it
is useful to have some global status data that is held between two is useful to have some global data that is held between two
calls to a procedure or is shared between different procedures. calls to a function or is shared between different functions.
This is easily done since This is easily done since
all PL/Tcl procedures executed in one backend share the same all PL/Tcl functions executed in one session share the same
safe Tcl interpreter. So, any global Tcl variable is accessible to safe Tcl interpreter. So, any global Tcl variable is accessible to
all PL/Tcl procedure calls, and will persist for the duration of the all PL/Tcl function calls and will persist for the duration of the
SQL client connection. (Note that <application>PL/TclU</> functions likewise share SQL session. (Note that <application>PL/TclU</> functions likewise share
global data, but they are in a different Tcl interpreter and cannot global data, but they are in a different Tcl interpreter and cannot
communicate with PL/Tcl functions.) communicate with PL/Tcl functions.)
</para> </para>
<para> <para>
To help protect PL/Tcl procedures from unintentionally interfering To help protect PL/Tcl functions from unintentionally interfering
with each other, a global with each other, a global
array is made available to each procedure via the <function>upvar</> array is made available to each function via the <function>upvar</>
command. The global name of this variable is the procedure's internal command. The global name of this variable is the function's internal
name and the local name is <literal>GD</>. It is recommended that name, and the local name is <literal>GD</>. It is recommended that
<literal>GD</> be used <literal>GD</> be used
for private status data of a procedure. Use regular Tcl global variables for private data of a function. Use regular Tcl global variables
only for values that you specifically intend to be shared among multiple only for values that you specifically intend to be shared among multiple
procedures. functions.
</para> </para>
<para> <para>
An example of using <literal>GD</> appears in the An example of using <literal>GD</> appears in the
<function>spi_execp</function> example below. <function>spi_execp</function> example below.
</para> </para>
</sect2> </sect1>
<sect2> <sect1 id="pltcl-dbaccess">
<title>Database Access from PL/Tcl</title> <title>Database Access from PL/Tcl</title>
<para> <para>
The following commands are available to access the database from The following commands are available to access the database from
the body of a PL/Tcl procedure: the body of a PL/Tcl function:
</para>
<variablelist> <variablelist>
<varlistentry> <varlistentry>
<term><function>spi_exec</function> <literal>?-count <replaceable>n</replaceable>? ?-array <replaceable>name</replaceable>? <replaceable>query</replaceable> ?<replaceable>loop-body</replaceable>?</literal></term> <term><function>spi_exec</function> <literal>?-count <replaceable>n</replaceable>? ?-array <replaceable>name</replaceable>? <replaceable>command</replaceable> ?<replaceable>loop-body</replaceable>?</literal></term>
<listitem> <listitem>
<para> <para>
Execute an SQL query given as a string. An error in the query Executes an SQL command given as a string. An error in the command
causes an error to be raised. Otherwise, the command's return value causes an error to be raised. Otherwise, the return value of <function>spi_exec</function>
is the number of rows processed (selected, inserted, updated, or is the number of rows processed (selected, inserted, updated, or
deleted) by the query, or zero if the query is a utility deleted) by the command, or zero if the command is a utility
statement. In addition, if the query is a SELECT statement, the statement. In addition, if the command is a <command>SELECT</> statement, the
values of the selected columns are placed in Tcl variables as values of the selected columns are placed in Tcl variables as
described below. described below.
</para> </para>
<para> <para>
The optional <literal>-count</> value tells The optional <literal>-count</> value tells
<function>spi_exec</function> the maximum number of rows <function>spi_exec</function> the maximum number of rows
to process in the query. The effect of this is comparable to to process in the command. The effect of this is comparable to
setting up the query as a cursor and then saying <literal>FETCH n</>. setting up a query as a cursor and then saying <literal>FETCH <replaceable>n</></>.
</para> </para>
<para> <para>
If the query is a <literal>SELECT</> statement, the values of the statement's If the command is a <command>SELECT</> statement, the values of the
result columns are placed into Tcl variables named after the columns. result columns are placed into Tcl variables named after the columns.
If the <literal>-array</> option is given, the column values are If the <literal>-array</> option is given, the column values are
instead stored into the named associative array, with the SELECT instead stored into the named associative array, with the
column names used as array indexes. column names used as array indexes.
</para> </para>
<para> <para>
If the query is a SELECT statement and no <replaceable>loop-body</> If the command is a <command>SELECT</> statement and no <replaceable>loop-body</>
script is given, then only the first row of results are stored into script is given, then only the first row of results are stored into
Tcl variables; remaining rows, if any, are ignored. No store occurs Tcl variables; remaining rows, if any, are ignored. No storing occurs
if the if the
SELECT returns no rows (this case can be detected by checking the query returns no rows. (This case can be detected by checking the
result of <function>spi_exec</function>). For example, result of <function>spi_exec</function>.) For example,
<programlisting> <programlisting>
spi_exec "SELECT count(*) AS cnt FROM pg_proc" spi_exec "SELECT count(*) AS cnt FROM pg_proc"
</programlisting> </programlisting>
will set the Tcl variable <literal>$cnt</> to the number of rows in will set the Tcl variable <literal>$cnt</> to the number of rows in
the <structname>pg_proc</> system catalog. the <structname>pg_proc</> system catalog.
...@@ -272,23 +272,23 @@ spi_exec "SELECT count(*) AS cnt FROM pg_proc" ...@@ -272,23 +272,23 @@ spi_exec "SELECT count(*) AS cnt FROM pg_proc"
<para> <para>
If the optional <replaceable>loop-body</> argument is given, it is If the optional <replaceable>loop-body</> argument is given, it is
a piece of Tcl script that is executed once for each row in the a piece of Tcl script that is executed once for each row in the
SELECT result (note: <replaceable>loop-body</> is ignored if the given query result. (<replaceable>loop-body</> is ignored if the given
query is not a SELECT). The values of the current row's fields command is not a <command>SELECT</>.) The values of the current row's columns
are stored into Tcl variables before each iteration. For example, are stored into Tcl variables before each iteration. For example,
<programlisting> <programlisting>
spi_exec -array C "SELECT * FROM pg_class" { spi_exec -array C "SELECT * FROM pg_class" {
elog DEBUG "have table $C(relname)" elog DEBUG "have table $C(relname)"
} }
</programlisting> </programlisting>
will print a DEBUG log message for every row of pg_class. This will print a log message for every row of <literal>pg_class</>. This
feature works similarly to other Tcl looping constructs; in feature works similarly to other Tcl looping constructs; in
particular <literal>continue</> and <literal>break</> work in the particular <literal>continue</> and <literal>break</> work in the
usual way inside the loop body. usual way inside the loop body.
</para> </para>
<para> <para>
If a field of a SELECT result is NULL, the target If a column of a query result is null, the target
variable for it is <quote>unset</> rather than being set. variable for it is <quote>unset</> rather than being set.
</para> </para>
</listitem> </listitem>
...@@ -299,18 +299,18 @@ spi_exec -array C "SELECT * FROM pg_class" { ...@@ -299,18 +299,18 @@ spi_exec -array C "SELECT * FROM pg_class" {
<listitem> <listitem>
<para> <para>
Prepares and saves a query plan for later execution. The saved plan Prepares and saves a query plan for later execution. The saved plan
will be retained for the life of the current backend. will be retained for the life of the current session.
</para> </para>
<para> <para>
The query may use <firstterm>arguments</>, which are placeholders for The query may use parameters, that is, placeholders for
values to be supplied whenever the plan is actually executed. values to be supplied whenever the plan is actually executed.
In the query string, refer to arguments In the query string, refer to parameters
by the symbols <literal>$1</literal> ... <literal>$n</literal>. by the symbols <literal>$1</literal> ... <literal>$<replaceable>n</replaceable></literal>.
If the query uses arguments, the names of the argument types If the query uses parameters, the names of the parameter types
must be given as a Tcl list. (Write an empty list for must be given as a Tcl list. (Write an empty list for
<replaceable>typelist</replaceable> if no arguments are used.) <replaceable>typelist</replaceable> if no parameters are used.)
Presently, the argument types must be identified by the internal Presently, the parameter types must be identified by the internal
type names shown in pg_type; for example <literal>int4</> not type names shown in the system table <literal>pg_type</>; for example <literal>int4</> not
<literal>integer</>. <literal>integer</>.
</para> </para>
<para> <para>
...@@ -325,24 +325,24 @@ spi_exec -array C "SELECT * FROM pg_class" { ...@@ -325,24 +325,24 @@ spi_exec -array C "SELECT * FROM pg_class" {
<term><function>spi_execp</> <literal>?-count <replaceable>n</replaceable>? ?-array <replaceable>name</replaceable>? ?-nulls <replaceable>string</replaceable>? <replaceable>queryid</replaceable> ?<replaceable>value-list</replaceable>? ?<replaceable>loop-body</replaceable>?</literal></term> <term><function>spi_execp</> <literal>?-count <replaceable>n</replaceable>? ?-array <replaceable>name</replaceable>? ?-nulls <replaceable>string</replaceable>? <replaceable>queryid</replaceable> ?<replaceable>value-list</replaceable>? ?<replaceable>loop-body</replaceable>?</literal></term>
<listitem> <listitem>
<para> <para>
Execute a query previously prepared with <function>spi_prepare</>. Executes a query previously prepared with <function>spi_prepare</>.
<replaceable>queryid</replaceable> is the ID returned by <replaceable>queryid</replaceable> is the ID returned by
<function>spi_prepare</>. If the query references arguments, <function>spi_prepare</>. If the query references parameters,
a <replaceable>value-list</replaceable> must be supplied: this a <replaceable>value-list</replaceable> must be supplied. This
is a Tcl list of actual values for the arguments. This must be is a Tcl list of actual values for the parameters. The list must be
the same length as the argument type list previously given to the same length as the parameter type list previously given to
<function>spi_prepare</>. Omit <replaceable>value-list</replaceable> <function>spi_prepare</>. Omit <replaceable>value-list</replaceable>
if the query has no arguments. if the query has no parameters.
</para> </para>
<para> <para>
The optional value for <literal>-nulls</> is a string of spaces and The optional value for <literal>-nulls</> is a string of spaces and
<literal>'n'</> characters telling <function>spi_execp</function> <literal>'n'</> characters telling <function>spi_execp</function>
which of the arguments are null values. If given, it must have exactly the which of the parameters are null values. If given, it must have exactly the
same length as the <replaceable>value-list</replaceable>. If it same length as the <replaceable>value-list</replaceable>. If it
is not given, all the argument values are non-NULL. is not given, all the parameter values are nonnull.
</para> </para>
<para> <para>
Except for the way in which the query and its arguments are specified, Except for the way in which the query and its parameters are specified,
<function>spi_execp</> works just like <function>spi_exec</>. <function>spi_execp</> works just like <function>spi_exec</>.
The <literal>-count</>, <literal>-array</>, and The <literal>-count</>, <literal>-array</>, and
<replaceable>loop-body</replaceable> options are the same, <replaceable>loop-body</replaceable> options are the same,
...@@ -351,7 +351,7 @@ spi_exec -array C "SELECT * FROM pg_class" { ...@@ -351,7 +351,7 @@ spi_exec -array C "SELECT * FROM pg_class" {
<para> <para>
Here's an example of a PL/Tcl function using a prepared plan: Here's an example of a PL/Tcl function using a prepared plan:
<programlisting> <programlisting>
CREATE FUNCTION t1_count(integer, integer) RETURNS integer AS ' CREATE FUNCTION t1_count(integer, integer) RETURNS integer AS '
if {![ info exists GD(plan) ]} { if {![ info exists GD(plan) ]} {
# prepare the saved plan on the first call # prepare the saved plan on the first call
...@@ -361,14 +361,14 @@ CREATE FUNCTION t1_count(integer, integer) RETURNS integer AS ' ...@@ -361,14 +361,14 @@ CREATE FUNCTION t1_count(integer, integer) RETURNS integer AS '
} }
spi_execp -count 1 $GD(plan) [ list $1 $2 ] spi_execp -count 1 $GD(plan) [ list $1 $2 ]
return $cnt return $cnt
' LANGUAGE 'pltcl'; ' LANGUAGE pltcl;
</programlisting> </programlisting>
Note that each backslash that Tcl should see must be doubled when Note that each backslash that Tcl should see must be doubled when
we type in the function, since the main parser processes we type in the function, since the main parser processes
backslashes too in CREATE FUNCTION. We need backslashes inside backslashes, too, in <command>CREATE FUNCTION</>. We need backslashes inside
the query string given to <function>spi_prepare</> to ensure that the query string given to <function>spi_prepare</> to ensure that
the <literal>$n</> markers will be passed through to the <literal>$<replaceable>n</replaceable></> markers will be passed through to
<function>spi_prepare</> as-is, and not <function>spi_prepare</> as-is, and not
replaced by Tcl variable substitution. replaced by Tcl variable substitution.
</para> </para>
...@@ -383,8 +383,8 @@ CREATE FUNCTION t1_count(integer, integer) RETURNS integer AS ' ...@@ -383,8 +383,8 @@ CREATE FUNCTION t1_count(integer, integer) RETURNS integer AS '
<listitem> <listitem>
<para> <para>
Returns the OID of the row inserted by the last Returns the OID of the row inserted by the last
<function>spi_exec</>'d or <function>spi_execp</>'d query, <function>spi_exec</> or <function>spi_execp</>,
if that query was a single-row INSERT. (If not, you get zero.) if the command was a single-row <command>INSERT</>. (If not, you get zero.)
</para> </para>
</listitem> </listitem>
</varlistentry> </varlistentry>
...@@ -395,18 +395,18 @@ CREATE FUNCTION t1_count(integer, integer) RETURNS integer AS ' ...@@ -395,18 +395,18 @@ CREATE FUNCTION t1_count(integer, integer) RETURNS integer AS '
<para> <para>
Duplicates all occurrences of single quote and backslash characters Duplicates all occurrences of single quote and backslash characters
in the given string. This may be used to safely quote strings in the given string. This may be used to safely quote strings
that are to be inserted into SQL queries given that are to be inserted into SQL commands given
to <function>spi_exec</function> or to <function>spi_exec</function> or
<function>spi_prepare</function>. <function>spi_prepare</function>.
For example, think about a query string like For example, think about an SQL command string like
<programlisting> <programlisting>
"SELECT '$val' AS ret" "SELECT '$val' AS ret"
</programlisting> </programlisting>
where the Tcl variable val actually contains where the Tcl variable <literal>val</> actually contains
<literal>doesn't</literal>. This would result <literal>doesn't</literal>. This would result
in the final query string in the final command string
<programlisting> <programlisting>
SELECT 'doesn't' AS ret SELECT 'doesn't' AS ret
...@@ -415,21 +415,21 @@ SELECT 'doesn't' AS ret ...@@ -415,21 +415,21 @@ SELECT 'doesn't' AS ret
which would cause a parse error during which would cause a parse error during
<function>spi_exec</function> or <function>spi_exec</function> or
<function>spi_prepare</function>. <function>spi_prepare</function>.
The submitted query should contain The submitted command should contain
<programlisting> <programlisting>
SELECT 'doesn''t' AS ret SELECT 'doesn''t' AS ret
</programlisting> </programlisting>
which can be formed in PL/Tcl as which can be formed in PL/Tcl using
<programlisting> <programlisting>
"SELECT '[ quote $val ]' AS ret" "SELECT '[ quote $val ]' AS ret"
</programlisting> </programlisting>
One advantage of <function>spi_execp</function> is that you don't One advantage of <function>spi_execp</function> is that you don't
have to quote argument values like this, since the arguments are never have to quote parameter values like this, since the parameters are never
parsed as part of an SQL query string. parsed as part of an SQL command string.
</para> </para>
</listitem> </listitem>
</varlistentry> </varlistentry>
...@@ -441,26 +441,27 @@ SELECT 'doesn''t' AS ret ...@@ -441,26 +441,27 @@ SELECT 'doesn''t' AS ret
<term><function>elog</> <replaceable>level</replaceable> <replaceable>msg</replaceable></term> <term><function>elog</> <replaceable>level</replaceable> <replaceable>msg</replaceable></term>
<listitem> <listitem>
<para> <para>
Emit a log or error message. Possible levels are Emits a log or error message. Possible levels are
<literal>DEBUG</>, <literal>LOG</>, <literal>INFO</>, <literal>DEBUG</>, <literal>LOG</>, <literal>INFO</>,
<literal>NOTICE</>, <literal>WARNING</>, <literal>ERROR</>, and <literal>NOTICE</>, <literal>WARNING</>, <literal>ERROR</>, and
<literal>FATAL</>. Most simply emit the given message just like <literal>FATAL</>. Most simply emit the given message just like
the <literal>elog</> backend C function. <literal>ERROR</> the <literal>elog</> C function. <literal>ERROR</>
raises an error condition: further execution of the function is raises an error condition: further execution of the function is
abandoned, and the current transaction is aborted. abandoned, and the current transaction is aborted.
<literal>FATAL</> aborts the transaction and causes the current <literal>FATAL</> aborts the transaction and causes the current
backend to shut down (there is probably no good reason to use session to shut down. (There is probably no good reason to use
this error level in PL/Tcl functions, but it's provided for this error level in PL/Tcl functions, but it's provided for
completeness). completeness.)
</para> </para>
</listitem> </listitem>
</varlistentry> </varlistentry>
</variablelist> </variablelist>
</para>
</sect2> </sect1>
<sect2> <sect1 id="pltcl-trigger">
<title>Trigger Procedures in PL/Tcl</title> <title>Trigger Procedures in PL/Tcl</title>
<indexterm> <indexterm>
...@@ -469,8 +470,8 @@ SELECT 'doesn''t' AS ret ...@@ -469,8 +470,8 @@ SELECT 'doesn''t' AS ret
</indexterm> </indexterm>
<para> <para>
Trigger procedures can be written in PL/Tcl. As is customary in Trigger procedures can be written in PL/Tcl.
<productname>PostgreSQL</productname>, a procedure that's to be called <productname>PostgreSQL</productname> requires that a procedure that is to be called
as a trigger must be declared as a function with no arguments as a trigger must be declared as a function with no arguments
and a return type of <literal>trigger</>. and a return type of <literal>trigger</>.
</para> </para>
...@@ -481,16 +482,16 @@ SELECT 'doesn''t' AS ret ...@@ -481,16 +482,16 @@ SELECT 'doesn''t' AS ret
<variablelist> <variablelist>
<varlistentry> <varlistentry>
<term><replaceable class="Parameter">$TG_name</replaceable></term> <term><varname>$TG_name</varname></term>
<listitem> <listitem>
<para> <para>
The name of the trigger from the CREATE TRIGGER statement. The name of the trigger from the <command>CREATE TRIGGER</command> statement.
</para> </para>
</listitem> </listitem>
</varlistentry> </varlistentry>
<varlistentry> <varlistentry>
<term><replaceable class="Parameter">$TG_relid</replaceable></term> <term><varname>$TG_relid</varname></term>
<listitem> <listitem>
<para> <para>
The object ID of the table that caused the trigger procedure The object ID of the table that caused the trigger procedure
...@@ -500,20 +501,20 @@ SELECT 'doesn''t' AS ret ...@@ -500,20 +501,20 @@ SELECT 'doesn''t' AS ret
</varlistentry> </varlistentry>
<varlistentry> <varlistentry>
<term><replaceable class="Parameter">$TG_relatts</replaceable></term> <term><varname>$TG_relatts</varname></term>
<listitem> <listitem>
<para> <para>
A Tcl list of the table field names, prefixed with an empty list A Tcl list of the table column names, prefixed with an empty list
element. So looking up an element name in the list with <application>Tcl</>'s element. So looking up a column name in the list with <application>Tcl</>'s
<function>lsearch</> command returns the element's number starting <function>lsearch</> command returns the element's number starting
with 1 for the first column, the same way the fields are customarily with 1 for the first column, the same way the columns are customarily
numbered in <productname>PostgreSQL</productname>. numbered in <productname>PostgreSQL</productname>.
</para> </para>
</listitem> </listitem>
</varlistentry> </varlistentry>
<varlistentry> <varlistentry>
<term><replaceable class="Parameter">$TG_when</replaceable></term> <term><varname>$TG_when</varname></term>
<listitem> <listitem>
<para> <para>
The string <literal>BEFORE</> or <literal>AFTER</> depending on the The string <literal>BEFORE</> or <literal>AFTER</> depending on the
...@@ -523,7 +524,7 @@ SELECT 'doesn''t' AS ret ...@@ -523,7 +524,7 @@ SELECT 'doesn''t' AS ret
</varlistentry> </varlistentry>
<varlistentry> <varlistentry>
<term><replaceable class="Parameter">$TG_level</replaceable></term> <term><varname>$TG_level</varname></term>
<listitem> <listitem>
<para> <para>
The string <literal>ROW</> or <literal>STATEMENT</> depending on the The string <literal>ROW</> or <literal>STATEMENT</> depending on the
...@@ -533,44 +534,46 @@ SELECT 'doesn''t' AS ret ...@@ -533,44 +534,46 @@ SELECT 'doesn''t' AS ret
</varlistentry> </varlistentry>
<varlistentry> <varlistentry>
<term><replaceable class="Parameter">$TG_op</replaceable></term> <term><varname>$TG_op</varname></term>
<listitem> <listitem>
<para> <para>
The string <literal>INSERT</>, <literal>UPDATE</> or The string <literal>INSERT</>, <literal>UPDATE</>, or
<literal>DELETE</> depending on the type of trigger call. <literal>DELETE</> depending on the type of trigger call.
</para> </para>
</listitem> </listitem>
</varlistentry> </varlistentry>
<varlistentry> <varlistentry>
<term><replaceable class="Parameter">$NEW</replaceable></term> <term><varname>$NEW</varname></term>
<listitem> <listitem>
<para> <para>
An associative array containing the values of the new table row for An associative array containing the values of the new table
INSERT/UPDATE actions, or empty for DELETE. The array is indexed row for <command>INSERT</> or <command>UPDATE</> actions, or
by field name. Fields that are NULL will not appear in the array! empty for <command>DELETE</>. The array is indexed by column
name. Columns that are null will not appear in the array.
</para> </para>
</listitem> </listitem>
</varlistentry> </varlistentry>
<varlistentry> <varlistentry>
<term><replaceable class="Parameter">$OLD</replaceable></term> <term><varname>$OLD</varname></term>
<listitem> <listitem>
<para> <para>
An associative array containing the values of the old table row for An associative array containing the values of the old table
UPDATE/DELETE actions, or empty for INSERT. The array is indexed row for <command>UPDATE</> or <command>DELETE</> actions, or
by field name. Fields that are NULL will not appear in the array! empty for <command>INSERT</>. The array is indexed by column
name. Columns that are null will not appear in the array.
</para> </para>
</listitem> </listitem>
</varlistentry> </varlistentry>
<varlistentry> <varlistentry>
<term><replaceable class="Parameter">$args</replaceable></term> <term><varname>$args</varname></term>
<listitem> <listitem>
<para> <para>
A Tcl list of the arguments to the procedure as given in the A Tcl list of the arguments to the procedure as given in the
CREATE TRIGGER statement. These arguments are also accessible as <command>CREATE TRIGGER</command> statement. These arguments are also accessible as
<literal>$1</literal> ... <literal>$n</literal> in the procedure body. <literal>$1</literal> ... <literal>$<replaceable>n</replaceable></literal> in the procedure body.
</para> </para>
</listitem> </listitem>
</varlistentry> </varlistentry>
...@@ -582,22 +585,22 @@ SELECT 'doesn''t' AS ret ...@@ -582,22 +585,22 @@ SELECT 'doesn''t' AS ret
The return value from a trigger procedure can be one of the strings The return value from a trigger procedure can be one of the strings
<literal>OK</> or <literal>SKIP</>, or a list as returned by the <literal>OK</> or <literal>SKIP</>, or a list as returned by the
<literal>array get</> Tcl command. If the return value is <literal>OK</>, <literal>array get</> Tcl command. If the return value is <literal>OK</>,
the operation (INSERT/UPDATE/DELETE) that fired the trigger will proceed the operation (<command>INSERT</>/<command>UPDATE</>/<command>DELETE</>) that fired the trigger will proceed
normally. <literal>SKIP</> tells the trigger manager to silently suppress normally. <literal>SKIP</> tells the trigger manager to silently suppress
the operation for this row. If a list is returned, it tells PL/Tcl to the operation for this row. If a list is returned, it tells PL/Tcl to
return a modified row to the trigger manager that will be inserted return a modified row to the trigger manager that will be inserted
instead of the one given in $NEW (this works for INSERT/UPDATE instead of the one given in <varname>$NEW</>. (This works for <command>INSERT</> and <command>UPDATE</>
only). Needless to say that all this is only meaningful when the trigger only.) Needless to say that all this is only meaningful when the trigger
is BEFORE and FOR EACH ROW; otherwise the return value is ignored. is <literal>BEFORE</> and <command>FOR EACH ROW</>; otherwise the return value is ignored.
</para> </para>
<para> <para>
Here's a little example trigger procedure that forces an integer value Here's a little example trigger procedure that forces an integer value
in a table to keep track of the number of updates that are performed on the in a table to keep track of the number of updates that are performed on the
row. For new rows inserted, the value is initialized to 0 and then row. For new rows inserted, the value is initialized to 0 and then
incremented on every update operation: incremented on every update operation.
<programlisting> <programlisting>
CREATE FUNCTION trigfunc_modcount() RETURNS TRIGGER AS ' CREATE FUNCTION trigfunc_modcount() RETURNS trigger AS '
switch $TG_op { switch $TG_op {
INSERT { INSERT {
set NEW($1) 0 set NEW($1) 0
...@@ -611,24 +614,24 @@ CREATE FUNCTION trigfunc_modcount() RETURNS TRIGGER AS ' ...@@ -611,24 +614,24 @@ CREATE FUNCTION trigfunc_modcount() RETURNS TRIGGER AS '
} }
} }
return [array get NEW] return [array get NEW]
' LANGUAGE 'pltcl'; ' LANGUAGE pltcl;
CREATE TABLE mytab (num integer, description text, modcnt integer); CREATE TABLE mytab (num integer, description text, modcnt integer);
CREATE TRIGGER trig_mytab_modcount BEFORE INSERT OR UPDATE ON mytab CREATE TRIGGER trig_mytab_modcount BEFORE INSERT OR UPDATE ON mytab
FOR EACH ROW EXECUTE PROCEDURE trigfunc_modcount('modcnt'); FOR EACH ROW EXECUTE PROCEDURE trigfunc_modcount('modcnt');
</programlisting> </programlisting>
Notice that the trigger procedure itself does not know the column Notice that the trigger procedure itself does not know the column
name; that's supplied from the trigger arguments. This lets the name; that's supplied from the trigger arguments. This lets the
trigger procedure be re-used with different tables. trigger procedure be reused with different tables.
</para> </para>
</sect2> </sect1>
<sect2> <sect1 id="pltcl-unknown">
<title> Modules and the <function>unknown</> command</title> <title>Modules and the <function>unknown</> command</title>
<para> <para>
PL/Tcl has support for auto-loading Tcl code when used. PL/Tcl has support for autoloading Tcl code when used.
It recognizes a special table, <literal>pltcl_modules</>, which It recognizes a special table, <literal>pltcl_modules</>, which
is presumed to contain modules of Tcl code. If this table is presumed to contain modules of Tcl code. If this table
exists, the module <literal>unknown</> is fetched from the table exists, the module <literal>unknown</> is fetched from the table
...@@ -638,7 +641,7 @@ CREATE TRIGGER trig_mytab_modcount BEFORE INSERT OR UPDATE ON mytab ...@@ -638,7 +641,7 @@ CREATE TRIGGER trig_mytab_modcount BEFORE INSERT OR UPDATE ON mytab
<para> <para>
While the <literal>unknown</> module could actually contain any While the <literal>unknown</> module could actually contain any
initialization script you need, it normally defines a Tcl initialization script you need, it normally defines a Tcl
<quote>unknown</> procedure that is invoked whenever Tcl does <function>unknown</> procedure that is invoked whenever Tcl does
not recognize an invoked procedure name. <application>PL/Tcl</>'s standard version not recognize an invoked procedure name. <application>PL/Tcl</>'s standard version
of this procedure tries to find a module in <literal>pltcl_modules</> of this procedure tries to find a module in <literal>pltcl_modules</>
that will define the required procedure. If one is found, it is that will define the required procedure. If one is found, it is
...@@ -653,7 +656,7 @@ CREATE TRIGGER trig_mytab_modcount BEFORE INSERT OR UPDATE ON mytab ...@@ -653,7 +656,7 @@ CREATE TRIGGER trig_mytab_modcount BEFORE INSERT OR UPDATE ON mytab
support scripts to maintain these tables: support scripts to maintain these tables:
<command>pltcl_loadmod</>, <command>pltcl_listmod</>, <command>pltcl_loadmod</>, <command>pltcl_listmod</>,
<command>pltcl_delmod</>, as well as source for the standard <command>pltcl_delmod</>, as well as source for the standard
unknown module <filename>share/unknown.pltcl</>. This module <literal>unknown</> module in <filename>share/unknown.pltcl</>. This module
must be loaded must be loaded
into each database initially to support the autoloading mechanism. into each database initially to support the autoloading mechanism.
</para> </para>
...@@ -662,9 +665,9 @@ CREATE TRIGGER trig_mytab_modcount BEFORE INSERT OR UPDATE ON mytab ...@@ -662,9 +665,9 @@ CREATE TRIGGER trig_mytab_modcount BEFORE INSERT OR UPDATE ON mytab
must be readable by all, but it is wise to make them owned and must be readable by all, but it is wise to make them owned and
writable only by the database administrator. writable only by the database administrator.
</para> </para>
</sect2> </sect1>
<sect2> <sect1 id="pltcl-procnames">
<title>Tcl Procedure Names</title> <title>Tcl Procedure Names</title>
<para> <para>
...@@ -674,16 +677,14 @@ CREATE TRIGGER trig_mytab_modcount BEFORE INSERT OR UPDATE ON mytab ...@@ -674,16 +677,14 @@ CREATE TRIGGER trig_mytab_modcount BEFORE INSERT OR UPDATE ON mytab
differ. Tcl, however, requires all procedure names to be distinct. differ. Tcl, however, requires all procedure names to be distinct.
PL/Tcl deals with this by making the internal Tcl procedure names contain PL/Tcl deals with this by making the internal Tcl procedure names contain
the object the object
ID of the procedure's <structname>pg_proc</> row as part of their name. Thus, ID of the function from the system table <structname>pg_proc</> as part of their name. Thus,
<productname>PostgreSQL</productname> functions with the same name <productname>PostgreSQL</productname> functions with the same name
and different argument types will be different Tcl procedures too. This and different argument types will be different Tcl procedures, too. This
is not normally a concern for a PL/Tcl programmer, but it might be visible is not normally a concern for a PL/Tcl programmer, but it might be visible
when debugging. when debugging.
</para> </para>
</sect2> </sect1>
</sect1>
</chapter> </chapter>
<!-- Keep this comment at the end of the file <!-- Keep this comment at the end of the file
......
<!-- $Header: /cvsroot/pgsql/doc/src/sgml/Attic/pygresql.sgml,v 1.9 2002/12/12 22:49:27 momjian Exp $ --> <!-- $Header: /cvsroot/pgsql/doc/src/sgml/Attic/pygresql.sgml,v 1.10 2003/04/07 01:29:25 petere Exp $ -->
<chapter id="pygresql"> <chapter id="pygresql">
<title><application>PyGreSQL</application> - <application>Python</application> Interface</title> <title><application>PyGreSQL</application> - <application>Python</application> Interface</title>
...@@ -334,13 +334,10 @@ make && make install ...@@ -334,13 +334,10 @@ make && make install
<acronym>API</acronym> at <ulink <acronym>API</acronym> at <ulink
url="http://www.python.org/topics/database/DatabaseAPI-2.0.html" url="http://www.python.org/topics/database/DatabaseAPI-2.0.html"
>http://www.python.org/topics/database/DatabaseAPI-2.0.html</ulink>. >http://www.python.org/topics/database/DatabaseAPI-2.0.html</ulink>.
</para>
<para>
A tutorial-like introduction to the <acronym>DB-API</acronym> can be A tutorial-like introduction to the <acronym>DB-API</acronym> can be
found at <ulink found at <ulink
url="http://www2.linuxjournal.com/lj-issues/issue49/2605.html" url="http://www2.linuxjournal.com/lj-issues/issue49/2605.html"
>http://www2.linuxjournal.com/lj-issues/issue49/2605.html</ulink> >http://www2.linuxjournal.com/lj-issues/issue49/2605.html</ulink>.
</para> </para>
<sect1 id="pygresql-pg"> <sect1 id="pygresql-pg">
...@@ -365,16 +362,15 @@ make && make install ...@@ -365,16 +362,15 @@ make && make install
<listitem> <listitem>
<para> <para>
<classname>pgqueryobject</classname> that handles query results. <classname>pgqueryobject</classname>, which handles query results.
</para> </para>
</listitem> </listitem>
</itemizedlist> </itemizedlist>
</para> </para>
<para> <para>
If you want to see a simple example of the use of some of these If you want to see a simple example of the use this module,
functions, see <ulink url="http://www.druid.net/rides" see <ulink url="http://www.druid.net/rides"></ulink> where you can find a link at the
>http://www.druid.net/rides</ulink> where you can find a link at the
bottom to the actual <application>Python</application> code for the bottom to the actual <application>Python</application> code for the
page. page.
</para> </para>
...@@ -395,9 +391,9 @@ make && make install ...@@ -395,9 +391,9 @@ make && make install
<term><varname>INV_WRITE</varname></term> <term><varname>INV_WRITE</varname></term>
<listitem> <listitem>
<para> <para>
large objects access modes, used by Large objects access modes, used by
<function>(pgobject.)locreate</function> and <function>(pgobject.)locreate</function> and
<function>(pglarge.)open</function>. <function>(pglarge.)open</function>
</para> </para>
</listitem> </listitem>
</varlistentry> </varlistentry>
...@@ -408,7 +404,7 @@ make && make install ...@@ -408,7 +404,7 @@ make && make install
<term><varname>SEEK_END</varname></term> <term><varname>SEEK_END</varname></term>
<listitem> <listitem>
<para> <para>
positional flags, used by <function>(pglarge.)seek</function>. Positional flags, used by <function>(pglarge.)seek</function>
</para> </para>
</listitem> </listitem>
</varlistentry> </varlistentry>
...@@ -418,7 +414,7 @@ make && make install ...@@ -418,7 +414,7 @@ make && make install
<term><varname>__version__</varname></term> <term><varname>__version__</varname></term>
<listitem> <listitem>
<para> <para>
constants that give the current version Constants that give the current version
</para> </para>
</listitem> </listitem>
</varlistentry> </varlistentry>
...@@ -443,13 +439,13 @@ make && make install ...@@ -443,13 +439,13 @@ make && make install
to handle general connection parameters without heavy code in your to handle general connection parameters without heavy code in your
programs. You can prompt the user for a value, put it in the programs. You can prompt the user for a value, put it in the
default variable, and forget it, without having to modify your default variable, and forget it, without having to modify your
environment. The support for default variables can be disabled by environment. The support for default variables can be disabled at build time by
setting the <option>-DNO_DEF_VAR</option> option in the Python setting the <option>-DNO_DEF_VAR</option> option in the Python
<filename>Setup</> file. Methods relative to this are specified by the tag [DV]. <filename>Setup</> file. Methods relative to this are specified by the tag [DV].
</para> </para>
<para> <para>
All variables are set to <symbol>None</symbol> at module All default values are set to <symbol>None</symbol> at module
initialization, specifying that standard environment variables initialization, specifying that standard environment variables
should be used. should be used.
</para> </para>
...@@ -478,7 +474,7 @@ connect(<optional><parameter>dbname</parameter></optional>, <optional><parameter ...@@ -478,7 +474,7 @@ connect(<optional><parameter>dbname</parameter></optional>, <optional><parameter
<term><parameter>dbname</parameter></term> <term><parameter>dbname</parameter></term>
<listitem> <listitem>
<para>Name of connected database (string/<symbol>None</>).</para> <para>Name of connected database (string/<symbol>None</>)</para>
</listitem> </listitem>
</varlistentry> </varlistentry>
...@@ -486,7 +482,7 @@ connect(<optional><parameter>dbname</parameter></optional>, <optional><parameter ...@@ -486,7 +482,7 @@ connect(<optional><parameter>dbname</parameter></optional>, <optional><parameter
<term><parameter>host</parameter></term> <term><parameter>host</parameter></term>
<listitem> <listitem>
<para>Name of the server host (string/<symbol>None</>).</para> <para>Name of the server host (string/<symbol>None</>)</para>
</listitem> </listitem>
</varlistentry> </varlistentry>
...@@ -494,7 +490,7 @@ connect(<optional><parameter>dbname</parameter></optional>, <optional><parameter ...@@ -494,7 +490,7 @@ connect(<optional><parameter>dbname</parameter></optional>, <optional><parameter
<term><parameter>port</parameter></term> <term><parameter>port</parameter></term>
<listitem> <listitem>
<para>Port used by the database server (integer/-1).</para> <para>Port used by the database server (integer/-1)</para>
</listitem> </listitem>
</varlistentry> </varlistentry>
...@@ -503,7 +499,7 @@ connect(<optional><parameter>dbname</parameter></optional>, <optional><parameter ...@@ -503,7 +499,7 @@ connect(<optional><parameter>dbname</parameter></optional>, <optional><parameter
<listitem> <listitem>
<para> <para>
Options for the server (string/<symbol>None</>). Options for the server (string/<symbol>None</>)
</para> </para>
</listitem> </listitem>
</varlistentry> </varlistentry>
...@@ -513,8 +509,8 @@ connect(<optional><parameter>dbname</parameter></optional>, <optional><parameter ...@@ -513,8 +509,8 @@ connect(<optional><parameter>dbname</parameter></optional>, <optional><parameter
<listitem> <listitem>
<para> <para>
File or tty for optional debug output from backend File or TTY for optional debug output from server
(string/<symbol>None</>). (string/<symbol>None</>)
</para> </para>
</listitem> </listitem>
</varlistentry> </varlistentry>
...@@ -524,7 +520,7 @@ connect(<optional><parameter>dbname</parameter></optional>, <optional><parameter ...@@ -524,7 +520,7 @@ connect(<optional><parameter>dbname</parameter></optional>, <optional><parameter
<listitem> <listitem>
<para> <para>
<productname>PostgreSQL</productname> user (string/<symbol>None</>). <productname>PostgreSQL</productname> user (string/<symbol>None</>)
</para> </para>
</listitem> </listitem>
</varlistentry> </varlistentry>
...@@ -533,7 +529,7 @@ connect(<optional><parameter>dbname</parameter></optional>, <optional><parameter ...@@ -533,7 +529,7 @@ connect(<optional><parameter>dbname</parameter></optional>, <optional><parameter
<term><parameter>passwd</parameter></term> <term><parameter>passwd</parameter></term>
<listitem> <listitem>
<para>Password for user (string/<symbol>None</>).</para> <para>Password for user (string/<symbol>None</>)</para>
</listitem> </listitem>
</varlistentry> </varlistentry>
</variablelist> </variablelist>
...@@ -601,12 +597,11 @@ connect(<optional><parameter>dbname</parameter></optional>, <optional><parameter ...@@ -601,12 +597,11 @@ connect(<optional><parameter>dbname</parameter></optional>, <optional><parameter
<para> <para>
This method opens a connection to a specified database on a given This method opens a connection to a specified database on a given
<productname>PostgreSQL</productname> server. You can use <productname>PostgreSQL</productname> server. The arguments can be
key words here, as described in the given using key words here. The names of the
<application>Python</application> tutorial. The names of the
key words are the name of the parameters given in the syntax key words are the name of the parameters given in the syntax
line. For a precise description of the parameters, please refer line. For a precise description of the parameters, please refer
to the <productname>PostgreSQL</productname> user manual. to <xref linkend="libpq">.
</para> </para>
</refsect1> </refsect1>
......
<!-- <!--
$Header: /cvsroot/pgsql/doc/src/sgml/xplang.sgml,v 1.20 2003/01/31 00:10:51 tgl Exp $ $Header: /cvsroot/pgsql/doc/src/sgml/xplang.sgml,v 1.21 2003/04/07 01:29:26 petere Exp $
--> -->
<chapter id="xplang"> <chapter id="xplang">
<title id="xplang-title">Procedural Languages</title> <title id="xplang-title">Procedural Languages</title>
<sect1 id="xplang-intro">
<title>Introduction</title>
<para> <para>
<productname>PostgreSQL</productname> allows users to add new <productname>PostgreSQL</productname> allows users to add new
programming languages to be available for writing functions and programming languages to be available for writing functions and
...@@ -21,7 +18,7 @@ $Header: /cvsroot/pgsql/doc/src/sgml/xplang.sgml,v 1.20 2003/01/31 00:10:51 tgl ...@@ -21,7 +18,7 @@ $Header: /cvsroot/pgsql/doc/src/sgml/xplang.sgml,v 1.20 2003/01/31 00:10:51 tgl
could serve as <quote>glue</quote> between could serve as <quote>glue</quote> between
<productname>PostgreSQL</productname> and an existing implementation <productname>PostgreSQL</productname> and an existing implementation
of a programming language. The handler itself is a special of a programming language. The handler itself is a special
programming language function compiled into a shared object and C language function compiled into a shared object and
loaded on demand. loaded on demand.
</para> </para>
...@@ -31,7 +28,6 @@ $Header: /cvsroot/pgsql/doc/src/sgml/xplang.sgml,v 1.20 2003/01/31 00:10:51 tgl ...@@ -31,7 +28,6 @@ $Header: /cvsroot/pgsql/doc/src/sgml/xplang.sgml,v 1.20 2003/01/31 00:10:51 tgl
available in the standard <productname>PostgreSQL</productname> available in the standard <productname>PostgreSQL</productname>
distribution, which can serve as examples. distribution, which can serve as examples.
</para> </para>
</sect1>
<sect1 id="xplang-install"> <sect1 id="xplang-install">
<title>Installing Procedural Languages</title> <title>Installing Procedural Languages</title>
...@@ -39,22 +35,24 @@ $Header: /cvsroot/pgsql/doc/src/sgml/xplang.sgml,v 1.20 2003/01/31 00:10:51 tgl ...@@ -39,22 +35,24 @@ $Header: /cvsroot/pgsql/doc/src/sgml/xplang.sgml,v 1.20 2003/01/31 00:10:51 tgl
<para> <para>
A procedural language must be <quote>installed</quote> into each A procedural language must be <quote>installed</quote> into each
database where it is to be used. But procedural languages installed in database where it is to be used. But procedural languages installed in
the template1 database are automatically available in all the database <literal>template1</> are automatically available in all
subsequently created databases. So the database administrator can subsequently created databases. So the database administrator can
decide which languages are available in which databases, and can make decide which languages are available in which databases and can make
some languages available by default if he chooses. some languages available by default if he chooses.
</para> </para>
<para> <para>
For the languages supplied with the standard distribution, the For the languages supplied with the standard distribution, the
shell script <filename>createlang</filename> may be used instead program <command>createlang</command> may be used to install the
of carrying out the details by hand. For example, to install <application>PL/pgSQL</application> language instead of carrying out the details by hand. For
into the template1 database, use example, to install the language
<application>PL/pgSQL</application> into the database
<literal>template1</>, use
<programlisting> <programlisting>
createlang plpgsql template1 createlang plpgsql template1
</programlisting> </programlisting>
The manual procedure described below is only recommended for The manual procedure described below is only recommended for
installing custom languages that <filename>createlang</filename> installing custom languages that <command>createlang</command>
does not know about. does not know about.
</para> </para>
...@@ -64,8 +62,11 @@ createlang plpgsql template1 ...@@ -64,8 +62,11 @@ createlang plpgsql template1
</title> </title>
<para> <para>
A procedural language is installed in the database in three A procedural language is installed in a database in three steps,
steps, which must be carried out by a database superuser. which must be carried out by a database superuser. The
<command>createlang</command> programm automates <xref
linkend="xplang-install-cr1"> and <xref
linkend="xplang-install-cr2">.
</para> </para>
<step performance="required"> <step performance="required">
...@@ -81,12 +82,13 @@ createlang plpgsql template1 ...@@ -81,12 +82,13 @@ createlang plpgsql template1
<para> <para>
The handler must be declared with the command The handler must be declared with the command
<synopsis> <synopsis>
CREATE FUNCTION <replaceable>handler_function_name</replaceable> () CREATE FUNCTION <replaceable>handler_function_name</replaceable>()
RETURNS LANGUAGE_HANDLER AS RETURNS language_handler
'<replaceable>path-to-shared-object</replaceable>' LANGUAGE C; AS '<replaceable>path-to-shared-object</replaceable>'
LANGUAGE C;
</synopsis> </synopsis>
The special return type of <type>LANGUAGE_HANDLER</type> tells The special return type of <type>language_handler</type> tells
the database that this function does not return one of the database system that this function does not return one of
the defined <acronym>SQL</acronym> data types and is not directly usable the defined <acronym>SQL</acronym> data types and is not directly usable
in <acronym>SQL</acronym> statements. in <acronym>SQL</acronym> statements.
</para> </para>
...@@ -99,7 +101,7 @@ CREATE FUNCTION <replaceable>handler_function_name</replaceable> () ...@@ -99,7 +101,7 @@ CREATE FUNCTION <replaceable>handler_function_name</replaceable> ()
CREATE <optional>TRUSTED</optional> <optional>PROCEDURAL</optional> LANGUAGE <replaceable>language-name</replaceable> CREATE <optional>TRUSTED</optional> <optional>PROCEDURAL</optional> LANGUAGE <replaceable>language-name</replaceable>
HANDLER <replaceable>handler_function_name</replaceable>; HANDLER <replaceable>handler_function_name</replaceable>;
</synopsis> </synopsis>
The optional key word <literal>TRUSTED</literal> tells whether The optional key word <literal>TRUSTED</literal> specifies that
ordinary database users that have no superuser privileges should ordinary database users that have no superuser privileges should
be allowed to use this language to create functions and trigger be allowed to use this language to create functions and trigger
procedures. Since PL functions are executed inside the database procedures. Since PL functions are executed inside the database
...@@ -119,20 +121,12 @@ CREATE <optional>TRUSTED</optional> <optional>PROCEDURAL</optional> LANGUAGE <re ...@@ -119,20 +121,12 @@ CREATE <optional>TRUSTED</optional> <optional>PROCEDURAL</optional> LANGUAGE <re
</procedure> </procedure>
<para> <para>
In a default <productname>PostgreSQL</productname> installation, <xref linkend="xplang-install-example"> shows how the manual
the handler for the <application>PL/pgSQL</application> language installation procedure would work with the language
is built and installed into the <quote>library</quote> <application>PL/pgSQL</application>.
directory. If <application>Tcl/Tk</> support is configured in, the handlers for
<application>PL/Tcl</> and <application>PL/TclU</> are also built and installed in the same
location. Likewise, the <application>PL/Perl</> and <application>PL/PerlU</> handlers are built
and installed if Perl support is configured, and <application>PL/Python</> is
installed if Python support is configured. The
<filename>createlang</filename> script automates <xref
linkend="xplang-install-cr1"> and <xref
linkend="xplang-install-cr2"> described above.
</para> </para>
<example> <example id="xplang-install-example">
<title>Manual Installation of <application>PL/pgSQL</application></title> <title>Manual Installation of <application>PL/pgSQL</application></title>
<para> <para>
...@@ -140,7 +134,7 @@ CREATE <optional>TRUSTED</optional> <optional>PROCEDURAL</optional> LANGUAGE <re ...@@ -140,7 +134,7 @@ CREATE <optional>TRUSTED</optional> <optional>PROCEDURAL</optional> LANGUAGE <re
shared object for the <application>PL/pgSQL</application> language's call handler function. shared object for the <application>PL/pgSQL</application> language's call handler function.
<programlisting> <programlisting>
CREATE FUNCTION plpgsql_call_handler () RETURNS LANGUAGE_HANDLER AS CREATE FUNCTION plpgsql_call_handler() RETURNS language_handler AS
'$libdir/plpgsql' LANGUAGE C; '$libdir/plpgsql' LANGUAGE C;
</programlisting> </programlisting>
</para> </para>
...@@ -157,6 +151,17 @@ CREATE TRUSTED PROCEDURAL LANGUAGE plpgsql ...@@ -157,6 +151,17 @@ CREATE TRUSTED PROCEDURAL LANGUAGE plpgsql
</para> </para>
</example> </example>
<para>
In a default <productname>PostgreSQL</productname> installation,
the handler for the <application>PL/pgSQL</application> language
is built and installed into the <quote>library</quote>
directory. If <application>Tcl/Tk</> support is configured in, the handlers for
<application>PL/Tcl</> and <application>PL/TclU</> are also built and installed in the same
location. Likewise, the <application>PL/Perl</> and <application>PL/PerlU</> handlers are built
and installed if Perl support is configured, and <application>PL/Python</> is
installed if Python support is configured.
</para>
</sect1> </sect1>
</chapter> </chapter>
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment