use strict;
use warnings FATAL => 'all';
use PostgreSQL::Test::Cluster;
use PostgreSQL::Test::Utils;
use Test::More;
use Time::HiRes qw(usleep);

# Initialize publisher node
my $node_publisher = PostgreSQL::Test::Cluster->new('publisher');
$node_publisher->init(allows_streaming => 'logical', extra => ['--wal-segsize=1']);
$node_publisher->append_conf(
	'postgresql.conf', q[
logical_decoding_work_mem = 64kB
max_connections = 100001
wal_sender_timeout = 0
log_statement = none
log_rotation_size = 10MB
debug_logical_replication_streaming = immediate
]);
$node_publisher->start;

# Create subscriber node
my $node_subscriber = PostgreSQL::Test::Cluster->new('subscriber');
$node_subscriber->init;
$node_subscriber->append_conf(
	'postgresql.conf', q[
wal_receiver_timeout = 0
]);
$node_subscriber->start;

my $publisher_connstr = $node_publisher->connstr . ' dbname=postgres';

$node_publisher->safe_psql(
	'postgres', qq(
	CREATE TABLE t1(c1 int);
	CREATE PUBLICATION pub for table t1;
));

$node_subscriber->safe_psql(
	'postgres', qq(
	CREATE TABLE t1(c1 int);
	CREATE SUBSCRIPTION sub CONNECTION '$publisher_connstr' PUBLICATION pub with (streaming=off);
));

my $psql_timeout_secs = 1000 * $PostgreSQL::Test::Utils::timeout_default;

# set no. of subtransactions. No. of subtransaction = no. of spill files generated
my $count = 1000;
my @background_psql_array;

my $background_psql = $node_publisher->background_psql(
'postgres',
on_error_stop => 0,
timeout => $psql_timeout_secs);

$background_psql->query_safe('BEGIN;');
for my $in(1 .. $count)
{
	$background_psql->query_safe(qq[INSERT INTO t1 VALUES ($in);]);
	$background_psql->query_safe(qq[SELECT pg_switch_wal();]);
	$background_psql->query_safe(qq[SAVEPOINT s$in]);
}

$background_psql->query_safe(qq[COMMIT;]);
sleep(3600);
 
$background_psql->quit;

$node_publisher->stop('fast');
$node_subscriber->stop('fast');
