forked from nhibernate/nhibernate-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAbstractBatcher.cs
636 lines (562 loc) · 17 KB
/
AbstractBatcher.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.Threading;
using NHibernate.Driver;
using NHibernate.Engine;
using NHibernate.Exceptions;
using NHibernate.SqlCommand;
using NHibernate.SqlTypes;
using NHibernate.Util;
using NHibernate.AdoNet.Util;
namespace NHibernate.AdoNet
{
/// <summary>
/// Manages prepared statements and batching. Class exists to enforce separation of concerns
/// </summary>
public abstract partial class AbstractBatcher : IBatcher
{
protected static readonly INHibernateLogger Log = NHibernateLogger.For(typeof(AbstractBatcher));
private static int _openCommandCount;
private static int _openReaderCount;
private readonly ConnectionManager _connectionManager;
private readonly ISessionFactoryImplementor _factory;
private readonly IInterceptor _interceptor;
// batchCommand used to be called batchUpdate - that name to me implied that updates
// were being sent - however this could be just INSERT/DELETE/SELECT SQL statement not
// just update. However I haven't seen this being used with read statements...
private DbCommand _batchCommand;
private SqlString _batchCommandSql;
private SqlType[] _batchCommandParameterTypes;
private readonly HashSet<DbCommand> _commandsToClose = new HashSet<DbCommand>();
private readonly HashSet<DbDataReader> _readersToClose = new HashSet<DbDataReader>();
private readonly Dictionary<DbDataReader, Stopwatch> _readersDuration = new Dictionary<DbDataReader, Stopwatch>();
private DbCommand _lastQuery;
private bool _releasing;
/// <summary>
/// Initializes a new instance of the <see cref="AbstractBatcher"/> class.
/// </summary>
/// <param name="connectionManager">The <see cref="ConnectionManager"/> owning this batcher.</param>
/// <param name="interceptor"></param>
protected AbstractBatcher(ConnectionManager connectionManager, IInterceptor interceptor)
{
_connectionManager = connectionManager;
_interceptor = interceptor;
_factory = connectionManager.Factory;
}
protected IDriver Driver
{
get { return _factory.ConnectionProvider.Driver; }
}
/// <summary>
/// Gets the current <see cref="DbCommand"/> that is contained for this Batch
/// </summary>
/// <value>The current <see cref="DbCommand"/>.</value>
protected DbCommand CurrentCommand
{
get { return _batchCommand; }
}
/// <summary>
/// Gets the current <see cref="SqlString"/> that is contained for this Batch
/// </summary>
/// <value>The current <see cref="SqlString"/>.</value>
protected SqlString CurrentCommandSql => _batchCommandSql;
/// <summary>
/// Gets the current <see cref="SqlType"/> parameters that are contained for this Batch
/// </summary>
/// <value>The current <see cref="SqlString"/>.</value>
protected SqlType[] CurrentCommandParameterTypes => _batchCommandParameterTypes;
public DbCommand Generate(CommandType type, SqlString sqlString, SqlType[] parameterTypes)
{
return Generate(type, sqlString, parameterTypes, false);
}
private DbCommand Generate(CommandType type, SqlString sqlString, SqlType[] parameterTypes, bool batch)
{
var sql = GetSQL(sqlString);
if (batch)
{
OnPreparedBatchStatement(sql);
}
var cmd = _factory.ConnectionProvider.Driver.GenerateCommand(type, sql, parameterTypes);
LogOpenPreparedCommand(sql);
_commandsToClose.Add(cmd);
return cmd;
}
/// <summary>
/// Prepares the <see cref="DbCommand"/> for execution in the database.
/// </summary>
/// <remarks>
/// This takes care of hooking the <see cref="DbCommand"/> up to an <see cref="DbConnection"/>
/// and <see cref="DbTransaction"/> if one exists. It will call <c>Prepare</c> if the Driver
/// supports preparing commands.
/// </remarks>
protected void Prepare(DbCommand cmd)
{
try
{
var sessionConnection = _connectionManager.GetConnection();
if (cmd.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 (cmd.Connection != sessionConnection)
{
cmd.Connection = sessionConnection;
}
}
else
{
cmd.Connection = sessionConnection;
}
_connectionManager.EnlistInTransaction(cmd);
Driver.PrepareCommand(cmd);
}
catch (InvalidOperationException ioe)
{
throw new ADOException("While preparing " + cmd.CommandText + " an error occurred", ioe);
}
}
public virtual DbCommand PrepareBatchCommand(CommandType type, SqlString sql, SqlType[] parameterTypes)
{
if (sql.Equals(_batchCommandSql) && ArrayHelper.ArrayEquals(parameterTypes, _batchCommandParameterTypes))
{
if (Log.IsDebugEnabled())
{
Log.Debug("reusing command {0}", _batchCommand.CommandText);
}
}
else
{
_batchCommand = PrepareCommand(type, sql, parameterTypes, true); // calls ExecuteBatch()
_batchCommandSql = sql;
_batchCommandParameterTypes = parameterTypes;
}
return _batchCommand;
}
public DbCommand PrepareCommand(CommandType type, SqlString sql, SqlType[] parameterTypes)
{
return PrepareCommand(type, sql, parameterTypes, false);
}
private DbCommand PrepareCommand(CommandType type, SqlString sql, SqlType[] parameterTypes, bool batch)
{
OnPreparedCommand();
// do not actually prepare the Command here - instead just generate it because
// if the command is associated with an ADO.NET Transaction/Connection while
// another open one Command is doing something then an exception will be
// thrown.
return Generate(type, sql, parameterTypes, batch);
}
protected virtual void OnPreparedCommand()
{
// a new DbCommand is being prepared and a new (potential) batch
// started - so execute the current batch of commands.
ExecuteBatch();
}
internal virtual void OnPreparedBatchStatement(SqlString sqlString) { }
public DbCommand PrepareQueryCommand(CommandType type, SqlString sql, SqlType[] parameterTypes)
{
// do not actually prepare the Command here - instead just generate it because
// if the command is associated with an ADO.NET Transaction/Connection while
// another open one Command is doing something then an exception will be
// thrown.
var command = Generate(type, sql, parameterTypes);
_lastQuery = command;
return command;
}
public void AbortBatch(Exception e)
{
var cmd = _batchCommand;
InvalidateBatchCommand();
// close the statement closeStatement(cmd)
if (cmd != null)
{
CloseCommand(cmd, null);
}
}
private void InvalidateBatchCommand()
{
_batchCommand = null;
_batchCommandSql = null;
_batchCommandParameterTypes = null;
}
public int ExecuteNonQuery(DbCommand cmd)
{
CheckReaders();
LogCommand(cmd);
Prepare(cmd);
Stopwatch duration = null;
if (Log.IsDebugEnabled())
duration = Stopwatch.StartNew();
try
{
return cmd.ExecuteNonQuery();
}
catch (Exception e)
{
e.Data["actual-sql-query"] = cmd.CommandText;
Log.Error(e, "Could not execute command: {0}", cmd.CommandText);
throw;
}
finally
{
if (duration != null)
Log.Debug("ExecuteNonQuery took {0} ms", duration.ElapsedMilliseconds);
}
}
public virtual DbDataReader ExecuteReader(DbCommand cmd)
{
CheckReaders();
LogCommand(cmd);
Prepare(cmd);
var duration = Log.IsDebugEnabled() ? Stopwatch.StartNew() : null;
var reader = DoExecuteReader(cmd);
_readersToClose.Add(reader);
LogOpenReader(duration , reader);
return reader;
}
private DbDataReader DoExecuteReader(DbCommand cmd)
{
try
{
var reader = cmd.ExecuteReader();
if (reader == null)
{
// MySql may return null instead of an exception, by example when the query is canceled by another thread.
throw new InvalidOperationException("The query execution has yielded a null reader. (Has it been canceled?)");
}
return _factory.ConnectionProvider.Driver.SupportsMultipleOpenReaders
? reader
: NHybridDataReader.Create(reader);
}
catch (Exception e)
{
e.Data["actual-sql-query"] = cmd.CommandText;
Log.Error(e, "Could not execute query: {0}", cmd.CommandText);
throw;
}
}
/// <summary>
/// Ensures that the Driver's rules for Multiple Open DataReaders are being followed.
/// </summary>
protected void CheckReaders()
{
// early exit because we don't need to move an open DbDataReader into memory
// since the Driver supports mult open readers.
if (_factory.ConnectionProvider.Driver.SupportsMultipleOpenReaders)
{
return;
}
foreach (NHybridDataReader reader in _readersToClose)
{
reader.ReadIntoMemory();
}
}
public virtual void CloseCommands()
{
_releasing = true;
try
{
foreach (var reader in new HashSet<DbDataReader>(_readersToClose))
{
try
{
CloseReader(reader);
}
catch (Exception e)
{
Log.Warn(e, "Could not close DbDataReader");
}
}
foreach (var cmd in _commandsToClose)
{
try
{
CloseCommand(cmd);
}
catch (Exception e)
{
// no big deal
Log.Warn(e, "Could not close ADO.NET Command");
}
}
_commandsToClose.Clear();
}
finally
{
_releasing = false;
}
}
private void CloseCommand(DbCommand cmd)
{
if (cmd == null)
return;
try
{
// no equiv to the java code in here
cmd.Dispose();
LogClosePreparedCommand();
}
catch (Exception e)
{
Log.Warn(e, "exception clearing maxRows/queryTimeout");
return; // NOTE: early exit!
}
finally
{
if (!_releasing)
{
_connectionManager.AfterStatement();
}
}
if (_lastQuery == cmd)
{
_lastQuery = null;
}
}
public void CloseCommand(DbCommand st, DbDataReader reader)
{
_commandsToClose.Remove(st);
try
{
CloseReader(reader);
}
finally
{
CloseCommand(st);
}
}
public void CloseReader(DbDataReader reader)
{
/* This method was added because PrepareCommand don't really prepare the command
* with its connection.
* In some case we need to manage a reader outsite the command scope.
* To do it we need to use the Batcher.ExecuteReader and then we need something
* to close the opened reader.
*/
// TODO NH: Study a way to use directly DbCommand.ExecuteReader() outsite the batcher
// An example of it's use is the management of generated ID.
if (reader == null)
return;
var rsw = reader as ResultSetWrapper;
var actualReader = rsw == null ? reader : rsw.Target;
_readersToClose.Remove(actualReader);
_readersDuration.Remove(actualReader, out var duration);
try
{
reader.Dispose();
}
catch (Exception e)
{
// NH2205 - prevent exceptions when closing the reader from hiding any original exception
Log.Warn(e, "exception closing reader");
}
LogCloseReader(duration);
}
public void ExecuteBatch()
{
// if there is currently a command that a batch is
// being built for then execute it
if (_batchCommand != null)
{
var ps = _batchCommand;
InvalidateBatchCommand();
try
{
ExecuteBatchWithTiming(ps);
}
finally
{
CloseCommand(ps, null);
}
}
}
protected void ExecuteBatchWithTiming(DbCommand ps)
{
Stopwatch duration = null;
if (Log.IsDebugEnabled())
duration = Stopwatch.StartNew();
var countBeforeExecutingBatch = CountOfStatementsInCurrentBatch;
DoExecuteBatch(ps);
if (duration != null)
Log.Debug("ExecuteBatch for {0} statements took {1} ms",
countBeforeExecutingBatch,
duration.ElapsedMilliseconds);
}
protected abstract void DoExecuteBatch(DbCommand ps);
protected abstract int CountOfStatementsInCurrentBatch { get; }
/// <summary>
/// Gets or sets the size of the batch, this can change dynamically by
/// calling the session's SetBatchSize.
/// </summary>
/// <value>The size of the batch.</value>
public abstract int BatchSize
{
get;
set;
}
/// <summary>
/// Adds the expected row count into the batch.
/// </summary>
/// <param name="expectation">The number of rows expected to be affected by the query.</param>
/// <remarks>
/// If Batching is not supported, then this is when the Command should be executed. If Batching
/// is supported then it should hold of on executing the batch until explicitly told to.
/// </remarks>
public abstract void AddToBatch(IExpectation expectation);
/// <summary>
/// Gets the <see cref="ISessionFactoryImplementor"/> the Batcher was
/// created in.
/// </summary>
/// <value>
/// The <see cref="ISessionFactoryImplementor"/> the Batcher was
/// created in.
/// </value>
protected ISessionFactoryImplementor Factory
{
get { return _factory; }
}
/// <summary>
/// Gets the <see cref="ConnectionManager"/> for this batcher.
/// </summary>
protected ConnectionManager ConnectionManager
{
get { return _connectionManager; }
}
protected void LogCommand(DbCommand command)
{
_factory.Settings.SqlStatementLogger.LogCommand(command, FormatStyle.Basic);
}
private void LogOpenPreparedCommand(SqlString sql)
{
if (Log.IsDebugEnabled())
{
int currentOpenCommandCount = Interlocked.Increment(ref _openCommandCount);
Log.Debug("Opened new DbCommand, open DbCommands: {0}", currentOpenCommandCount);
Log.Debug("Building an DbCommand object for the SqlString: {0}", sql);
}
if (_factory.Statistics.IsStatisticsEnabled)
{
_factory.StatisticsImplementor.PrepareStatement();
}
}
private void LogClosePreparedCommand()
{
if (Log.IsDebugEnabled())
{
int currentOpenCommandCount = Interlocked.Decrement(ref _openCommandCount);
Log.Debug("Closed DbCommand, open DbCommands: {0}", currentOpenCommandCount);
}
if (_factory.Statistics.IsStatisticsEnabled)
{
_factory.StatisticsImplementor.CloseStatement();
}
}
private void LogOpenReader(Stopwatch duration, DbDataReader reader)
{
if (duration == null)
return;
Log.Debug("ExecuteReader took {0} ms", duration.ElapsedMilliseconds);
_readersDuration[reader] = duration;
int currentOpenReaderCount = Interlocked.Increment(ref _openReaderCount);
Log.Debug("Opened DbDataReader, open DbDataReaders: {0}", currentOpenReaderCount);
}
private static void LogCloseReader(Stopwatch duration)
{
if (duration == null)
return;
int currentOpenReaderCount = Interlocked.Decrement(ref _openReaderCount);
Log.Debug("Closed DbDataReader, open DbDataReaders :{0}", currentOpenReaderCount);
Log.Debug("DataReader was closed after {0} ms", duration.ElapsedMilliseconds);
}
public void CancelLastQuery()
{
try
{
if (_lastQuery != null)
{
_lastQuery.Cancel();
}
}
catch (HibernateException)
{
// Do not call Convert on HibernateExceptions
throw;
}
catch (Exception sqle)
{
throw Convert(sqle, "Could not cancel query");
}
}
public bool HasOpenResources
{
get { return _commandsToClose.Count > 0 || _readersToClose.Count > 0; }
}
protected Exception Convert(Exception sqlException, string message)
{
return ADOExceptionHelper.Convert(Factory.SQLExceptionConverter, sqlException, message);
}
#region IDisposable Members
/// <summary>
/// A flag to indicate if <c>Dispose()</c> has been called.
/// </summary>
private bool _isAlreadyDisposed;
/// <summary>
/// Finalizer that ensures the object is correctly disposed of.
/// </summary>
~AbstractBatcher()
{
// Don't log in the finalizer, it causes problems
// if the output stream is finalized before the batcher.
//log.Debug( "running BatcherImpl.Dispose(false)" );
Dispose(false);
}
/// <summary>
/// Takes care of freeing the managed and unmanaged resources that
/// this class is responsible for.
/// </summary>
public void Dispose()
{
Log.Debug("running BatcherImpl.Dispose(true)");
Dispose(true);
}
/// <summary>
/// Takes care of freeing the managed and unmanaged resources that
/// this class is responsible for.
/// </summary>
/// <param name="isDisposing">Indicates if this BatcherImpl is being Disposed of or Finalized.</param>
/// <remarks>
/// If this BatcherImpl is being Finalized (<c>isDisposing==false</c>) then make sure not
/// to call any methods that could potentially bring this BatcherImpl back to life.
/// </remarks>
protected virtual void Dispose(bool isDisposing)
{
if (_isAlreadyDisposed)
{
// don't dispose of multiple times.
return;
}
// free managed resources that are being managed by the AdoTransaction if we
// know this call came through Dispose()
if (isDisposing)
{
CloseCommands();
// nothing for Finalizer to do - so tell the GC to ignore it
GC.SuppressFinalize(this);
}
// free unmanaged resources here
_isAlreadyDisposed = true;
}
#endregion
protected SqlString GetSQL(SqlString sql)
{
sql = _interceptor.OnPrepareStatement(sql);
if (sql == null || sql.Length == 0)
{
throw new AssertionFailure("Interceptor.OnPrepareStatement(SqlString) returned null or empty SqlString.");
}
return sql;
}
}
}