#!/usr/bin/perl -w
#
# Import large objects of a Pg database
#  - Sherwin T. Daganato (win@email.com.ph)
#  - October 8, 2000
#

use strict;
use Pg;

die "Usage: $0 inputdir database\n" if ($#ARGV != 1);
my ($space, $dbname) = @ARGV;

# make sure the directory doesn't end in '/'
$space =~ s/\/$//;

my $path = sprintf ("%s/%s/lo_dump.index", $space, $dbname);
local (*F);

# opens file for reading. The file must exist
open(F, $path) || die "\n $0 Cannot open $! \n";

my $conn = Pg::connectdb("dbname=$dbname");
die $conn->errorMessage unless PGRES_CONNECTION_OK eq $conn->status;

my $counter = 0;
my $line;
while ($line = <F>) {
  next if ($line =~ /^#/);
  print $line;
  
  my ($lo_oid, $tbl, $fld, $path) = ($line =~ /^(\d+)\t(.+)\t(.+)\t(.+)\n$/);

  my $lo_path = sprintf ("%s/%s", $space, $path);

  my $result = $conn->exec("BEGIN");
  die $conn->errorMessage unless PGRES_COMMAND_OK eq $result->resultStatus;

  # import old large object and get its new oid
  my $new_oid = $conn->lo_import($lo_path) or die $conn->errorMessage;

  $result = $conn->exec("END");
  die $conn->errorMessage unless PGRES_COMMAND_OK eq $result->resultStatus;

  # count no. of imports
  $counter++;

  # update the old oid
  my $sql = sprintf ("UPDATE %s SET %s=%ld WHERE %s=%ld", 
    $tbl, $fld, $new_oid, $fld, $lo_oid);

  $result = $conn->exec($sql);
  die $conn->errorMessage unless PGRES_COMMAND_OK eq $result->resultStatus;

}

close(F);
undef $conn;
printf "\nImported %d large objects.\n\n", $counter;