Skip to content

Add needed overrides to ReliableSqlClientBatchingBatcher for (at least some of) the new async methods added to SqlClientBatchingBatcher #38

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

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
5 changes: 3 additions & 2 deletions NHibernate5.SqlAzure.Tests/NHibernate5.SqlAzure.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,9 @@
<Reference Include="Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Web.Infrastructure.1.0.0.0\lib\net40\Microsoft.Web.Infrastructure.dll</HintPath>
</Reference>
<Reference Include="NHibernate, Version=5.2.0.0, Culture=neutral, PublicKeyToken=aa95f207798dfdb4, processorArchitecture=MSIL">
<HintPath>..\packages\NHibernate.5.2.3\lib\net461\NHibernate.dll</HintPath>
<Reference Include="NHibernate, Version=5.3.0.0, Culture=neutral, PublicKeyToken=aa95f207798dfdb4">
<HintPath>..\packages\NHibernate.5.3.9\lib\net461\NHibernate.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="nunit.framework, Version=2.6.2.12296, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL">
<HintPath>..\packages\NUnit.2.6.2\lib\nunit.framework.dll</HintPath>
Expand Down
2 changes: 1 addition & 1 deletion NHibernate5.SqlAzure.Tests/packages.config
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
<package id="Microsoft.VisualStudio.SlowCheetah" version="3.0.61" targetFramework="net461" />
<package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net461" />
<package id="NBuilder" version="3.0.1.1" targetFramework="net461" />
<package id="NHibernate" version="5.2.3" targetFramework="net461" />
<package id="NHibernate" version="5.3.9" targetFramework="net461" />
<package id="NHibernateProfiler" version="5.0.5044" targetFramework="net461" />
<package id="NUnit" version="2.6.2" targetFramework="net461" />
<package id="NUnitTestAdapter" version="2.1.0" targetFramework="net461" />
Expand Down
5 changes: 3 additions & 2 deletions NHibernate5.SqlAzure/NHibernate5.SqlAzure.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,9 @@
<Reference Include="Microsoft.Practices.EnterpriseLibrary.TransientFaultHandling.Data, Version=6.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\EnterpriseLibrary.TransientFaultHandling.Data.6.0.1304.1\lib\NET45\Microsoft.Practices.EnterpriseLibrary.TransientFaultHandling.Data.dll</HintPath>
</Reference>
<Reference Include="NHibernate, Version=5.2.0.0, Culture=neutral, PublicKeyToken=aa95f207798dfdb4, processorArchitecture=MSIL">
<HintPath>..\packages\NHibernate.5.2.3\lib\net461\NHibernate.dll</HintPath>
<Reference Include="NHibernate, Version=5.3.0.0, Culture=neutral, PublicKeyToken=aa95f207798dfdb4">
<HintPath>..\packages\NHibernate.5.3.9\lib\net461\NHibernate.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Remotion.Linq, Version=2.2.0.0, Culture=neutral, PublicKeyToken=fee00910d6e5f53b, processorArchitecture=MSIL">
<HintPath>..\packages\Remotion.Linq.2.2.0\lib\net45\Remotion.Linq.dll</HintPath>
Expand Down
135 changes: 118 additions & 17 deletions NHibernate5.SqlAzure/ReliableSqlClientBatchingBatcher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
using System.Data.Common;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using NHibernate.AdoNet;
using NHibernate.AdoNet.Util;
using NHibernate.Exceptions;
Expand Down Expand Up @@ -94,35 +96,125 @@ public override void AddToBatch(IExpectation expectation)
#endregion
}

// Need this method call in this class rather than the base class to ensure Prepare is called... if only it was virtual :(
protected void ExecuteBatch(IDbCommand ps)
public override Task AddToBatchAsync(IExpectation expectation, CancellationToken cancellationToken)
{
#region NHibernate code
Log.Debug("Executing batch");
CheckReaders();
Prepare(_currentBatch.BatchCommand);
if (Factory.Settings.SqlStatementLogger.IsDebugEnabled)
if (cancellationToken.IsCancellationRequested)
{
Factory.Settings.SqlStatementLogger.LogBatchCommand(_currentBatchCommandsLog.ToString());
_currentBatchCommandsLog = new StringBuilder().AppendLine("Batch commands:");
return Task.FromCanceled<object>(cancellationToken);
}

int rowsAffected;
try
{
rowsAffected = _currentBatch.ExecuteNonQuery();
_totalExpectedRowsAffected += expectation.ExpectedRowCount;
var batchUpdate = CurrentCommand;
Driver.AdjustCommand(batchUpdate);
string lineWithParameters = null;
var sqlStatementLogger = Factory.Settings.SqlStatementLogger;
if (sqlStatementLogger.IsDebugEnabled || Log.IsDebugEnabled())
{
lineWithParameters = sqlStatementLogger.GetCommandLineWithParameters(batchUpdate);
var formatStyle = sqlStatementLogger.DetermineActualStyle(FormatStyle.Basic);
lineWithParameters = formatStyle.Formatter.Format(lineWithParameters);
_currentBatchCommandsLog.Append("command ")
.Append(_currentBatch.CountOfCommands)
.Append(":")
.AppendLine(lineWithParameters);
}
if (Log.IsDebugEnabled())
{
Log.Debug("Adding to batch:{0}", lineWithParameters);
}
#endregion

_currentBatch.Append((System.Data.SqlClient.SqlCommand)(ReliableSqlCommand)batchUpdate);

#region NHibernate code
if (_currentBatch.CountOfCommands >= _batchSize)
{
return ExecuteBatchWithTimingAsync(batchUpdate, cancellationToken);
}
return Task.CompletedTask;
}
catch (DbException e)
catch (Exception ex)
{
throw ADOExceptionHelper.Convert(Factory.SQLExceptionConverter, e, "could not execute batch command.");
return Task.FromException<object>(ex);
}
#endregion
}

