Skip to content

Commit

Permalink
Use interface default implementations
Browse files Browse the repository at this point in the history
  • Loading branch information
gliljas committed Mar 15, 2024
1 parent b96fe21 commit b177721
Show file tree
Hide file tree
Showing 13 changed files with 71 additions and 93 deletions.
4 changes: 2 additions & 2 deletions src/NHibernate.Test/Ado/BatcherFixture.cs
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ public void BatchedoutputShouldBeFormatted()
{
FillDb();
var log = sqlLog.GetWholeLog();
Assert.IsTrue(log.Contains("INSERT \n INTO"));
Assert.That(log, Does.Contain("INSERT \n INTO").IgnoreCase);
}

Cleanup();
Expand Down Expand Up @@ -239,7 +239,7 @@ public void AbstractBatcherLog()
foreach (var loggingEvent in sl.Appender.GetEvents())
{
string message = loggingEvent.RenderedMessage;
if(message.ToLowerInvariant().Contains("insert"))
if(message.Contains("insert"))
{
Assert.That(message, Does.Contain("batch").IgnoreCase);
}
Expand Down
6 changes: 3 additions & 3 deletions src/NHibernate/AdoNet/ConnectionManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -524,15 +524,15 @@ public void EnlistInTransaction(DbBatch batch)
if (batch == null)
throw new ArgumentNullException(nameof(batch));

if (_transaction is ITransactionWithBatchSupport transactionWithBatch)
if (_transaction != null)
{
transactionWithBatch.Enlist(batch);
_transaction.Enlist(batch);
return;
}

if (batch.Transaction != null)
{
_log.Warn("set a nonnull DbCommand.Transaction to null because the Session had no Transaction");
_log.Warn("set a nonnull DbBatch.Transaction to null because the Session had no Transaction");
batch.Transaction = null;
}
}
Expand Down
52 changes: 44 additions & 8 deletions src/NHibernate/AdoNet/DbBatchBatcher.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#if NET6_0_OR_GREATER
#if NET6_0_OR_GREATER
using System;
using System.Data.Common;
using System.Linq;
Expand Down Expand Up @@ -26,7 +26,7 @@ public DbBatchBatcher(ConnectionManager connectionManager, IInterceptor intercep
{
_batchSize = Factory.Settings.AdoBatchSize;
_defaultTimeout = Driver.GetCommandTimeout();

_currentBatch = CreateConfiguredBatch();
//we always create this, because we need to deal with a scenario in which
//the user change the logging configuration at runtime. Trying to put this
Expand Down Expand Up @@ -152,7 +152,7 @@ protected override void DoExecuteBatch(DbCommand ps)
{
throw ADOExceptionHelper.Convert(Factory.SQLExceptionConverter, e, "could not execute batch command.");
}

Expectations.VerifyOutcomeBatched(_totalExpectedRowsAffected, rowsAffected, ps);
}
finally
Expand All @@ -168,8 +168,7 @@ protected override async Task DoExecuteBatchAsync(DbCommand ps, CancellationToke
{
Log.Debug("Executing batch");
await (CheckReadersAsync(cancellationToken)).ConfigureAwait(false);
//await (PrepareAsync(_currentBatch, cancellationToken)).ConfigureAwait(false);
Prepare(_currentBatch);
await (PrepareAsync(_currentBatch, cancellationToken)).ConfigureAwait(false);
if (Factory.Settings.SqlStatementLogger.IsDebugEnabled)
{
Factory.Settings.SqlStatementLogger.LogBatchCommand(_currentBatchCommandsLog.ToString());
Expand All @@ -194,7 +193,7 @@ protected override async Task DoExecuteBatchAsync(DbCommand ps, CancellationToke

private DbBatch CreateConfiguredBatch()
{
var result = ((IDriverWithBatchSupport) Driver).CreateBatch();
var result = Driver.CreateBatch();
if (_defaultTimeout > 0)
{
try
Expand All @@ -218,7 +217,7 @@ private void ClearCurrentBatch()
_currentBatch.Dispose();
_totalExpectedRowsAffected = 0;
_currentBatch = CreateConfiguredBatch();

if (Factory.Settings.SqlStatementLogger.IsDebugEnabled)
{
_currentBatchCommandsLog = new StringBuilder().AppendLine("Batch commands:");
Expand Down Expand Up @@ -285,7 +284,44 @@ protected void Prepare(DbBatch batch)
}

_connectionManager.EnlistInTransaction(batch);
(Driver as IDriverWithBatchSupport).PrepareBatch(batch);
Driver.PrepareBatch(batch);
}
catch (InvalidOperationException ioe)
{
throw new ADOException("While preparing " + string.Join(Environment.NewLine, batch.BatchCommands.Select(x => x.CommandText)) + " an error occurred", ioe);
}
}

/// <summary>
/// Prepares the <see cref="DbBatch"/> for execution in the database.
/// </summary>
/// <remarks>
/// This takes care of hooking the <see cref="DbBatch"/> up to an <see cref="DbConnection"/>
/// and <see cref="DbTransaction"/> if one exists. It will call <c>Prepare</c> if the Driver
/// supports preparing batches.
/// </remarks>
protected async Task PrepareAsync(DbBatch batch, CancellationToken cancellationToken)
{
try
{
var sessionConnection = await _connectionManager.GetConnectionAsync(cancellationToken).ConfigureAwait(false);

if (batch.Connection != null)
{
// make sure the commands connection is the same as the Sessions connection
// these can be different when the session is disconnected and then reconnected
if (batch.Connection != sessionConnection)
{
batch.Connection = sessionConnection;
}
}
else
{
batch.Connection = sessionConnection;
}

_connectionManager.EnlistInTransaction(batch);
Driver.PrepareBatch(batch);
}
catch (InvalidOperationException ioe)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,6 @@
namespace NHibernate.Driver
{
public class DbProviderFactoryDriveConnectionCommandProvider : IDriveConnectionCommandProvider
#if NET6_0_OR_GREATER
, IDriveConnectionCommandProviderWithBatchSupport
#endif
{
private readonly DbProviderFactory dbProviderFactory;

Expand All @@ -29,10 +26,7 @@ public DbCommand CreateCommand()
return dbProviderFactory.CreateCommand();
}
#if NET6_0_OR_GREATER
public DbBatch CreateBatch()
{
return dbProviderFactory.CreateBatch();
}
public DbBatch CreateBatch() => dbProviderFactory.CreateBatch();

public bool CanCreateBatch => dbProviderFactory.CanCreateBatch && dbProviderFactory.CreateCommand() is ICloneable;
#endif
Expand Down
3 changes: 0 additions & 3 deletions src/NHibernate/Driver/DriverBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,6 @@ namespace NHibernate.Driver
/// Base class for the implementation of IDriver
/// </summary>
public abstract class DriverBase : IDriver, ISqlParameterFormatter
#if NET6_0_OR_GREATER
, IDriverWithBatchSupport
#endif
{
private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(DriverBase));

Expand Down
7 changes: 6 additions & 1 deletion src/NHibernate/Driver/IDriveConnectionCommandProvider.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System;
using System.Data.Common;

namespace NHibernate.Driver
Expand All @@ -6,5 +7,9 @@ public interface IDriveConnectionCommandProvider
{
DbConnection CreateConnection();
DbCommand CreateCommand();
#if NET6_0_OR_GREATER
DbBatch CreateBatch() => throw new NotImplementedException();
bool CanCreateBatch => false;
#endif
}
}
}

This file was deleted.

10 changes: 8 additions & 2 deletions src/NHibernate/Driver/IDriver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Windows.Input;
using NHibernate.Engine;
using NHibernate.SqlCommand;
using NHibernate.SqlTypes;
Expand Down Expand Up @@ -165,5 +163,13 @@ public interface IDriver
/// The minimal date supplied as a <see cref="DateTime" /> supported by this driver.
/// </summary>
DateTime MinDate { get; }

#if NET6_0_OR_GREATER
DbBatch CreateBatch() => throw new NotImplementedException();
bool CanCreateBatch => false;

void AdjustBatch(DbBatch dbBatch) => throw new NotImplementedException();
void PrepareBatch(DbBatch dbBatch) => throw new NotImplementedException();
#endif
}
}
16 changes: 0 additions & 16 deletions src/NHibernate/Driver/IDriverWithBatchSupport.cs

This file was deleted.

21 changes: 2 additions & 19 deletions src/NHibernate/Driver/ReflectionBasedDriver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -75,26 +75,9 @@ public override DbCommand CreateCommand()
}

#if NET6_0_OR_GREATER
public override DbBatch CreateBatch()
{
if (connectionCommandProvider is IDriveConnectionCommandProviderWithBatchSupport driveConnectionCommandProviderWithBatch)
{
return driveConnectionCommandProviderWithBatch.CreateBatch();
}
throw new NotSupportedException();
}
public override DbBatch CreateBatch() => connectionCommandProvider.CreateBatch();

public override bool CanCreateBatch
{
get
{
if (connectionCommandProvider is IDriveConnectionCommandProviderWithBatchSupport driveConnectionCommandProviderWithBatch)
{
return driveConnectionCommandProviderWithBatch.CanCreateBatch;
}
return false;
}
}
public override bool CanCreateBatch => connectionCommandProvider.CanCreateBatch;
#endif
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,6 @@
namespace NHibernate.Driver
{
public class ReflectionDriveConnectionCommandProvider : IDriveConnectionCommandProvider
#if NET6_0_OR_GREATER
, IDriveConnectionCommandProviderWithBatchSupport
#endif
{
private readonly System.Type commandType;
private readonly System.Type connectionType;
Expand Down Expand Up @@ -49,7 +46,6 @@ public DbCommand CreateCommand()
#endregion

#if NET6_0_OR_GREATER

private Lazy<bool> _canCreateBatch;

public DbBatch CreateBatch()
Expand All @@ -63,8 +59,6 @@ public DbBatch CreateBatch()
}

public bool CanCreateBatch => _canCreateBatch.Value;


#endif
}
}
7 changes: 2 additions & 5 deletions src/NHibernate/ITransaction.cs
Original file line number Diff line number Diff line change
Expand Up @@ -81,21 +81,18 @@ public partial interface ITransaction : IDisposable
"RegisterSynchronization(ITransactionCompletionSynchronization)': the TransactionExtensions extension " +
"method will call it.")]
void RegisterSynchronization(ISynchronization synchronization);
}

