# Test: ENABLE TRIGGER ALL on a table with a DEFERRABLE primary key brings
# back the silent duplicates in logical replication.

use strict;
use warnings FATAL => 'all';
use PostgreSQL::Test::Cluster;
use PostgreSQL::Test::Utils;
use Test::More;
use Time::HiRes qw(usleep time);

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

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

my $connstr = $publisher->connstr . ' dbname=postgres';

# The same table on both sides.  The subscriber already has a row with id 1.
$publisher->safe_psql(
	'postgres', q{
	CREATE TABLE t (id int PRIMARY KEY DEFERRABLE INITIALLY DEFERRED);
	CREATE PUBLICATION pub FOR TABLE t;
});
$subscriber->safe_psql(
	'postgres', q{
	CREATE TABLE t (id int PRIMARY KEY DEFERRABLE INITIALLY DEFERRED);
	INSERT INTO t VALUES (1);
});
$subscriber->safe_psql('postgres',
	"CREATE SUBSCRIPTION sub CONNECTION '$connstr' PUBLICATION pub
	 WITH (copy_data = false)");
$publisher->wait_for_catchup('sub');

# Premise: the recheck trigger of the primary key is ENABLE ALWAYS.
my $trigger_state = q{SELECT tgenabled FROM pg_trigger
	WHERE tgrelid = 't'::regclass AND tgisinternal
	  AND tgfoid = 'unique_key_recheck'::regproc};
is($subscriber->safe_psql('postgres', $trigger_state),
	'A', 'premise: the recheck trigger is ENABLE ALWAYS');

# What pg_restore --disable-triggers does after loading data.
$subscriber->safe_psql('postgres', "ALTER TABLE t ENABLE TRIGGER ALL");

# A change that conflicts with the local row 1.
my $offset = -s $subscriber->logfile;
$publisher->safe_psql('postgres', "INSERT INTO t VALUES (1)");

# Wait for the outcome: either the row is committed, or the apply worker fails.
my $applied = 0;
for (my $i = 0; $i < 150 && !$applied; $i++)
{
	$applied =
	     $subscriber->safe_psql('postgres', "SELECT count(*) FROM t") > 1
	  || slurp_file($subscriber->logfile, $offset) =~ /duplicate key|ERROR/;
	usleep(100_000) unless $applied;
}
ok($applied, 'premise: the replicated INSERT was either applied or rejected');

# The only check that fails with the patch as posted.
is( $subscriber->safe_psql(
		'postgres',
		"SELECT count(*) FROM (SELECT id FROM t GROUP BY id HAVING count(*) > 1) d"
	),
	'0',
	'no duplicate key is committed after ENABLE TRIGGER ALL');

done_testing();
