I want to open several connections within the same transaction so that each connection can see the changes made by the previous ones.
I need this for tests - the real code is written to the database, and the test code checks to see if the data has really been inserted / updated. At the end, I discard the transaction transaction, so as not to affect the real database.
This approach works fine in SQL Server, but doesn't seem to work in PostgreSQL (I use 9.3 with the Npgsql provider), a small example is provided below.
Here's a helper for starting an arbitrary request within a transaction
private void RunQuery(string query, Action<IDataReader> process) { using (var connection = new NpgsqlConnection(Config.ConnectionString)) { connection.Open(); connection.EnlistTransaction(Transaction.Current); using (var command = connection.CreateCommand()) { command.CommandText = query; using (var reader = command.ExecuteReader()) { while (reader.Read()) { process(reader); } } } } }
.. and here is the test code - it inserts into the users table and then checks if the user was really inserted:
using (var scope = new TransactionScope()) {
The test above does not work in Postgres, since id2 always zero. I tried the TransactionScope constructor with TransactionOptions.ReadUncommitted , but it doesn't seem to help. Note that if I run this for SQL Server (change NpgsqlConnection to SqlConection , use SCOPE_IDENTITY to extract the identifier), then everything will work fine, and id2 not zero.
As you expect, it selects connections for Postgres within the same work, but I do not need it, my goal is to use several connections in the general transaction area. I also do not need multithreading, these connections occur sequentially.