use strict;
use warnings FATAL => 'all';
use PostgreSQL::Test::Cluster;
use PostgreSQL::Test::Utils;
use Test::More;

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

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

$node_publisher->safe_psql(
	'postgres', qq(
	CREATE TABLE tab (a int);
	CREATE PUBLICATION tap_pub FOR TABLE tab;
));
$node_subscriber->safe_psql('postgres', 'CREATE TABLE tab (a int)');

# With copy_data = false, the relation is ready immediately.
my $publisher_connstr = $node_publisher->connstr . ' dbname=postgres';
$node_subscriber->safe_psql('postgres',
	"CREATE SUBSCRIPTION tap_sub CONNECTION '$publisher_connstr' PUBLICATION tap_pub WITH (copy_data = false)"
);

$node_publisher->safe_psql('postgres',
	'ALTER PUBLICATION tap_pub DROP TABLE tab');

is( $node_subscriber->safe_psql(
		'postgres',
		q(SELECT srrelid::regclass, srsubstate FROM pg_subscription_rel
		  WHERE srsubid = (SELECT oid FROM pg_subscription
		                   WHERE subname = 'tap_sub'))),
	'tab|r',
	'publication change leaves the subscription relation until refresh');

# Refresh calls RemoveSubscriptionRel() with both relation and subscription
# OIDs. We are testing the scan keys orders: (srrelid, srsubid) or 
# (srsubid, srrelid)?
my ($ret, $stdout, $stderr) = $node_subscriber->psql('postgres',
	'ALTER SUBSCRIPTION tap_sub REFRESH PUBLICATION WITH (copy_data = false)');
is($ret, 0, 'refresh publication succeeds with both scan keys')
  or diag($stderr);

is( $node_subscriber->safe_psql(
		'postgres', 'SELECT count(*) FROM pg_subscription_rel'),
	'0',
	'refresh removes the subscription relation');

$node_subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION tap_sub');
$node_subscriber->stop('fast');
$node_publisher->stop('fast');

done_testing();
