#!/bin/bash


#Set PG variables
#set PGDATA=E:\WorkSpace\PostgreSQL\master\Data
#set PGPORT=5432
#set PATH=E:\WorkSpace\PostgreSQL\master\installation;%PATH%
export PGDATA=/mnt/data-mag/amit.kapila/pgdata_300
export PGPORT=5432
export LD_LIBRARY_PATH=/home/amit.kapila/workspace/master/installation/lib:$LD_LIBRARY_PATH

#config_values
no_of_rows=50000000
shared_bufs=8GB
run_bin="org_rel"


drop_sequence_clog_access="drop sequence if exists clog_access_test_c1_seq CASCADE"
create_sequence_clog_access="create sequence clog_access_test_c1_seq"
create_clog_access="create table clog_access_test(c1 bigint default nextval('clog_access_test_c1_seq'::regclass), c2 int)"
drop_clog_access="drop table if exists clog_access_test CASCADE"
create_index_clog_access="create index idx_clog on clog_access_test(c1)"
drop_index_clog_access="drop index if exists idx_clog"
insert_clog_access="insert into clog_access_test (c2) values(100)"
create_func_clog_disk="create or replace function func_clog_disk(c1_param int8, nrows int8, delta integer) returns integer
as \$\$
Declare
var int;
c2_var int;
begin
		-- maximum number of transactions that can be accomodated in 
		-- clog buffers (considering 32 such buffers). This is required
		-- to access each time a row with xid that is n transactions
		-- (equivalent to pages in Clog bufffers) far.
		var := 1048576;

		c1_param := c1_param + var;
		IF (c1_param > nrows) THEN
			c1_param := c1_param - nrows;
		END IF;
		RAISE NOTICE 'value of c1_param(%)', c1_param;
        	UPDATE clog_access_test SET c2 = c2 + delta WHERE c1 = c1_param;
		SELECT c2 into c2_var FROM clog_access_test WHERE c1 = c1_param;
		return 1;
end;
\$\$ language plpgsql"


echo "============== $run_bin =============" >> test_results.txt
cp postgres_${run_bin} postgres

#Start the server
./postgres -c shared_buffers=$shared_bufs &

sleep 5 

#Setup the objects.
./psql -d postgres -c "$drop_index_clog_access"
./psql -d postgres -c "$drop_clog_access"
./psql -d postgres -c "$drop_sequence_clog_access"
./psql -d postgres -c "$create_sequence_clog_access"
./psql -d postgres -c "$create_clog_access"
./psql -d postgres -c "$create_index_clog_access"
./psql -d postgres -c "$create_func_clog_disk"

#echo "================================================"  >> test_results.txt
#echo ${insert_clog_access} No of rows - ${no_of_rows} >> test_results.txt
for ((count_stmt = 1; count_stmt < $no_of_rows; count_stmt++))
do
	# Run Statement
	./psql -d postgres -c "$insert_clog_access"
done;


./psql -d postgres -c "checkpoint" >> test_results.txt
./pg_ctl stop
sleep 1


mv test_results.txt test_results_${run_bin}.txt
