#!/usr/bin/perl

use DBI;
use DBD::Pg;

$dbname = "testdb";
$dbhost = "127.0.0.1";
$dbuser = "kjh";
$dbpass = "Trinitron";

$testfile = "/bin/ls";

my $dbi_dsn = "dbi:Pg:dbname=" . $dbname . ";host=" . $dbhost;

my $dbh = DBI->connect("$dbi_dsn","$dbuser","$dbpass",
		       {
			AutoCommit => 0,
			RaiseError => 1,
			PrintError => 1
		       }
		      );

unless ( stat($testfile) ) {
  die("stat() '$testfile'\n$!");
}
my $filesize = (stat(_))[7];
my $contents = "";

print "- reading testfile '$testfile'\n";
local(*FILE);
open(FILE,$testfile) || die("open('$testfile'): $!");
binmode(FILE);
sysread(FILE,$contents,$filesize);

print "- inserting testfile contents\n";
my $oid   = $dbh->func($dbh->{pg_INV_WRITE},'lo_creat');
my $fd    = $dbh->func($oid, $dbh->{pg_INV_WRITE}, 'lo_open');
my $bytes = $dbh->func($fd, $contents, $filesize, 'lo_write');
$dbh->func($fd, 'lo_close');
unless ( $bytes == $filesize ) {
  die("error: inserted '$bytes' of '$filesize' bytes");
}
print "- oid = '$oid'\n";

$fd       = undef;
$bytes    = undef;
$contents = undef;

print "- reading large object\n";
$fd    = $dbh->func($oid, $dbh->{pg_INV_READ}, 'lo_open');
$bytes = $dbh->func($fd, $contents, $filesize, 'lo_read');
$dbh->func($fd, 'lo_close');
print "success.. removing large object\n";
$dbh->func($oid, 'lo_unlink');

$dbh->disconnect();

