npgsql: Error when autopreparing statement replaces another which is later used in the same command

When executing a batched command, an earlier statement which hits the autoprepare threshold may end up replacing a statement that is executed later in the same batch. This causes a total mismatch as the later statement executes with the earlier statement’s server-side prepared statement.

Minimal repro:

[Test, IssueLink("https://github.com/npgsql/npgsql/issues/2026")]
public void EarlierStatementReplacesLaterInBatch()
{
    var connectionString = new NpgsqlConnectionStringBuilder(ConnectionString)
    {
        Pooling = false,
        MaxAutoPrepare = 1,
        AutoPrepareMinUsages = 5
    };

    using (var conn = OpenConnection(connectionString))
    {
        using (var cmd1 = new NpgsqlCommand("SELECT @p1", conn))
        using (var cmd2 = new NpgsqlCommand("SELECT @p2+1; SELECT @p1", conn))
        {
            cmd1.Parameters.Add(new NpgsqlParameter { ParameterName = "p1", Value = "foo" });
            for (var i = 0; i < 5; i++)
                cmd1.ExecuteNonQuery();
            // cmd1 should now be autoprepared

            cmd2.Parameters.Add(new NpgsqlParameter { ParameterName = "p1", Value = "foo"});
            cmd2.Parameters.Add(new NpgsqlParameter { ParameterName = "p2", Value = 8 });
            for (var i = 0; i < 5; i++)
                cmd2.ExecuteNonQuery();
        }
    }
}

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Comments: 18 (11 by maintainers)

Most upvoted comments

One more thing - when you do have a repro, please open a new issue. This issue is specifically the interaction between auto-preparation and batching, where the same statement is prepared and then replaced within the same batch. That’s quite an edge case and doesn’t sound like your problem.