# Test postgres_fdw reaction on target server disconnection

use strict;
use warnings;

use PostgreSQL::Test::Utils;
use Test::More tests => 1;
use PostgreSQL::Test::Cluster;

use Time::HiRes qw( time );
use DateTime;

use threads;
use threads::shared;

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

$local->append_conf(
	'postgresql.conf', qq{
log_min_messages = DEBUG1
log_min_error_statement = log
log_connections = on
log_disconnections = on
log_line_prefix = '%m|%u|%d|%c|'
log_statement = 'all'
	});
$local->start();

diag(`ipconfig`);

$local->safe_psql('postgres', qq{
CREATE EXTENSION postgres_fdw;
CREATE SERVER fpg FOREIGN DATA WRAPPER postgres_fdw OPTIONS (dbname 'postgres', host '1.0.0.150', port '54321');
CREATE USER MAPPING FOR CURRENT_USER SERVER fpg;
CREATE FUNCTION fx2(i integer) RETURNS int AS 'begin return i * 2; end;' LANGUAGE plpgsql;
});

$local->safe_psql('postgres', 'IMPORT FOREIGN SCHEMA public FROM SERVER fpg INTO public;');
print($local->psql('postgres', 'EXPLAIN (VERBOSE) SELECT * FROM large WHERE a = fx2(a)') . "\n");
for (my $i = 0; $i < 20; $i++) {
	diag(DateTime->from_epoch( epoch => time )->strftime('%H:%M:%S.%6N') . " executing query...");
	my ($ret, $stdout, $stderr) = $local->psql('postgres', 'SELECT * FROM large WHERE a = fx2(a)');
	diag(DateTime->from_epoch( epoch => time )->strftime('%H:%M:%S.%6N') . " result: \t$ret\n$stdout\n$stderr");
	sleep(0.2);
}
ok(1);
