1
1
#if NET6_0_OR_GREATER
2
2
using System ;
3
3
using System . Data . Common ;
4
+ using System . Linq ;
4
5
using System . Text ;
5
6
using System . Threading ;
6
7
using System . Threading . Tasks ;
7
8
using NHibernate . AdoNet . Util ;
8
9
using NHibernate . Driver ;
9
10
using NHibernate . Engine ;
10
11
using NHibernate . Exceptions ;
11
- using NHibernate . Util ;
12
12
13
13
namespace NHibernate . AdoNet
14
14
{
@@ -19,6 +19,7 @@ public class DbBatchBatcher : AbstractBatcher
19
19
private DbBatch _currentBatch ;
20
20
private StringBuilder _currentBatchCommandsLog ;
21
21
private readonly int _defaultTimeout ;
22
+ private readonly ConnectionManager _connectionManager ;
22
23
23
24
public DbBatchBatcher ( ConnectionManager connectionManager , IInterceptor interceptor )
24
25
: base ( connectionManager , interceptor )
@@ -32,6 +33,7 @@ public DbBatchBatcher(ConnectionManager connectionManager, IInterceptor intercep
32
33
//behind an if(log.IsDebugEnabled) will cause a null reference exception
33
34
//at that point.
34
35
_currentBatchCommandsLog = new StringBuilder ( ) . AppendLine ( "Batch commands:" ) ;
36
+ _connectionManager = connectionManager ;
35
37
}
36
38
37
39
public override int BatchSize
@@ -253,6 +255,43 @@ protected override void Dispose(bool isDisposing)
253
255
Log . Warn ( e , "Exception closing batcher" ) ;
254
256
}
255
257
}
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
+ }
256
295
}
257
296
258
297
public class DbBatchBatcherFactory : IBatcherFactory
0 commit comments