#! /usr/bin/perl

use strict;
use warnings;

use Time::HiRes;
use DBI;

my $rows= 0.2e6;
my $chars= ['0'..'9', 'A'..'Z', 'a'..'z', '_', '.', '/', '-'];
my $rowlen= 1000;

my $chars_count= scalar(@$chars);
my $sock= $ARGV[0];
my $dbh1= DBI->connect("DBI:mysql:database=test;host=localhost;mysql_socket=$sock",
                       "root", undef, {RaiseError=>1, AutoCommit=>0});
my $dbh2= DBI->connect("DBI:mysql:database=test;host=localhost;mysql_socket=$sock",
                       "root", undef, {RaiseError=>1, AutoCommit=>0});
my $dbh3= DBI->connect("DBI:mysql:database=test;host=localhost;mysql_socket=$sock",
                       "root", undef, {RaiseError=>1, AutoCommit=>0});

$dbh1->do('CREATE OR REPLACE TABLE t1 (a INT PRIMARY KEY, b VARCHAR(1024)) ENGINE=InnoDB');

# A large transaction to test impact of checksum pre-compute on commit stall.
for my $i (1..$rows) {
  my $val= join('', map($chars->[rand($chars_count)], (1..$rowlen)));
  $dbh1->do('INSERT INTO t1 VALUES (?, ?)', undef, $i, $val);
}

# Two small connections to time the stall from commit of the large one.

$dbh2->do('INSERT INTO t1 VALUES (?, ?)', undef, -1, 'A');
$dbh3->do('INSERT INTO t1 VALUES (?, ?)', undef, -2, 'B');

my $t0= [Time::HiRes::gettimeofday()];
$dbh2->commit;
my $t1= [Time::HiRes::gettimeofday()];
$dbh1->commit;
my $elapsed1= Time::HiRes::tv_interval($t1, [Time::HiRes::gettimeofday()]);
$dbh3->commit;
my $elapsed0= Time::HiRes::tv_interval($t0, [Time::HiRes::gettimeofday()]);

my ($check_count)= $dbh1->selectrow_array('SELECT COUNT(*) FROM t1');
print "Table rows: $check_count\n";
print "Time for all commits: ", $elapsed0, "\n";
print "Time for big commits: ", $elapsed1, "\n";
