use strict;
use warnings;
use DBI;
use Data::Dumper;
use List::Util qw(shuffle);
use Digest::MD5 qw(md5_hex);

## centralize connections to one place, in case we want to point to a remote server or use a password
sub dbconnect {
  my $dbh = DBI->connect("dbi:Pg:", "", "", {AutoCommit => 1, RaiseError=>1, PrintError=>0});
  return $dbh;
};

my $dbh = dbconnect();
eval { ## on multiple times through, the table already exists, just let it fail
       ## But if the table exists, don't pollute the log with errors
       ($dbh->selectrow_array("select count(*) from pg_tables where tablename='foo';"))[0] == 1 and return;
       $dbh->do(<<'END');
create table foo(index int, count int, text_array text[]);
create unique index on foo(index);
create index on foo using gin (text_array);
END
};

unless (defined $ARGV[1]) {
  # if just given one argument, it is number of rows to insert at the end of existing rows
  my ($max)=$dbh->selectrow_array('select max(index) from foo');
  $max//=1;
  $ARGV[1]=$ARGV[0]+$max;
  $ARGV[0]=$max+1;
};

my $sth=$dbh->prepare("insert into foo (index, count, text_array) values (?,0,?)");
$dbh->begin_work();
my $count=0;
foreach ($ARGV[0]..$ARGV[1]) { 
  $sth->execute($_, [map md5_hex($_), shuffle ($_, map {-int(rand()*10_000)-10} 1..100)] );
  warn "$count" unless ++$count%1000;
};
$dbh->commit();
