2 43.3. Built-in Functions #
4 43.3.1. Database Access from PL/Perl
5 43.3.2. Utility Functions in PL/Perl
7 43.3.1. Database Access from PL/Perl #
9 Access to the database itself from your Perl function can be done via
10 the following functions:
12 spi_exec_query(query [, limit])
13 spi_exec_query executes an SQL command and returns the entire
14 row set as a reference to an array of hash references. If limit
15 is specified and is greater than zero, then spi_exec_query
16 retrieves at most limit rows, much as if the query included a
17 LIMIT clause. Omitting limit or specifying it as zero results in
20 You should only use this command when you know that the result
21 set will be relatively small. Here is an example of a query
22 (SELECT command) with the optional maximum number of rows:
24 $rv = spi_exec_query('SELECT * FROM my_table', 5);
26 This returns up to 5 rows from the table my_table. If my_table
27 has a column my_column, you can get that value from row $i of
30 $foo = $rv->{rows}[$i]->{my_column};
32 The total number of rows returned from a SELECT query can be
35 $nrows = $rv->{processed}
37 Here is an example using a different command type:
39 $query = "INSERT INTO my_table VALUES (1, 'test')";
40 $rv = spi_exec_query($query);
42 You can then access the command status (e.g., SPI_OK_INSERT)
47 To get the number of rows affected, do:
49 $nrows = $rv->{processed};
51 Here is a complete example:
58 INSERT INTO test (i, v) VALUES (1, 'first line');
59 INSERT INTO test (i, v) VALUES (2, 'second line');
60 INSERT INTO test (i, v) VALUES (3, 'third line');
61 INSERT INTO test (i, v) VALUES (4, 'immortal');
63 CREATE OR REPLACE FUNCTION test_munge() RETURNS SETOF test AS $$
64 my $rv = spi_exec_query('select i, v from test;');
65 my $status = $rv->{status};
66 my $nrows = $rv->{processed};
67 foreach my $rn (0 .. $nrows - 1) {
68 my $row = $rv->{rows}[$rn];
69 $row->{i} += 200 if defined($row->{i});
70 $row->{v} =~ tr/A-Za-z/a-zA-Z/ if (defined($row->{v}));
76 SELECT * FROM test_munge();
80 spi_cursor_close(cursor)
81 spi_query and spi_fetchrow work together as a pair for row sets
82 which might be large, or for cases where you wish to return rows
83 as they arrive. spi_fetchrow works only with spi_query. The
84 following example illustrates how you use them together:
86 CREATE TYPE foo_type AS (the_num INTEGER, the_text TEXT);
88 CREATE OR REPLACE FUNCTION lotsa_md5 (INTEGER) RETURNS SETOF foo_type AS $$
89 use Digest::MD5 qw(md5_hex);
90 my $file = '/usr/share/dict/words';
92 elog(NOTICE, "opening file $file at $t" );
93 open my $fh, '<', $file # ooh, it's a file access!
94 or elog(ERROR, "cannot open $file for reading: $!");
98 elog(NOTICE, "closed file $file at $t");
101 my $sth = spi_query("SELECT * FROM generate_series(1,$_[0]) AS b(a)");
102 while (defined ($row = spi_fetchrow($sth))) {
104 the_num => $row->{a},
105 the_text => md5_hex($words[rand @words])
111 SELECT * from lotsa_md5(500);
113 Normally, spi_fetchrow should be repeated until it returns
114 undef, indicating that there are no more rows to read. The
115 cursor returned by spi_query is automatically freed when
116 spi_fetchrow returns undef. If you do not wish to read all the
117 rows, instead call spi_cursor_close to free the cursor. Failure
118 to do so will result in memory leaks.
120 spi_prepare(command, argument types)
121 spi_query_prepared(plan, arguments)
122 spi_exec_prepared(plan [, attributes], arguments)
124 spi_prepare, spi_query_prepared, spi_exec_prepared, and
125 spi_freeplan implement the same functionality but for prepared
126 queries. spi_prepare accepts a query string with numbered
127 argument placeholders ($1, $2, etc.) and a string list of
130 $plan = spi_prepare('SELECT * FROM test WHERE id > $1 AND name = $2',
133 Once a query plan is prepared by a call to spi_prepare, the plan
134 can be used instead of the string query, either in
135 spi_exec_prepared, where the result is the same as returned by
136 spi_exec_query, or in spi_query_prepared which returns a cursor
137 exactly as spi_query does, which can be later passed to
138 spi_fetchrow. The optional second parameter to spi_exec_prepared
139 is a hash reference of attributes; the only attribute currently
140 supported is limit, which sets the maximum number of rows
141 returned from the query. Omitting limit or specifying it as zero
142 results in no row limit.
144 The advantage of prepared queries is that is it possible to use
145 one prepared plan for more than one query execution. After the
146 plan is not needed anymore, it can be freed with spi_freeplan:
148 CREATE OR REPLACE FUNCTION init() RETURNS VOID AS $$
149 $_SHARED{my_plan} = spi_prepare('SELECT (now() + $1)::date AS now',
153 CREATE OR REPLACE FUNCTION add_time( INTERVAL ) RETURNS TEXT AS $$
154 return spi_exec_prepared(
157 )->{rows}->[0]->{now};
160 CREATE OR REPLACE FUNCTION done() RETURNS VOID AS $$
161 spi_freeplan( $_SHARED{my_plan});
162 undef $_SHARED{my_plan};
166 SELECT add_time('1 day'), add_time('2 days'), add_time('3 days');
169 add_time | add_time | add_time
170 ------------+------------+------------
171 2005-12-10 | 2005-12-11 | 2005-12-12
173 Note that the parameter subscript in spi_prepare is defined via
174 $1, $2, $3, etc., so avoid declaring query strings in double
175 quotes that might easily lead to hard-to-catch bugs.
177 Another example illustrates usage of an optional parameter in
180 CREATE TABLE hosts AS SELECT id, ('192.168.1.'||id)::inet AS address
181 FROM generate_series(1,3) AS id;
183 CREATE OR REPLACE FUNCTION init_hosts_query() RETURNS VOID AS $$
184 $_SHARED{plan} = spi_prepare('SELECT * FROM hosts
185 WHERE address << $1', 'inet');
188 CREATE OR REPLACE FUNCTION query_hosts(inet) RETURNS SETOF hosts AS $$
189 return spi_exec_prepared(
196 CREATE OR REPLACE FUNCTION release_hosts_query() RETURNS VOID AS $$
197 spi_freeplan($_SHARED{plan});
198 undef $_SHARED{plan};
201 SELECT init_hosts_query();
202 SELECT query_hosts('192.168.1.0/30');
203 SELECT release_hosts_query();
213 Commit or roll back the current transaction. This can only be
214 called in a procedure or anonymous code block (DO command)
215 called from the top level. (Note that it is not possible to run
216 the SQL commands COMMIT or ROLLBACK via spi_exec_query or
217 similar. It has to be done using these functions.) After a
218 transaction is ended, a new transaction is automatically
219 started, so there is no separate function for that.
223 CREATE PROCEDURE transaction_test1()
226 foreach my $i (0..9) {
227 spi_exec_query("INSERT INTO test1 (a) VALUES ($i)");
236 CALL transaction_test1();
238 43.3.2. Utility Functions in PL/Perl #
241 Emit a log or error message. Possible levels are DEBUG, LOG,
242 INFO, NOTICE, WARNING, and ERROR. ERROR raises an error
243 condition; if this is not trapped by the surrounding Perl code,
244 the error propagates out to the calling query, causing the
245 current transaction or subtransaction to be aborted. This is
246 effectively the same as the Perl die command. The other levels
247 only generate messages of different priority levels. Whether
248 messages of a particular priority are reported to the client,
249 written to the server log, or both is controlled by the
250 log_min_messages and client_min_messages configuration
251 variables. See Chapter 19 for more information.
253 quote_literal(string)
254 Return the given string suitably quoted to be used as a string
255 literal in an SQL statement string. Embedded single-quotes and
256 backslashes are properly doubled. Note that quote_literal
257 returns undef on undef input; if the argument might be undef,
258 quote_nullable is often more suitable.
260 quote_nullable(string)
261 Return the given string suitably quoted to be used as a string
262 literal in an SQL statement string; or, if the argument is
263 undef, return the unquoted string "NULL". Embedded single-quotes
264 and backslashes are properly doubled.
267 Return the given string suitably quoted to be used as an
268 identifier in an SQL statement string. Quotes are added only if
269 necessary (i.e., if the string contains non-identifier
270 characters or would be case-folded). Embedded quotes are
274 Return the unescaped binary data represented by the contents of
275 the given string, which should be bytea encoded.
278 Return the bytea encoded form of the binary data contents of the
281 encode_array_literal(array)
282 encode_array_literal(array, delimiter)
283 Returns the contents of the referenced array as a string in
284 array literal format (see Section 8.15.2). Returns the argument
285 value unaltered if it's not a reference to an array. The
286 delimiter used between elements of the array literal defaults to
287 ", " if a delimiter is not specified or is undef.
289 encode_typed_literal(value, typename)
290 Converts a Perl variable to the value of the data type passed as
291 a second argument and returns a string representation of this
292 value. Correctly handles nested arrays and values of composite
295 encode_array_constructor(array)
296 Returns the contents of the referenced array as a string in
297 array constructor format (see Section 4.2.12). Individual values
298 are quoted using quote_nullable. Returns the argument value,
299 quoted using quote_nullable, if it's not a reference to an
302 looks_like_number(string)
303 Returns a true value if the content of the given string looks
304 like a number, according to Perl, returns false otherwise.
305 Returns undef if the argument is undef. Leading and trailing
306 space is ignored. Inf and Infinity are regarded as numbers.
308 is_array_ref(argument)
309 Returns a true value if the given argument may be treated as an
310 array reference, that is, if ref of the argument is ARRAY or
311 PostgreSQL::InServer::ARRAY. Returns false otherwise.