#if NET6_0_OR_GREATER
internal interface ITransactionWithBatchSupport : ITransaction
{
/// <summary>
/// Enlist a <see cref="DbBatch"/> in the current Transaction.
/// </summary>
/// <param name="batch">The <see cref="DbBatch"/> to enlist.</param>
/// <remarks>
/// It is okay for this to be a no op implementation.
/// </remarks>
void Enlist(DbBatch batch);
}
void Enlist(DbBatch batch) => throw new NotImplementedException();
#endif
}

// 6.0 TODO: merge into ITransaction
public static class TransactionExtensions
Expand Down
9 changes: 3 additions & 6 deletions src/NHibernate/Transaction/AdoTransaction.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,6 @@ namespace NHibernate.Transaction
/// the <see cref="ITransaction" /> interface.
/// </summary>
public partial class AdoTransaction : ITransaction
#if NET6_0_OR_GREATER
, ITransactionWithBatchSupport
#endif
{
private static readonly INHibernateLogger log = NHibernateLogger.For(typeof(AdoTransaction));
private ISessionImplementor session;
Expand Down Expand Up @@ -112,7 +109,7 @@ public void Enlist(DbBatch batch)
{
if (batch.Transaction != null)
{
log.Warn("set a nonnull DbCommand.Transaction to null because the Session had no Transaction");
log.Warn("set a nonnull DbBatch.Transaction to null because the Session had no Transaction");
}
}

Expand All @@ -127,11 +124,11 @@ public void Enlist(DbBatch batch)
// don't need to be confused by that - just a normal part of initialization...
if (batch.Transaction != null && batch.Transaction != trans)
{
log.Warn("The DbCommand had a different Transaction than the Session. This can occur when " +
log.Warn("The DbBatch had a different Transaction than the Session. This can occur when " +
"Disconnecting and Reconnecting Sessions because the PreparedCommand Cache is Session specific.");
}
}
log.Debug("Enlist Command");
log.Debug("Enlist DbBatch");

// If you try to assign a disposed transaction to a command with MSSQL, it will leave the command's
// transaction as null and not throw an error. With SQLite, for example, it will throw an exception
Expand Down

0 comments on commit b177721

Please sign in to comment.