Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP Add support for BeginTransactionAsync #3139

Open
wants to merge 32 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 21 commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
59c108f
Generate Async Code of .NET Standard 2.1
hazzik Aug 29, 2022
38ae990
Add shim for DbConnection.BeginTransactionAsync
hazzik Aug 29, 2022
8b483e8
Generate async files
github-actions[bot] Aug 29, 2022
691e967
Update AsyncGenerator.yml
hazzik Aug 29, 2022
e196880
Rename AsynExtensions.cs to AsyncExtensions.cs
hazzik Aug 29, 2022
685267a
Generate async files
github-actions[bot] Aug 29, 2022
d4f9e18
Update AsyncGenerator.yml
hazzik Sep 1, 2022
6d46bf6
Generate async files
github-actions[bot] Sep 1, 2022
de5e256
Update AsyncExtensions.cs
hazzik Sep 1, 2022
d5f6eeb
Update AsyncGenerator.yml
hazzik Sep 1, 2022
85e62a5
Generate async files
github-actions[bot] Sep 1, 2022
78ffed7
Update ITransaction.cs
hazzik Sep 1, 2022
69376ba
Update AsyncGenerator.yml
hazzik Sep 1, 2022
b5a3e35
Update ITransaction.cs
hazzik Sep 1, 2022
275cdd1
Generate async files
github-actions[bot] Sep 1, 2022
d792db3
Update AsyncExtensions.cs
hazzik Sep 1, 2022
c0e48ad
Fix async extensions
hazzik Sep 1, 2022
15c32ee
Register AsyncExtensions.cs
hazzik Sep 14, 2022
dad96b8
Make IDriver not partial
hazzik Sep 14, 2022
2e79402
Update AsyncGenerator.yml
hazzik Sep 14, 2022
8e434c6
Merge branch 'master' into begin-transaction-async
hazzik Sep 14, 2022
fccd63c
Update dotnet-tools.json
hazzik Sep 15, 2022
2146533
Generate async files
github-actions[bot] Sep 15, 2022
f344e0f
Update AsyncGenerator.yml
hazzik Sep 15, 2022
0ec8c4f
Update AsyncGenerator.yml
hazzik Sep 15, 2022
c5f899d
Update AsyncGenerator.yml
hazzik Sep 15, 2022
13e53c4
Update AsyncGenerator.yml
hazzik Sep 15, 2022
7a482b9
Update AsyncGenerator.yml
hazzik Sep 15, 2022
b446b28
Update AsyncGenerator.yml
hazzik Sep 15, 2022
74415d1
Update AsyncGenerator.yml
hazzik Sep 15, 2022
5c98a54
Generate async files
github-actions[bot] Sep 15, 2022
626fa94
Merge branch 'master' into begin-transaction-async
hazzik Jan 22, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions src/AsyncGenerator.yml
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,9 @@
- conversion: ToAsync
name: ExecuteNonQuery
containingTypeName: IBatcher
- conversion: ToAsync
name: BeginTransaction
containingTypeName: DriverBase
- conversion: ToAsync
rule: EventListener
- conversion: ToAsync
Expand All @@ -139,6 +142,10 @@
- conversion: Ignore
name: DependentContext
containingTypeName: AdoNetWithSystemTransactionFactory
asyncExtensionMethods:
projectFiles:
- fileName: AsyncExtensions.cs
hazzik marked this conversation as resolved.
Show resolved Hide resolved
projectName: NHibernate
ignoreSearchForAsyncCounterparts:
- name: GetFieldValue
- name: IsDBNull
Expand Down Expand Up @@ -212,6 +219,8 @@
projectFiles:
- fileName: LinqExtensionMethods.cs
projectName: NHibernate
- fileName: AsyncExtensions.cs
hazzik marked this conversation as resolved.
Show resolved Hide resolved
projectName: NHibernate
typeConversion:
- conversion: Ignore
name: ObjectAssert
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,16 @@ public async Task ShouldNotifyAfterTransactionWithOwnConnectionAsync(bool usePre
public partial class CustomTransaction : ITransaction
{

public Task BeginAsync()
{
throw new NotImplementedException();
}

public Task BeginAsync(IsolationLevel isolationLevel)
{
throw new NotImplementedException();
}

public Task CommitAsync(CancellationToken cancellationToken = default(CancellationToken))
{
throw new NotImplementedException();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -548,7 +548,7 @@ protected DateTimeKind GetTypeKind()
}
}

public class ClientDriverWithParamsStats : IDriver
public partial class ClientDriverWithParamsStats : IDriver
{
private readonly Dictionary<SqlType, int> _usedSqlTypes = new Dictionary<SqlType, int>();
private readonly Dictionary<DbType, int> _usedDbTypes = new Dictionary<DbType, int>();
Expand Down
43 changes: 43 additions & 0 deletions src/NHibernate/AdoNet/AsyncExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
#if NETFX || NETSTANDARD2_0 || NETCOREAPP2_0
using System;
using System.Data;
using System.Data.Common;
using System.Threading;
using System.Threading.Tasks;

namespace NHibernate
{
internal static class AsyncExtensions
{
public static Task<DbTransaction> BeginTransactionAsync(this DbConnection connection, CancellationToken cancellationToken = default)
hazzik marked this conversation as resolved.
Show resolved Hide resolved
{
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled<DbTransaction>(cancellationToken);

try
{
return Task.FromResult(connection.BeginTransaction());
}
catch (Exception ex)
{
return Task.FromException<DbTransaction>(ex);
}
}

public static Task<DbTransaction> BeginTransactionAsync(this DbConnection connection, IsolationLevel isolationLevel, CancellationToken cancellationToken = default)
{
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled<DbTransaction>(cancellationToken);

try
{
return Task.FromResult(connection.BeginTransaction(isolationLevel));
}
catch (Exception ex)
{
return Task.FromException<DbTransaction>(ex);
}
}
}
}
#endif
2 changes: 1 addition & 1 deletion src/NHibernate/AdoNet/ResultSetWrapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ namespace NHibernate.AdoNet
/// and Postgres).
/// </summary>
/// <seealso cref="IDataRecord.GetOrdinal"/>
public class ResultSetWrapper : DbDataReader
public partial class ResultSetWrapper : DbDataReader
{
private DbDataReader rs;
private readonly ColumnNameCache columnNameCache;
Expand Down
14 changes: 14 additions & 0 deletions src/NHibernate/Async/AdoNet/ConnectionManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,20 @@ async Task<DbConnection> InternalGetConnectionAsync()
}
}

public async Task<ITransaction> BeginTransactionAsync(IsolationLevel isolationLevel)
{
EnsureTransactionIsCreated();
await (_transaction.BeginAsync(isolationLevel)).ConfigureAwait(false);
return _transaction;
}

public async Task<ITransaction> BeginTransactionAsync()
{
EnsureTransactionIsCreated();
await (_transaction.BeginAsync()).ConfigureAwait(false);
return _transaction;
}

public async Task<DbCommand> CreateCommandAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
Expand Down
51 changes: 51 additions & 0 deletions src/NHibernate/Async/Driver/DriverBase.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by AsyncGenerator.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------


using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using NHibernate.Engine;
using NHibernate.SqlCommand;
using NHibernate.SqlTypes;
using NHibernate.Util;
using Environment = NHibernate.Cfg.Environment;

namespace NHibernate.Driver
{
using System.Threading.Tasks;
public abstract partial class DriverBase : IDriver, ISqlParameterFormatter
{

/// <summary>
/// Begin an ADO <see cref="DbTransaction" />.
/// </summary>
/// <param name="isolationLevel">The isolation level requested for the transaction.</param>
/// <param name="connection">The connection on which to start the transaction.</param>
/// <returns>The started <see cref="DbTransaction" />.</returns>
public virtual Task<DbTransaction> BeginTransactionAsync(IsolationLevel isolationLevel, DbConnection connection)
{
try
{
return Task.FromResult<DbTransaction>(BeginTransaction(isolationLevel, connection));
}
catch (Exception ex)
{
return Task.FromException<DbTransaction>(ex);
}
}

#if NETFX
#else

#endif
}
}
54 changes: 54 additions & 0 deletions src/NHibernate/Async/Driver/DriverExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by AsyncGenerator.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------


using System.Data;
using System.Data.Common;
using NHibernate.AdoNet;
using NHibernate.SqlTypes;
using NHibernate.Util;

namespace NHibernate.Driver
{
using System.Threading.Tasks;
public static partial class DriverExtensions
{

// 6.0 TODO: merge into IDriver
/// <summary>
/// Begin an ADO <see cref="DbTransaction" />.
/// </summary>
/// <param name="driver">The driver.</param>
/// <param name="isolationLevel">The isolation level requested for the transaction.</param>
/// <param name="connection">The connection on which to start the transaction.</param>
/// <returns>The started <see cref="DbTransaction" />.</returns>
public static Task<DbTransaction> BeginTransactionAsync(this IDriver driver, IsolationLevel isolationLevel, DbConnection connection)
{
try
{
if (driver is DriverBase driverBase)
{
return driverBase.BeginTransactionAsync(isolationLevel, connection);
}

// So long for custom drivers not deriving from DriverBase, they will have to wait for 6.0 if they
// need the feature.
if (isolationLevel == IsolationLevel.Unspecified)
{
return Task.FromResult<DbTransaction>(connection.BeginTransaction());
}
return Task.FromResult<DbTransaction>(connection.BeginTransaction(isolationLevel));
}
catch (System.Exception ex)
{
return Task.FromException<DbTransaction>(ex);
}
}
}
}
12 changes: 11 additions & 1 deletion src/NHibernate/Async/ITransaction.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,24 @@
using System;
using System.Data;
using System.Data.Common;
using System.Threading.Tasks;
using NHibernate.Transaction;

namespace NHibernate
{
using System.Threading.Tasks;
using System.Threading;
public partial interface ITransaction : IDisposable
{
/// <summary>
/// Begin the transaction with the default isolation level.
/// </summary>
Task BeginAsync();

/// <summary>
/// Begin the transaction with the specified isolation level.
/// </summary>
/// <param name="isolationLevel">Isolation level of the transaction</param>
Task BeginAsync(IsolationLevel isolationLevel);

/// <summary>
/// Flush the associated <c>ISession</c> and end the unit of work.
Expand Down
39 changes: 39 additions & 0 deletions src/NHibernate/Async/Impl/AbstractSessionImpl.cs
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,45 @@ protected async Task AfterOperationAsync(bool success, CancellationToken cancell
}
}

/// <summary>
/// Begin a NHibernate transaction
/// </summary>
/// <returns>A NHibernate transaction</returns>
public async Task<ITransaction> BeginTransactionAsync()
{
using (BeginProcess())
{
if (IsTransactionCoordinatorShared)
{
// Todo : should seriously consider not allowing a txn to begin from a child session
// can always route the request to the root session...
Log.Warn("Transaction started on non-root session");
}

return await (ConnectionManager.BeginTransactionAsync()).ConfigureAwait(false);
}
}

/// <summary>
/// Begin a NHibernate transaction with the specified isolation level
/// </summary>
/// <param name="isolationLevel">The isolation level</param>
/// <returns>A NHibernate transaction</returns>
public async Task<ITransaction> BeginTransactionAsync(IsolationLevel isolationLevel)
{
using (BeginProcess())
{
if (IsTransactionCoordinatorShared)
{
// Todo : should seriously consider not allowing a txn to begin from a child session
// can always route the request to the root session...
Log.Warn("Transaction started on non-root session");
}

return await (ConnectionManager.BeginTransactionAsync(isolationLevel)).ConfigureAwait(false);
}
}

public abstract Task<IQuery> CreateFilterAsync(object collection, IQueryExpression queryExpression, CancellationToken cancellationToken);

public abstract Task<IEnumerable> EnumerableAsync(IQueryExpression queryExpression, QueryParameters queryParameters, CancellationToken cancellationToken);
Expand Down
59 changes: 59 additions & 0 deletions src/NHibernate/Async/Transaction/AdoTransaction.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,65 @@ namespace NHibernate.Transaction
public partial class AdoTransaction : ITransaction
{

public Task BeginAsync()
{
return BeginAsync(IsolationLevel.Unspecified);
}

/// <summary>
/// Begins the <see cref="DbTransaction"/> on the <see cref="DbConnection"/>
/// used by the <see cref="ISession"/>.
/// </summary>
/// <exception cref="TransactionException">
/// Thrown if there is any problems encountered while trying to create
/// the <see cref="DbTransaction"/>.
/// </exception>
public async Task BeginAsync(IsolationLevel isolationLevel)
{
using (session.BeginProcess())
{
if (begun)
{
return;
}

if (commitFailed)
{
throw new TransactionException("Cannot restart transaction after failed commit");
}

if (isolationLevel == IsolationLevel.Unspecified)
{
isolationLevel = session.Factory.Settings.IsolationLevel;
}

log.Debug("Begin ({0})", isolationLevel);

try
{
trans = await (session.Factory.ConnectionProvider.Driver.BeginTransactionAsync(isolationLevel, session.Connection)).ConfigureAwait(false);
}
catch (HibernateException)
{
// Don't wrap HibernateExceptions
throw;
}
catch (Exception e)
{
log.Error(e, "Begin transaction failed");
throw new TransactionException("Begin failed with SQL exception", e);
}

begun = true;
committed = false;
rolledBack = false;

session.AfterTransactionBegin(this);
foreach (var dependentSession in session.ConnectionManager.DependentSessions)
dependentSession.AfterTransactionBegin(this);
}
}

private async Task AfterTransactionCompletionAsync(bool successful, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
Expand Down
2 changes: 1 addition & 1 deletion src/NHibernate/Driver/DriverBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ namespace NHibernate.Driver
/// <summary>
/// Base class for the implementation of IDriver
/// </summary>
public abstract class DriverBase : IDriver, ISqlParameterFormatter
public abstract partial class DriverBase : IDriver, ISqlParameterFormatter
{
private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(DriverBase));

Expand Down
2 changes: 1 addition & 1 deletion src/NHibernate/Driver/DriverExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

namespace NHibernate.Driver
{
public static class DriverExtensions
public static partial class DriverExtensions
{
internal static void AdjustParameterForValue(this IDriver driver, DbParameter parameter, SqlType sqlType, object value)
{
Expand Down
Loading