#!/bin/bash

times=3
rows=10000000
distinct_values=1000
dbname=postgres
backup_path="/home/drowley"

psql -c "drop table if exists raw_data;" $dbname
psql -c "create table raw_data (key int not null, payload int not null);" $dbname
psql -c "insert into raw_data select x,y from generate_series(1,$distinct_values) x, generate_series(1, $rows / $distinct_values) y order by x,y" $dbname
psql -c "copy raw_data to '$backup_path/ordered.csv';" $dbname
psql -c "truncate table raw_data;" $dbname
psql -c "insert into raw_data select x,y from generate_series(1,$distinct_values) x, generate_series(1, $rows / $distinct_values) y order by y,x" $dbname
psql -c "copy raw_data to '$backup_path/unordered.csv';" $dbname
psql -c "drop table raw_data" $dbname

psql -c "drop table if exists hashp;" $dbname
psql -c "create table hashp (key int not null, payload int not null) partition by hash(key);" $dbname
for (( i=1; i<=$distinct_values; i++ ))
do
	let remainder=i-1
        psql -c "create table hashp$i partition of hashp for values with(modulus $distinct_values, remainder $remainder);" $dbname
done


for file in "ordered.csv" "unordered.csv"
do
        echo "Test: Hash $file test..."
        echo "copy hashp from '$backup_path/$file';" > bench.sql

	for (( i=1; i<=$times; i++ ))
        do
                pgbench -n -t 1 -f bench.sql $dbname
                psql -c "truncate table hashp;" $dbname
        done
done

psql -c "drop table hashp;" $dbname

psql -c "drop table if exists listp;" $dbname
psql -c "create table listp (key int not null, payload int not null) partition by list(key);" $dbname
for (( i=1; i<=$distinct_values; i++ ))
do
        psql -c "create table listp$i partition of listp for values in ($i);" $dbname
done


for file in "ordered.csv" "unordered.csv"
do
        echo "Test: List $file test..."
        echo "copy listp from '$backup_path/$file';" > bench.sql

	for (( i=1; i<=$times; i++ ))
        do
                pgbench -n -t 1 -f bench.sql $dbname
                psql -c "truncate table listp;" $dbname
        done
done


psql -c "drop table listp;" $dbname


psql -c "drop table if exists rangep;" $dbname
psql -c "create table rangep (key int not null, payload int not null) partition by range(key);" $dbname
for (( i=1; i<=$distinct_values; i++ ))
do
	let upper=i+1
        psql -c "create table rangep$i partition of rangep for values from ($i) to ($upper);" $dbname
done


for file in "ordered.csv" "unordered.csv"
do
        echo "Test: Range $file test..."
        echo "copy rangep from '$backup_path/$file';" > bench.sql

	for (( i=1; i<=$times; i++ ))
        do
                pgbench -n -t 1 -f bench.sql $dbname
                psql -c "truncate table rangep;" $dbname
        done
done


psql -c "drop table rangep;" $dbname
