# Copyright (c) 2021-2024, PostgreSQL Global Development Group

# Basic logical replication test
use strict;
use warnings FATAL => 'all';
use PostgreSQL::Test::Cluster;
use PostgreSQL::Test::Utils;
use Test::More;

# Initialize publisher node
my $node_publisher = PostgreSQL::Test::Cluster->new('publisher');
$node_publisher->init(allows_streaming => 'logical');

$node_publisher->append_conf('postgresql.conf',
qq{
autovacuum_naptime = 1
autovacuum_vacuum_threshold = 1
});
    
$node_publisher->start;

# Create subscriber node
my $node_subscriber = PostgreSQL::Test::Cluster->new('subscriber');
$node_subscriber->init;
$node_subscriber->start;

# Create some preexisting content on publisher
$node_publisher->safe_psql('postgres',
	"CREATE TABLE tab_rep (a int primary key)");

# Setup structure on subscriber
$node_subscriber->safe_psql('postgres',
	"CREATE TABLE tab_rep (a int primary key)");

# Setup logical replication
my $publisher_connstr = $node_publisher->connstr . ' dbname=postgres';
$node_publisher->safe_psql('postgres', "CREATE PUBLICATION tap_pub");
$node_publisher->safe_psql('postgres', "ALTER PUBLICATION tap_pub ADD TABLE tab_rep");

$node_subscriber->safe_psql('postgres',
	"CREATE SUBSCRIPTION tap_sub CONNECTION '$publisher_connstr' PUBLICATION tap_pub"
);

# Wait for initial table sync to finish
$node_subscriber->wait_for_subscription_sync($node_publisher, 'tap_sub');

for (my $i = 1; $i <= 100; $i++)
{
$node_publisher->wait_for_catchup('tap_sub');
diag("$i");

$node_publisher->safe_psql('postgres',
	"INSERT INTO tab_rep SELECT generate_series(1, (random() * 40000)::integer) ");
$node_publisher->safe_psql('postgres', "DELETE FROM tab_rep");

$node_publisher->stop('fast');
$node_publisher->start();
}

ok(1);
done_testing();
