| The PostgreSQL 9.0 Reference Manual - Volume 2 - Programming Guide
by The PostgreSQL Global Development Group Paperback (6"x9"), 478 pages ISBN 9781906966065 RRP £14.95 ($19.95) Sales of this book support the PostgreSQL project! Get a printed copy>>> |
11.3.1 Database Access from PL/Perl
Access to the database itself from your Perl function can be done via the following functions:
spi_exec_query(query [, max-rows])-
spi_exec_queryexecutes an SQL command and returns the entire row set as a reference to an array of hash references. You should only use this command when you know that the result set will be relatively small. Here is an example of a query (SELECTcommand) with the optional maximum number of rows:$rv = spi_exec_query('SELECT * FROM my_table', 5);This returns up to 5 rows from the tablemy_table. Ifmy_tablehas a columnmy_column, you can get that value from row$iof the result like this:$foo = $rv->{rows}[$i]->{my_column};The total number of rows returned from aSELECTquery can be accessed like this:$nrows = $rv->{processed}Here is an example using a different command type:$query = "INSERT INTO my_table VALUES (1, 'test')"; $rv = spi_exec_query($query);
You can then access the command status (e.g.,SPI_OK_INSERT) like this:$res = $rv->{status};To get the number of rows affected, do:$nrows = $rv->{processed};Here is a complete example:CREATE TABLE test ( i int, v varchar ); INSERT INTO test (i, v) VALUES (1, 'first line'); INSERT INTO test (i, v) VALUES (2, 'second line'); INSERT INTO test (i, v) VALUES (3, 'third line'); INSERT INTO test (i, v) VALUES (4, 'immortal'); CREATE OR REPLACE FUNCTION test_munge() RETURNS SETOF test AS $$ my $rv = spi_exec_query('select i, v from test;'); my $status = $rv->{status}; my $nrows = $rv->{processed}; foreach my $rn (0 .. $nrows - 1) { my $row = $rv->{rows}[$rn]; $row->{i} += 200 if defined($row->{i}); $row->{v} =~ tr/A-Za-z/a-zA-Z/ if (defined($row->{v})); return_next($row); } return undef; $$ LANGUAGE plperl; SELECT * FROM test_munge(); spi_query(command)spi_fetchrow(cursor)spi_cursor_close(cursor)-
spi_queryandspi_fetchrowwork together as a pair for row sets which might be large, or for cases where you wish to return rows as they arrive.spi_fetchrowworks only withspi_query. The following example illustrates how you use them together:CREATE TYPE foo_type AS (the_num INTEGER, the_text TEXT); CREATE OR REPLACE FUNCTION lotsa_md5 (INTEGER) RETURNS SETOF foo_type AS $$ use Digest::MD5 qw(md5_hex); my $file = '/usr/share/dict/words'; my $t = localtime; elog(NOTICE, "opening file $file at $t" ); open my $fh, '<', $file # ooh, it's a file access! or elog(ERROR, "cannot open $file for reading: $!"); my @words = <$fh>; close $fh; $t = localtime; elog(NOTICE, "closed file $file at $t"); chomp(@words); my $row; my $sth = spi_query("SELECT * FROM generate_series(1, $_[0]) AS b(a)"); while (defined ($row = spi_fetchrow($sth))) { return_next({ the_num => $row->{a}, the_text => md5_hex($words[rand @words]) }); } return; $$ LANGUAGE plperlu; SELECT * from lotsa_md5(500);Normally,spi_fetchrowshould be repeated until it returnsundef, indicating that there are no more rows to read. The cursor returned byspi_queryis automatically freed whenspi_fetchrowreturnsundef. If you do not wish to read all the rows, instead callspi_cursor_closeto free the cursor. Failure to do so will result in memory leaks. spi_prepare(command, argument types)spi_query_prepared(plan, arguments)spi_exec_prepared(plan [, attributes], arguments)spi_freeplan(plan)-
spi_prepare,spi_query_prepared,spi_exec_prepared, andspi_freeplanimplement the same functionality but for prepared queries.spi_prepareaccepts a query string with numbered argument placeholders ($1, $2, etc) and a string list of argument types:$plan = spi_prepare('SELECT * FROM test WHERE id > $1 AND name = $2', 'INTEGER', 'TEXT');Once a query plan is prepared by a call tospi_prepare, the plan can be used instead of the string query, either inspi_exec_prepared, where the result is the same as returned byspi_exec_query, or inspi_query_preparedwhich returns a cursor exactly asspi_querydoes, which can be later passed tospi_fetchrow. The optional second parameter tospi_exec_preparedis a hash reference of attributes; the only attribute currently supported islimit, which sets the maximum number of rows returned by a query. The advantage of prepared queries is that is it possible to use one prepared plan for more than one query execution. After the plan is not needed anymore, it can be freed withspi_freeplan:CREATE OR REPLACE FUNCTION init() RETURNS VOID AS $$ $_SHARED{my_plan} = spi_prepare('SELECT (now() + $1)::date AS now', 'INTERVAL'); $$ LANGUAGE plperl; CREATE OR REPLACE FUNCTION add_time( INTERVAL ) RETURNS TEXT AS $$ return spi_exec_prepared( $_SHARED{my_plan}, $_[0] )->{rows}->[0]->{now}; $$ LANGUAGE plperl; CREATE OR REPLACE FUNCTION done() RETURNS VOID AS $$ spi_freeplan( $_SHARED{my_plan}); undef $_SHARED{my_plan}; $$ LANGUAGE plperl; SELECT init(); SELECT add_time('1 day'), add_time('2 days'), add_time('3 days'); SELECT done(); add_time | add_time | add_time ------------+------------+------------ 2005-12-10 | 2005-12-11 | 2005-12-12Note that the parameter subscript inspi_prepareis defined via $1, $2, $3, etc, so avoid declaring query strings in double quotes that might easily lead to hard-to-catch bugs. Another example illustrates usage of an optional parameter inspi_exec_prepared:CREATE TABLE hosts AS SELECT id, ('192.168.1.'||id)::inet AS address FROM generate_series(1,3) AS id; CREATE OR REPLACE FUNCTION init_hosts_query() RETURNS VOID AS $$ $_SHARED{plan} = spi_prepare('SELECT * FROM hosts WHERE address << $1', 'inet'); $$ LANGUAGE plperl; CREATE OR REPLACE FUNCTION query_hosts(inet) RETURNS SETOF hosts AS $$ return spi_exec_prepared( $_SHARED{plan}, {limit => 2}, $_[0] )->{rows}; $$ LANGUAGE plperl; CREATE OR REPLACE FUNCTION release_hosts_query() RETURNS VOID AS $$ spi_freeplan($_SHARED{plan}); undef $_SHARED{plan}; $$ LANGUAGE plperl; SELECT init_hosts_query(); SELECT query_hosts('192.168.1.0/30'); SELECT release_hosts_query(); query_hosts ----------------- (1,192.168.1.1) (2,192.168.1.2) (2 rows)
| ISBN 9781906966065 | The PostgreSQL 9.0 Reference Manual - Volume 2 - Programming Guide | See the print edition |