3
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
4
<title>38.2.�Database Access from PL/Perl</title>
5
<link rel="stylesheet" href="stylesheet.css" type="text/css">
6
<link rev="made" href="pgsql-docs@postgresql.org">
7
<meta name="generator" content="DocBook XSL Stylesheets V1.70.0">
8
<link rel="start" href="index.html" title="PostgreSQL 8.1.4 Documentation">
9
<link rel="up" href="plperl.html" title="Chapter�38.�PL/Perl - Perl Procedural Language">
10
<link rel="prev" href="plperl.html" title="Chapter�38.�PL/Perl - Perl Procedural Language">
11
<link rel="next" href="plperl-data.html" title="38.3.�Data Values in PL/Perl">
12
<link rel="copyright" href="ln-legalnotice.html" title="Legal Notice">
14
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"><div class="sect1" lang="en">
15
<div class="titlepage"><div><div><h2 class="title" style="clear: both">
16
<a name="plperl-database"></a>38.2.�Database Access from PL/Perl</h2></div></div></div>
17
<p> Access to the database itself from your Perl function can be done
18
via the function <code class="function">spi_exec_query</code> described
19
below, or via an experimental module
20
<a href="http://www.cpan.org/modules/by-module/DBD/APILOS/" target="_top"> <code class="literal">DBD::PgSPI</code></a>
21
(also available at <a href="http://www.cpan.org/SITES.html" target="_top"> <acronym class="acronym">CPAN mirror sites</acronym></a>). This module makes available a
22
<acronym class="acronym">DBI</acronym>-compliant database-handle named
23
<code class="varname">$pg_dbh</code> that can be used to perform queries with
24
normal <acronym class="acronym">DBI</acronym>
25
syntax.<a name="id731851"></a>
27
<p> PL/Perl provides three additional Perl commands:
30
<div class="variablelist"><dl>
32
<span xmlns="http://www.w3.org/TR/xhtml1/transitional" class="term"><code xmlns="" class="literal"><code class="function">spi_exec_query</code>(<em class="replaceable"><code>query</code></em> [, <em class="replaceable"><code>max-rows</code></em>])</code></span><br xmlns="http://www.w3.org/TR/xhtml1/transitional"></br><span xmlns="http://www.w3.org/TR/xhtml1/transitional" class="term"><code xmlns="" class="literal"><code class="function">spi_exec_query</code>(<em class="replaceable"><code>command</code></em>)</code></span><br xmlns="http://www.w3.org/TR/xhtml1/transitional"></br><span xmlns="http://www.w3.org/TR/xhtml1/transitional" class="term"><code xmlns="" class="literal"><code class="function">spi_query</code>(<em class="replaceable"><code>command</code></em>)</code></span><br xmlns="http://www.w3.org/TR/xhtml1/transitional"></br><span class="term"><code class="literal"><code class="function">spi_fetchrow</code>(<em class="replaceable"><code>command</code></em>)</code></span>
35
<p> <code class="literal">spi_exec_query</code> executes an SQL command and
36
returns the entire row set as a reference to an array of hash
37
references. <span class="emphasis"><em>You should only use this command when you know
38
that the result set will be relatively small.</em></span> Here is an
39
example of a query (<code class="command">SELECT</code> command) with the
40
optional maximum number of rows:
43
<pre class="programlisting">$rv = spi_exec_query('SELECT * FROM my_table', 5);</pre>
45
This returns up to 5 rows from the table
46
<code class="literal">my_table</code>. If <code class="literal">my_table</code>
47
has a column <code class="literal">my_column</code>, you can get that
48
value from row <code class="literal">$i</code> of the result like this:
50
<pre class="programlisting">$foo = $rv->{rows}[$i]->{my_column};</pre>
52
The total number of rows returned from a <code class="command">SELECT</code>
53
query can be accessed like this:
55
<pre class="programlisting">$nrows = $rv->{processed}</pre>
58
<p> Here is an example using a different command type:
60
<pre class="programlisting">$query = "INSERT INTO my_table VALUES (1, 'test')";
61
$rv = spi_exec_query($query);</pre>
63
You can then access the command status (e.g.,
64
<code class="literal">SPI_OK_INSERT</code>) like this:
66
<pre class="programlisting">$res = $rv->{status};</pre>
68
To get the number of rows affected, do:
70
<pre class="programlisting">$nrows = $rv->{processed};</pre>
73
<p> Here is a complete example:
75
<pre class="programlisting">CREATE TABLE test (
80
INSERT INTO test (i, v) VALUES (1, 'first line');
81
INSERT INTO test (i, v) VALUES (2, 'second line');
82
INSERT INTO test (i, v) VALUES (3, 'third line');
83
INSERT INTO test (i, v) VALUES (4, 'immortal');
85
CREATE OR REPLACE FUNCTION test_munge() RETURNS SETOF test AS $$
86
my $rv = spi_exec_query('select i, v from test;');
87
my $status = $rv->{status};
88
my $nrows = $rv->{processed};
89
foreach my $rn (0 .. $nrows - 1) {
90
my $row = $rv->{rows}[$rn];
91
$row->{i} += 200 if defined($row->{i});
92
$row->{v} =~ tr/A-Za-z/a-zA-Z/ if (defined($row->{v}));
98
SELECT * FROM test_munge();</pre>
101
<p> <code class="literal">spi_query</code> and <code class="literal">spi_fetchrow</code>
102
work together as a pair for row sets which may be large, or for cases
103
where you wish to return rows as they arrive.
104
<code class="literal">spi_fetchrow</code> works <span class="emphasis"><em>only</em></span> with
105
<code class="literal">spi_query</code>. The following example illustrates how
106
you use them together:
109
<pre class="programlisting">CREATE TYPE foo_type AS (the_num INTEGER, the_text TEXT);
111
CREATE OR REPLACE FUNCTION lotsa_md5 (INTEGER) RETURNS SETOF foo_type AS $$
112
use Digest::MD5 qw(md5_hex);
113
my $file = '/usr/share/dict/words';
115
elog(NOTICE, "opening file $file at $t" );
116
open my $fh, '<', $file # ooh, it's a file access!
117
or elog(ERROR, "Can't open $file for reading: $!");
118
my @words = <$fh>;
121
elog(NOTICE, "closed file $file at $t");
124
my $sth = spi_query("SELECT * FROM generate_series(1,$_[0]) AS b(a)");
125
while (defined ($row = spi_fetchrow($sth))) {
127
the_num => $row->{a},
128
the_text => md5_hex($words[rand @words])
134
SELECT * from lotsa_md5(500);</pre>
138
<dt><span class="term"><code class="literal"><code class="function">elog</code>(<em class="replaceable"><code>level</code></em>, <em class="replaceable"><code>msg</code></em>)</code></span></dt>
139
<dd><p> Emit a log or error message. Possible levels are
140
<code class="literal">DEBUG</code>, <code class="literal">LOG</code>, <code class="literal">INFO</code>,
141
<code class="literal">NOTICE</code>, <code class="literal">WARNING</code>, and <code class="literal">ERROR</code>.
142
<code class="literal">ERROR</code>
143
raises an error condition; if this is not trapped by the surrounding
144
Perl code, the error propagates out to the calling query, causing
145
the current transaction or subtransaction to be aborted. This
146
is effectively the same as the Perl <code class="literal">die</code> command.
147
The other levels only generate messages of different
149
Whether messages of a particular priority are reported to the client,
150
written to the server log, or both is controlled by the
151
<a href="runtime-config-logging.html#guc-log-min-messages">log_min_messages</a> and
152
<a href="runtime-config-logging.html#guc-client-min-messages">client_min_messages</a> configuration
153
variables. See <a href="runtime-config.html" title="Chapter�17.�Server Configuration">Chapter�17, <i>Server Configuration</i></a> for more