Skip to content

StateChange event no longer fires when connection is observed to be killed #3442

@madelson

Description

@madelson

Steps to reproduce

Here is an NUnit test that reproduces the issue for me. As mentioned in the comments, it passes using 4.1.4 of Npgsql and fails when updated to 5.0.1.1.

        [Test]
        public async Task TestExecutingQueryOnKilledConnectionFiresStateChanged()
        {
            using var stateChangedEvent = new ManualResetEventSlim(initialState: false);

            using var connection = new NpgsqlConnection("valid connection string here");
            await connection.OpenAsync();
            connection.StateChange += (o, e) => stateChangedEvent.Set();

            using var getPidCommand = connection.CreateCommand();
            getPidCommand.CommandText = "SELECT pg_backend_pid()";
            var pid = (int)(await getPidCommand.ExecuteScalarAsync());

            Assert.AreEqual(ConnectionState.Open, connection.State);

            // kill the connection from the back end
            using var killingConnection = new NpgsqlConnection(TestingPostgresDb.ConnectionString);
            await killingConnection.OpenAsync();
            using var killCommand = killingConnection.CreateCommand();
            killCommand.CommandText = $"SELECT pg_terminate_backend({pid})";
            await killCommand.ExecuteNonQueryAsync();

            Assert.ThrowsAsync<PostgresException>(() => getPidCommand.ExecuteScalarAsync());
            Assert.AreNotEqual(ConnectionState.Open, connection.State);

            Assert.IsTrue(stateChangedEvent.Wait(TimeSpan.FromSeconds(5))); // assertion passes in 4.1.4, fails in 5.0.1.1
        }

The issue

The connection's StateChange event should fire whenever the connection state is observed to have changed, such as when running a query against a connection that turns out to have been killed. This worked in the version of Npgsql I was upgrading from and works with MSFT's SqlServer ADO providers.

Further technical details

Npgsql version: 4.1.4 -> 5.0.1.1
PostgreSQL version: 12
Operating system: Windows 10

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions