Skip to content

Commit dff2802

Browse files
committed
Revert "Found sad disposal transaction in async execution. :( This seems to be impossible."
This reverts commit 16545fd.
1 parent 65a02aa commit dff2802

2 files changed

Lines changed: 63 additions & 0 deletions

File tree

DirectSQL/Database.cs

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -387,6 +387,32 @@ public static void Transaction(
387387
}
388388
}
389389

390+
/// <summary>
391+
/// Execute in a transaction asynchronously.
392+
/// </summary>
393+
/// <param name="connection">connection to be used</param>
394+
/// <param name="execute">to be executed</param>
395+
/// <returns>A task stands for asynchronous execution</returns>
396+
public static async Task TransactionAsync(
397+
C connection,
398+
AsyncSqlExecution<C,T> execute)
399+
{
400+
using (var transaction = (T) connection.BeginTransaction())
401+
{
402+
try
403+
{
404+
await execute(connection, transaction);
405+
}
406+
catch (Exception exception)
407+
{
408+
transaction.Rollback();
409+
throw new DatabaseException(
410+
MessageResource.msg_error_sqlExecutionError,
411+
exception);
412+
}
413+
}
414+
}
415+
390416
private static(String sql, (String,Object)[] parameters) ExtractSqlAndParam(FormattableString sqlFormattableString)
391417
{
392418
var paramNames =

TestSqlLiteDatabase/TransactionTest.cs

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,43 @@ public void TestTransaction()
4848
});
4949
}
5050

51+
[TestMethod]
52+
public void TestTransactionAsync()
53+
{
54+
SqlLiteDatabase db = new SqlLiteDatabase("Data Source=:memory:");
55+
56+
db.Process(async (connection) => {
57+
CreateTableForTest(connection);
58+
59+
await SqlLiteDatabase.TransactionAsync(connection,
60+
async (conn, tran) => {
61+
await Task.Delay(1);
62+
InsertDataForTest(conn, tran);
63+
tran.Rollback();
64+
}
65+
);
66+
67+
await SqlLiteDatabase.TransactionAsync(connection,
68+
async (conn, tran) =>
69+
{
70+
await Task.Delay(1);
71+
AssertDataCount(0, conn, tran);
72+
InsertDataForTest(conn, tran);
73+
AssertDataCount(1, conn, tran);
74+
tran.Commit();
75+
}
76+
);
77+
78+
await SqlLiteDatabase.TransactionAsync(connection,
79+
async (conn, tran) =>
80+
{
81+
await Task.Delay(1);
82+
AssertDataCount(1, conn, tran);
83+
}
84+
);
85+
});
86+
}
87+
5188
private static void AssertDataCount(long expectedCount,SQLiteConnection conn, SQLiteTransaction tran)
5289
{
5390
Assert.AreEqual(

0 commit comments

Comments
 (0)