Re: How to get text for a plpgsql variable from a file.

From: "Greg Sabino Mullane" <greg(at)turnstep(dot)com>
To: pgsql-general(at)postgresql(dot)org
Subject: Re: How to get text for a plpgsql variable from a file.
Date: 2009-12-17 14:23:11
Message-ID: b81a603b7ad6ca197ddd786cc1d9ae53@biglumber.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general


-----BEGIN PGP SIGNED MESSAGE-----
Hash: RIPEMD160
NotDashEscaped: You need GnuPG to verify this message

> I need a long text form from a file in my plpgsql variable.
> Can anyone think of a more straightforward way to read the file than
> the following:

Sounds like a job for an 'untrusted' procedural language.
Here's a quick example using plperlu:

===
\t
\o /tmp/gtest
SELECT 'OH HAI';
\o
\t

CREATE OR REPLACE FUNCTION
read_file(TEXT)
RETURNS TEXT
LANGUAGE plperlu
AS $bc$
use strict;
use warnings;

my $filename = shift;

index($filename, '/')
and die qq{File name must be an absolute path\n};

open my $fh, '<', $filename
or die qq{Could not open file "$filename": $!\n};

my $string;
{
local $/;
$string = <$fh>;
}

close $fh
or die qq{Could not close file "$filename": $!\n};

return $string;

$bc$;

CREATE OR REPLACE FUNCTION gtest()
RETURNS TEXT
LANGUAGE plpgsql
AS $bc$
DECLARE
external_file_contents TEXT;
BEGIN
SELECT INTO external_file_contents read_file('/tmp/gtest');
RETURN 'GOT:' || external_file_contents;
END
$bc$;

SELECT gtest();
===

Piping all of the above into psql gives:

Output format is unaligned.
Showing only tuples.
Tuples only is off.
Output format is aligned.
CREATE FUNCTION
CREATE FUNCTION
gtest
------------
GOT:OH HAI

--
Greg Sabino Mullane greg(at)turnstep(dot)com
End Point Corporation http://www.endpoint.com/
PGP Key: 0x14964AC8 200912170920
http://biglumber.com/x/web?pk=2529DF6AB8F79407E94445B4BC9B906714964AC8
-----BEGIN PGP SIGNATURE-----

iEYEAREDAAYFAksqPrkACgkQvJuQZxSWSsgjFACfebEHE6rLGs04w6mptctG7nuI
IXwAoJmLOwavrXyaU+4lHx3OsIws4JOc
=58sb
-----END PGP SIGNATURE-----

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Greg Sabino Mullane 2009-12-17 14:27:57 Re: Justifying a PG over MySQL approach to a project
Previous Message Vincenzo Romano 2009-12-17 13:41:40 Re: Table Partitioning Advice Request