#!/bin/sh

#PATH=${PATH}:/home/perftester/seqscantest/pgsql-installation/bin/
PATH=${PATH}:/home/hlinnaka/pgsql.cvshead/bin/

LABEL=$1

# in MB
BIGTABLESIZE=10

psql postgres -c "CREATE TABLE testresult (description VARCHAR(200), begints TIMESTAMP, endts TIMESTAMP)";

function createtable
{
    psql postgres -c "CREATE TABLE bigtable (id int, data VARCHAR(500));" 
}

function copy_nowal {
    psql postgres -c "CHECKPOINT; TRUNCATE bigtable;"
    ./gendata $2 | psql postgres -c "BEGIN; TRUNCATE bigtable; COPY bigtable FROM STDIN; INSERT INTO testresult (description, begints, endts) VALUES ('copy_nowal-$1', transaction_timestamp(), clock_timestamp()); COMMIT;"
}


function copy {
    psql postgres -c "CHECKPOINT; TRUNCATE bigtable;"
    ./gendata $2 | psql postgres -c "BEGIN; COPY bigtable FROM STDIN; INSERT INTO testresult (description, begints, endts) VALUES ('copy-$1', transaction_timestamp(), clock_timestamp()); COMMIT;"
}

function selecttest {
    psql postgres <<EOF
CHECKPOINT;
BEGIN;
SELECT COUNT(*) FROM bigtable;
INSERT INTO testresult (description, begints, endts) VALUES ('select-$1', transaction_timestamp(), statement_timestamp());
COMMIT;
EOF
}

function vacuum_clean {
    psql postgres <<EOF
CHECKPOINT;
INSERT INTO testresult (description, begints) VALUES ('vacuum_clean-$1', now());
VACUUM bigtable;
UPDATE testresult SET endts = statement_timestamp() WHERE endts IS NULL;
EOF
}

function vacuum_hintbits {
    psql postgres <<EOF
BEGIN; DELETE FROM bigtable WHERE textin(tidout(ctid)) LIKE '%,1)'; ROLLBACK;
CHECKPOINT;
INSERT INTO testresult (description, begints) VALUES ('vacuum_hintbits-$1', now());
VACUUM bigtable;
UPDATE testresult SET endts = statement_timestamp() WHERE endts IS NULL;
EOF
}

function vacuum_dirty {
    psql postgres <<EOF
BEGIN; DELETE FROM bigtable WHERE textin(tidout(ctid)) LIKE '%,$2)'; COMMIT;
CHECKPOINT;
INSERT INTO testresult (description, begints) VALUES ('vacuum_dirty-$1', now());
VACUUM bigtable;
UPDATE testresult SET endts = statement_timestamp() WHERE endts IS NULL;
EOF
}


#####
createtable;

copy $LABEL $BIGTABLESIZE
copy $LABEL $BIGTABLESIZE
copy $LABEL $BIGTABLESIZE
copy_nowal $LABEL $BIGTABLESIZE
copy_nowal $LABEL $BIGTABLESIZE
copy_nowal $LABEL $BIGTABLESIZE
selecttest $LABEL
selecttest $LABEL
selecttest $LABEL
selecttest $LABEL
selecttest $LABEL
selecttest $LABEL
vacuum_clean $LABEL
vacuum_clean $LABEL
vacuum_clean $LABEL
vacuum_clean $LABEL
vacuum_hintbits $LABEL
vacuum_hintbits $LABEL
vacuum_hintbits $LABEL
vacuum_hintbits $LABEL
vacuum_dirty $LABEL 1
vacuum_dirty $LABEL 2 
vacuum_dirty $LABEL 3

psql postgres -c "SELECT description, endts-begints FROM testresult ORDER BY begints";

## end