Skip to content

Reset the connection whenever it's closed inside of a TransactionScope #3735

Closed

Description

@vonzshik

Whenever a pooled connection is closed inside of a TransactionScope, the next open in the same scope will return the same physical connection with already created temporary tables, sequenced and many other things. We should reset the connection, doing the same thing as with prepared statements.

Activity

  1. added this to the Backlog milestone on May 14, 2021
  2. added theissue type on Jun 14, 2025
  3. brianpursley commented on Jan 24, 2026

    @brianpursley
    Contributor

    I know this is a few years old, but it seems like it is still a problem.

    Here is some code to reproduce it:

    using System.Transactions;
    using Npgsql;
    
    const string connectionString = "Host=localhost;Username=postgres;Password=postgres;";
    
    await using var ds = NpgsqlDataSource.Create(connectionString);
    
    using var tx = new TransactionScope(TransactionScopeOption.RequiresNew, TransactionScopeAsyncFlowOption.Enabled);
    
    await using (var c = await ds.OpenConnectionAsync())
    {
        await using var cmd = new NpgsqlCommand(
            """
                create temp table temp_customer (id int, name text);
                insert into temp_customer (id, name) values (123, 'foo');
                select * from temp_customer;
            """, c);
        await using var r = await cmd.ExecuteReaderAsync();
        while (await r.ReadAsync())
        {
            Console.WriteLine($"Customer: {r.GetInt32(0)} {r.GetString(1)}");
        }
    }
    
    await using (var c = await ds.OpenConnectionAsync())
    {
        // This fails with 'relation "temp_customer" already exists' if we are unlucky enough to get the same connection as above from the connection pool.
        await using var cmd = new NpgsqlCommand(
            """
                create temp table temp_customer (id int, name text);
                insert into temp_customer (id, name) values (456, 'bar');
                select * from temp_customer;
            """, c);
        await using var r = await cmd.ExecuteReaderAsync();
        while (await r.ReadAsync())
        {
            Console.WriteLine($"Customer: {r.GetInt32(0)} {r.GetString(1)}");
        }
    }
    
    tx.Complete();
    Customer: 123 foo
    Unhandled exception. Npgsql.PostgresException (0x80004005): 42P07: relation "temp_customer" already exists
       at Npgsql.Internal.NpgsqlConnector.ReadMessageLong(Boolean async, DataRowLoadingMode dataRowLoadingMode, Boolean readingNotifications, Boolean isReadingPrependedMessage)
       at System.Runtime.CompilerServices.PoolingAsyncValueTaskMethodBuilder`1.StateMachineBox`1.System.Threading.Tasks.Sources.IValueTaskSource<TResult>.GetResult(Int16 token)
       at Npgsql.NpgsqlDataReader.NextResult(Boolean async, Boolean isConsuming, CancellationToken cancellationToken)
       at Npgsql.NpgsqlDataReader.NextResult(Boolean async, Boolean isConsuming, CancellationToken cancellationToken)
       at Npgsql.NpgsqlCommand.ExecuteReader(Boolean async, CommandBehavior behavior, CancellationToken cancellationToken)
       at Npgsql.NpgsqlCommand.ExecuteReader(Boolean async, CommandBehavior behavior, CancellationToken cancellationToken)
       at Program.<Main>$(String[] args) in /Users/bpursley/projects/npgsql-3735-repro/npgsql-3735-repro/Program.cs:line 34
       at Program.<Main>$(String[] args) in /Users/bpursley/projects/npgsql-3735-repro/npgsql-3735-repro/Program.cs:line 35
       at Program.<Main>$(String[] args) in /Users/bpursley/projects/npgsql-3735-repro/npgsql-3735-repro/Program.cs:line 39
       at Program.<Main>$(String[] args) in /Users/bpursley/projects/npgsql-3735-repro/npgsql-3735-repro/Program.cs:line 41
       at Program.<Main>(String[] args)
      Exception data:
        Severity: ERROR
        SqlState: 42P07
        MessageText: relation "temp_customer" already exists
        File: heap.c
        Line: 1160
        Routine: heap_create_with_catalog
    

    Adding discard temp in the second connection allows it to succeed.

    using System.Transactions;
    using Npgsql;
    
    const string connectionString = "Host=localhost;Username=postgres;Password=postgres;";
    
    await using var ds = NpgsqlDataSource.Create(connectionString);
    
    using var tx = new TransactionScope(TransactionScopeOption.RequiresNew, TransactionScopeAsyncFlowOption.Enabled);
    
    await using (var c = await ds.OpenConnectionAsync())
    {
        await using var cmd = new NpgsqlCommand(
            """
                create temp table temp_customer (id int, name text);
                insert into temp_customer (id, name) values (123, 'foo');
                select * from temp_customer;
            """, c);
        await using var r = await cmd.ExecuteReaderAsync();
        while (await r.ReadAsync())
        {
            Console.WriteLine($"Customer: {r.GetInt32(0)} {r.GetString(1)}");
        }
    }
    
    await using (var c = await ds.OpenConnectionAsync())
    {
        await using var cmd = new NpgsqlCommand(
            """
                discard temp;
                create temp table temp_customer (id int, name text);
                insert into temp_customer (id, name) values (456, 'bar');
                select * from temp_customer;
            """, c);
        await using var r = await cmd.ExecuteReaderAsync();
        while (await r.ReadAsync())
        {
            Console.WriteLine($"Customer: {r.GetInt32(0)} {r.GetString(1)}");
        }
    }
    
    tx.Complete();
    Customer: 123 foo
    Customer: 456 bar
    

    It seems like the problem occurs somewhere around here:
    https://github.com/brianpursley/npgsql/blob/e222c911bc25b0495e21d03df7fe6c63ef8b41e4/src/Npgsql/NpgsqlConnection.cs#L845-L887

    When there is an enlisted transaction, it doesn't reset the connection when it is closed.

  4. self-assigned this
    on Jan 25, 2026
  5. modified the milestones: Backlog, 11.0.0 on Jan 25, 2026
  6. added 2 commits that reference this issue on Jan 25, 2026
    689ce47
    93dbcbe
  7. added a commit that references this issue on Feb 9, 2026
    792a273
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions