#!/bin/bash

dbname=postgres
times=5
gigabytes=10

psql -c "alter system set max_parallel_workers_per_gather TO 0;" $dbname
psql -c "alter system set jit to 0;" $dbname
psql -c "select pg_reload_conf();" $dbname

for cols in 6 7 8 9 10 11 12 13 14
do

	sql="("
	psql -c "drop table if exists t" $dbname
	psql -c "drop table if exists tsize" $dbname
	i=1
	while [ $i -lt $cols ]
	do
		sql+="c$i BIGINT NOT NULL DEFAULT 0,"
		i=$[$i+1]
	done
	sql+="c$cols BIGINT NOT NULL DEFAULT 0);"
	echo "NOTICE: Creating $cols column $gigabytes gigabyte table"

	# use the tsize table just to figure out how many of these rows we can fit on a page
	psql -c "create table tsize$sql" $dbname
	# 300 rows should always fill at least 1 page
	psql -c "insert into tsize (c1) select x from generate_series(1,300) x" $dbname
	psql -c "create table t$sql" $dbname
	# insert enough rows for $gigabytes gigabytes data
	psql -c "insert into t (c1) select x from generate_Series(1, (select count(*) * ($gigabytes::bigint*1024*1024*1024/8192) from tsize where ctid < '(1,0)')) x;" $dbname
	psql -c "vacuum freeze t" $dbname

	for mem in "4MB" "8MB" "16MB" "32MB" "64MB" "128MB" "256MB" "512MB" "1024MB" "2048MB" "4096MB" "8192MB" "16384MB"
	do
	        psql -c "alter system set work_mem TO '$mem';" $dbname
	        psql -c "select pg_reload_conf();" $dbname

		echo "NOTICE: $cols column $gigabytes gigabyte table with work_mem of $mem"
	        for sql in "select * from t order by c1 offset 1000000000000"
	        do
	                echo "$sql" > bench.sql
	                pgbench -n -f bench.sql -t $times -M prepared $dbname
	        done
	done	
done