// Need this method call in this class rather than the base class to ensure Prepare is called... if only it was virtual :(
protected void ExecuteBatch(DbCommand ps)
{
try
{
Log.Debug("Executing batch");
CheckReaders();
Prepare(_currentBatch.BatchCommand);
if (Factory.Settings.SqlStatementLogger.IsDebugEnabled)
{
Factory.Settings.SqlStatementLogger.LogBatchCommand(_currentBatchCommandsLog.ToString());
}
int rowsAffected;
try
{
rowsAffected = _currentBatch.ExecuteNonQuery();
}
catch (DbException e)
{
throw ADOExceptionHelper.Convert(Factory.SQLExceptionConverter, e, "could not execute batch command.");
}

Expectations.VerifyOutcomeBatched(_totalExpectedRowsAffected, rowsAffected);
Expectations.VerifyOutcomeBatched(_totalExpectedRowsAffected, rowsAffected, ps);
}
finally
{
ClearCurrentBatch();
}
}

#region Possible Future Use if async support for retries is added (commented out)
// protected async Task ExecuteBatchAsync(DbCommand ps, CancellationToken cancellationToken)
// {
// cancellationToken.ThrowIfCancellationRequested();
// try
// {
// Log.Debug("Executing batch");
// await (CheckReadersAsync(cancellationToken)).ConfigureAwait(false);
// await (PrepareAsync(_currentBatch.BatchCommand, cancellationToken)).ConfigureAwait(false);
// if (Factory.Settings.SqlStatementLogger.IsDebugEnabled)
// {
// Factory.Settings.SqlStatementLogger.LogBatchCommand(_currentBatchCommandsLog.ToString());
// }
// int rowsAffected;
// try
// {
// rowsAffected = _currentBatch.ExecuteNonQuery();
// }
// catch (DbException e)
// {
// throw ADOExceptionHelper.Convert(Factory.SQLExceptionConverter, e, "could not execute batch command.");
// }
//
// Expectations.VerifyOutcomeBatched(_totalExpectedRowsAffected, rowsAffected, ps);
// }
// finally
// {
// ClearCurrentBatch();
// }
// }
#endregion

// Copied from NHibernate base class
private void ClearCurrentBatch()
{
_currentBatch.Dispose();
_totalExpectedRowsAffected = 0;
_currentBatch = CreateConfiguredBatch();
#endregion

if (Factory.Settings.SqlStatementLogger.IsDebugEnabled)
{
_currentBatchCommandsLog = new StringBuilder().AppendLine("Batch commands:");
}
}

/// <summary>
Expand All @@ -133,7 +225,7 @@ protected void ExecuteBatch(IDbCommand ps)
/// and <see cref="DbTransaction"/> if one exists. It will call <c>Prepare</c> if the Driver
/// supports preparing commands.
/// </remarks>
protected new void Prepare(DbCommand cmd)
private new void Prepare(DbCommand cmd)
{
try
{
Expand All @@ -154,7 +246,7 @@ protected void ExecuteBatch(IDbCommand ps)
cmd.Connection = (System.Data.SqlClient.SqlConnection) sessionConnection;
}

_connectionManager.Transaction.Enlist(cmd);
_connectionManager.CurrentTransaction?.Enlist(cmd);
Driver.PrepareCommand(cmd);
#endregion
}
Expand All @@ -171,5 +263,14 @@ protected override void DoExecuteBatch(DbCommand ps)
var connection = (ReliableSqlDbConnection)_connectionManager.GetConnection();
ReliableAdoTransaction.ExecuteWithRetry(connection, () => ExecuteBatch(ps));
}

protected override async Task DoExecuteBatchAsync(DbCommand ps, CancellationToken cancellationToken)
{
var connection = (ReliableSqlDbConnection) await _connectionManager.GetConnectionAsync(cancellationToken);
ReliableAdoTransaction.ExecuteWithRetry(connection, () => ExecuteBatch(ps));

// NOTE: To support full async, changes will need to be made all the way through to Enterprise Library code
// ReliableAdoTransaction.ExecuteWithRetry(connection, async () => await ExecuteBatchAsync(ps, cancellationToken));
}
}
}
2 changes: 1 addition & 1 deletion NHibernate5.SqlAzure/packages.config
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<package id="EnterpriseLibrary.TransientFaultHandling.Data" version="6.0.1304.1" targetFramework="net461" />
<package id="Iesi.Collections" version="4.0.4" targetFramework="net461" />
<package id="ILMerge" version="2.14.1208" targetFramework="net461" />
<package id="NHibernate" version="5.2.3" targetFramework="net461" />
<package id="NHibernate" version="5.3.9" targetFramework="net461" />
<package id="Remotion.Linq" version="2.2.0" targetFramework="net461" />
<package id="Remotion.Linq.EagerFetching" version="2.2.0" targetFramework="net461" />
</packages>