#!/bin/sh

export PGDATABASE=postgres

# ARG 1 -- statement to populate narrowtable
inittest()
{
    line="$1"
    while [ ${#line} -lt 1024 ]
    do
	line="${line}$1"
    done
    
    # Escape backslashes
    line=${line//\\/\\\\}

    rm -f /tmp/copyreadline.tbl

    exec 3>/tmp/copyreadline2.tbl

    for ((i=0;i<5000;i+=1)); do
	echo "$line" >&3
    done
    
    exec 3>&-

    for ((i=0;i<100;i+=1)); do
	cat /tmp/copyreadline2.tbl >> /tmp/copyreadline.tbl
    done

    echo "input file created"
    sync
    cat /tmp/copyreadline.tbl > /dev/null # warm cache
}


initandruntests()
{
    inittest $1;
    runtest $2;
    runtest $2;
    runtest $2;
    runtest $2;
}

runtest()
{
    psql postgres <<EOF
TRUNCATE narrowtable;
CHECKPOINT;
BEGIN;
TRUNCATE narrowtable;
COPY narrowtable FROM '/tmp/copyreadline.tbl';
INSERT INTO results VALUES ('$1', transaction_timestamp(), statement_timestamp());
commit;
EOF
    psql postgres -c "SELECT testname, testend-testbegin AS duration FROM results"
}

psql -c "DROP TABLE narrowtable"
psql -c "CREATE TABLE narrowtable (t text)"

psql -c "DROP TABLE results"
psql -c "CREATE TABLE results (testname text, testbegin timestamp, testend timestamp)"

initandruntests "\\" "all";
initandruntests "1\\" "1/2";
initandruntests "123\\" "1/4";
initandruntests "1234567\\" "1/8";
initandruntests "123456789012345\\" "1/16";
initandruntests "0" "none";

psql -c "SELECT testname, testend - testbegin AS duration FROM results"
psql -c "SELECT testname, MIN(testend - testbegin) AS \"min duration\" FROM results GROUP BY testname ORDER BY MIN(testbegin)"

exit 0