#!/bin/bash
###SHELLPACK preamble sqlite-bench 3090200

###SHELLPACK parseargBegin
###SHELLPACK parseargInstall
###SHELLPACK parseargParam    --size         SQLITE_SIZE
###SHELLPACK parseargEnd
###SHELLPACK monitor_hooks

install-depends util-linux
###SHELLPACK check_install_required sqlite-${VERSION}
###SHELLPACK init_complete

###SHELLPACK self_extract perl-trans.pl
chmod a+x $SHELLPACK_TEMP/perl-trans.pl

cd $SHELLPACK_SOURCES/sqlite-${VERSION}-installed || die Failed to cd to sqlite install directory

echo Creating insert script for $SQLITE_SIZE entries
cat /dev/urandom | base64 -w 20 | head -$SQLITE_SIZE | sed "s/\(.\{4\}\)\(.\{16\}\)/INSERT INTO 'mmtests' ('SmallInt', 'DateTime', 'ShortString', 'LongString') VALUES ('10', CURRENT_TIMESTAMP, '\1', '\2');/" > basic-insert.script
cp basic-insert.script $LOGDIR_RESULTS/

mmtests_activity sqlite-insert
monitor_pre_hook $LOGDIR_RESULTS $P

echo Creating table
rm -f $SHELLPACK_DATA/benchmark.db
./bin/sqlite3 $SHELLPACK_DATA/benchmark.db "CREATE TABLE mmtests
	('SmallInt'    SMALLINT NOT NULL,
	 'DateTime'    TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
	 'ShortString' VARCHAR(4) NOT NULL,
	 'LongString'  VARCHAR(16) NOT NULL
	);" || die Failed to create table

echo Inserting rows
cat basic-insert.script |							\
	$TIME_CMD -o $LOGDIR_RESULTS/sqlite.time				\
		$SHELLPACK_TEMP/perl-trans.pl $SHELLPACK_DATA/benchmark.db	\
		| tee -a $LOGDIR_RESULTS/sqlite.log
	ls -lh $SHELLPACK_DATA/benchmark.db
monitor_post_hook $LOGDIR_RESULTS $P

exit $SHELLPACK_SUCCESS

==== BEGIN perl-trans.pl ====
#!/usr/bin/perl

use strict;
use Time::HiRes qw/ time sleep /;

open(SQLITE, "|./bin/sqlite3 $ARGV[0]") || die("Failed to exec sqlite3");

my $threshold = 10;
my $nr_trans = 0;
my $last_trans = 0;
my $last_time;
my $current_time = $last_time = time;

$SIG{ALRM} = sub {
	alarm 1;

	my $type = "execute";
	if ($threshold > 0) {
		$threshold--;
		$type = "warmup ";
	}
	my $current_time = time;
	my $time_diff = $current_time - $last_time;
	my $seconds_trans = ($nr_trans - $last_trans) / $time_diff;
	print "$type $seconds_trans\n";
	$last_time = $current_time;
	$last_trans = $nr_trans;
};

alarm 1;
while (!eof(STDIN)) {
	my $line = <STDIN>;
	print SQLITE $line;
	$nr_trans++;
}

alarm 0;
close(PIPE);
==== END perl-trans.pl ====
