~ubuntu-branches/debian/squeeze/pgadmin3/squeeze

« back to all changes in this revision

Viewing changes to docs/en_US/pg/plperl-database.html

  • Committer: Bazaar Package Importer
  • Author(s): Lionel Porcheron
  • Date: 2008-02-07 00:56:22 UTC
  • mto: (2.1.6 hardy) (6.1.2 sid)
  • mto: This revision was merged to the branch mainline in revision 4.
  • Revision ID: james.westby@ubuntu.com-20080207005622-c2ail8p4d0sk3dnw
Tags: upstream-1.8.2
Import upstream version 1.8.2

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
<html>
2
 
<head>
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">
13
 
</head>
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>
26
 
  </p>
27
 
<p>   PL/Perl provides three additional Perl commands:
28
 
 
29
 
   </p>
30
 
<div class="variablelist"><dl>
31
 
<dt>
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>
33
 
</dt>
34
 
<dd>
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:
41
 
 
42
 
</p>
43
 
<pre class="programlisting">$rv = spi_exec_query('SELECT * FROM my_table', 5);</pre>
44
 
<p>
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:
49
 
</p>
50
 
<pre class="programlisting">$foo = $rv-&gt;{rows}[$i]-&gt;{my_column};</pre>
51
 
<p>
52
 
       The total number of rows returned from a <code class="command">SELECT</code>
53
 
       query can be accessed like this:
54
 
</p>
55
 
<pre class="programlisting">$nrows = $rv-&gt;{processed}</pre>
56
 
<p>
57
 
      </p>
58
 
<p>       Here is an example using a different command type:
59
 
</p>
60
 
<pre class="programlisting">$query = "INSERT INTO my_table VALUES (1, 'test')";
61
 
$rv = spi_exec_query($query);</pre>
62
 
<p>
63
 
       You can then access the command status (e.g.,
64
 
       <code class="literal">SPI_OK_INSERT</code>) like this:
65
 
</p>
66
 
<pre class="programlisting">$res = $rv-&gt;{status};</pre>
67
 
<p>
68
 
       To get the number of rows affected, do:
69
 
</p>
70
 
<pre class="programlisting">$nrows = $rv-&gt;{processed};</pre>
71
 
<p>
72
 
      </p>
73
 
<p>       Here is a complete example:
74
 
</p>
75
 
<pre class="programlisting">CREATE TABLE test (
76
 
    i int,
77
 
    v varchar
78
 
);
79
 
 
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');
84
 
 
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-&gt;{status};
88
 
    my $nrows = $rv-&gt;{processed};
89
 
    foreach my $rn (0 .. $nrows - 1) {
90
 
        my $row = $rv-&gt;{rows}[$rn];
91
 
        $row-&gt;{i} += 200 if defined($row-&gt;{i});
92
 
        $row-&gt;{v} =~ tr/A-Za-z/a-zA-Z/ if (defined($row-&gt;{v}));
93
 
        return_next($row);
94
 
    }
95
 
    return undef;
96
 
$$ LANGUAGE plperl;
97
 
 
98
 
SELECT * FROM test_munge();</pre>
99
 
<p>
100
 
    </p>
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:
107
 
 
108
 
</p>
109
 
<pre class="programlisting">CREATE TYPE foo_type AS (the_num INTEGER, the_text TEXT);
110
 
 
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';
114
 
    my $t = localtime;
115
 
    elog(NOTICE, "opening file $file at $t" );
116
 
    open my $fh, '&lt;', $file # ooh, it's a file access!
117
 
        or elog(ERROR, "Can't open $file for reading: $!");
118
 
    my @words = &lt;$fh&gt;;
119
 
    close $fh;
120
 
    $t = localtime;
121
 
    elog(NOTICE, "closed file $file at $t");
122
 
    chomp(@words);
123
 
    my $row;
124
 
    my $sth = spi_query("SELECT * FROM generate_series(1,$_[0]) AS b(a)");
125
 
    while (defined ($row = spi_fetchrow($sth))) {
126
 
        return_next({
127
 
            the_num =&gt; $row-&gt;{a},
128
 
            the_text =&gt; md5_hex($words[rand @words])
129
 
        });
130
 
    }
131
 
    return;
132
 
$$ LANGUAGE plperlu;
133
 
 
134
 
SELECT * from lotsa_md5(500);</pre>
135
 
<p>
136
 
    </p>
137
 
</dd>
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
148
 
        priority levels.
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
154
 
        information.
155
 
      </p></dd>
156
 
</dl></div>
157
 
<p>
158
 
  </p>
159
 
</div></body>
160
 
</html>