#!/usr/bin/perl

use warnings;
use strict;

use DBI;

my ($conn, $insert, $update);

$conn = DBI->connect('dbi:Pg:dbname=alvherre port=55432 host=/tmp', '', '', {AutoCommit => 1});
$conn->{pg_prepare_now} = 1;

$conn->do("drop table if exists brintest");
$conn->do("create table brintest (id serial, a integer, b text, c text)");
$conn->do("create index brinidx on brintest using brin (a, b, c) with (pages_per_range=1)");

$insert = $conn->prepare("insert into brintest (a, b, c) values (?, ?, 'this is a very long text intended to make each brin tuple a bit larger than it should really be, because only because I am an annoying person') returning id");
$update = $conn->prepare("update brintest set a = a + ?, b = ? where id = ?");

my $total = 100000;
my $i = 0;
my $lastval;

my @letters = ("a" .. "z");

$insert->execute(int(rand(1000)), 'foo');
$lastval = $insert->fetch()->[0];

my $thresh = 1;
my $maxlength = 4;
while ($i++ < $total) {
	my $prob = rand(1);

	if ($prob < $thresh) {
		$insert->execute(int(rand(1000)), 'foo');
		$lastval = $insert->fetch()->[0];
		$thresh *= 0.99;
	} else {
		my $length = rand($maxlength);
		$maxlength++ if $length >= $maxlength / 2;
		my $b = "";
		while ($length-- > 0) {
			$b = $b . $letters[rand $#letters];
		}

		$update->execute(
			int(rand(100)), 
			$b,
			int(rand($lastval + 1)));
	}

	if ($prob > 0.95) {
		$conn->do('vacuum brintest');
	}
}
