#!/usr/bin/perl -w

use DBI;
use IO::File;

my $dovac = 0;
my $doidx = 0;
my $dostats = 0;
$dovac = $ARGV[0] if @ARGV > 0;
$dostats = $ARGV[1] if @ARGV > 1;

$dbname=$ENV{DBNAME} || "testdb";
$dbhost=$ENV{DBHOST} || "localhost";
$dbuser=$ENV{DBUSER} || "postgres";
my $fh = new IO::File "rane1-analyze.out" || die "Unable to open text file";
my $bof = $fh->getpos;

my $dbh = DBI->connect("dbi:Pg:dbname=$dbname;host=$dbhost",$dbuser) || die "Unable to connect to database";
$dbh->do("set stats_block_level to true") if $dostats;
$dbh->do("set stats_row_level to true") if $dostats;
my $us1 = $dbh->prepare("update testtab set field1=? where keyfield=?");
my $us2 = $dbh->prepare("update testtab set field2=? where keyfield=?");
my $us3 = $dbh->prepare("update testtab set field3=? where keyfield=?");
my $is = $dbh->prepare("insert into testtab values (?, ?, ?, ?)");
my @us = ($us1, $us2, $us3);

sub gentext {
    if ($fh->eof) {
        $fh->setpos($bof);
    }
    my $rec = $fh->getline;
}

foreach my $p (1..1000) {
    my $tm = time;
    foreach my $loop (1..1000) {
        my $rn = int(rand(1000)) + 1;
        my $s = int(rand(3));
        if ($us[$s]->execute(gentext(), $rn) == 0) {
            if ($is->execute($rn, gentext(), gentext(), gentext()) == 0) {
                print STDERR "Update/Insert failed\n";
                next;
            }
        }
    }
    my $tm1 = time - $tm;
    $dbh->do("vacuum testtab") or die "Vacuum failed" if $dovac;
    my $tm2 = time - $tm;
    print "pass $p complete - $tm1 seconds; $tm2 seconds w/maintenance\n";
}

foreach my $st ($us1,$us2,$us3,$is) {
    $st->finish;
}

$dbh->disconnect;
