11#if NET6_0_OR_GREATER
22using System ;
33using System . Data . Common ;
4+ using System . Linq ;
45using System . Text ;
56using System . Threading ;
67using System . Threading . Tasks ;
78using NHibernate . AdoNet . Util ;
89using NHibernate . Driver ;
910using NHibernate . Engine ;
1011using NHibernate . Exceptions ;
11- using NHibernate . Util ;
1212
1313namespace NHibernate . AdoNet
1414{
@@ -19,6 +19,7 @@ public class DbBatchBatcher : AbstractBatcher
1919 private DbBatch _currentBatch ;
2020 private StringBuilder _currentBatchCommandsLog ;
2121 private readonly int _defaultTimeout ;
22+ private readonly ConnectionManager _connectionManager ;
2223
2324 public DbBatchBatcher ( ConnectionManager connectionManager , IInterceptor interceptor )
2425 : base ( connectionManager , interceptor )
@@ -32,6 +33,7 @@ public DbBatchBatcher(ConnectionManager connectionManager, IInterceptor intercep
3233 //behind an if(log.IsDebugEnabled) will cause a null reference exception
3334 //at that point.
3435 _currentBatchCommandsLog = new StringBuilder ( ) . AppendLine ( "Batch commands:" ) ;
36+ _connectionManager = connectionManager ;
3537 }
3638
3739 public override int BatchSize
@@ -253,6 +255,43 @@ protected override void Dispose(bool isDisposing)
253255 Log . Warn ( e , "Exception closing batcher" ) ;
254256 }
255257 }
258+
259+ /// <summary>
260+ /// Prepares the <see cref="DbBatch"/> for execution in the database.
261+ /// </summary>
262+ /// <remarks>
263+ /// This takes care of hooking the <see cref="DbBatch"/> up to an <see cref="DbConnection"/>
264+ /// and <see cref="DbTransaction"/> if one exists. It will call <c>Prepare</c> if the Driver
265+ /// supports preparing batches.
266+ /// </remarks>
267+ protected void Prepare ( DbBatch batch )
268+ {
269+ try
270+ {
271+ var sessionConnection = _connectionManager . GetConnection ( ) ;
272+
273+ if ( batch . Connection != null )
274+ {
275+ // make sure the commands connection is the same as the Sessions connection
276+ // these can be different when the session is disconnected and then reconnected
277+ if ( batch . Connection != sessionConnection )
278+ {
279+ batch . Connection = sessionConnection ;
280+ }
281+ }
282+ else
283+ {
284+ batch . Connection = sessionConnection ;
285+ }
286+
287+ _connectionManager . EnlistInTransaction ( batch ) ;
288+ ( Driver as IDriverWithBatchSupport ) . PrepareBatch ( batch ) ;
289+ }
290+ catch ( InvalidOperationException ioe )
291+ {
292+ throw new ADOException ( "While preparing " + string . Join ( Environment . NewLine , batch . BatchCommands . Select ( x => x . CommandText ) ) + " an error occurred" , ioe ) ;
293+ }
294+ }
256295 }
257296
258297 public class DbBatchBatcherFactory : IBatcherFactory
0 commit comments