-
Notifications
You must be signed in to change notification settings - Fork 935
/
Copy pathGenericBatchingBatcher.cs
247 lines (215 loc) · 7.01 KB
/
GenericBatchingBatcher.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
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Text;
using NHibernate.AdoNet.Util;
using NHibernate.Exceptions;
using NHibernate.SqlCommand;
namespace NHibernate.AdoNet
{
/// <summary>
/// A generic batcher that will batch UPDATE/INSERT/DELETE commands by concatenating them with a semicolon.
/// Use this batcher only if there are no dedicated batchers in the given environment. Unfortunately some
/// database clients do not support concatenating commands with a semicolon. Here are the known clients
/// that do not work with this batcher:
/// - FirebirdSql.Data.FirebirdClient
/// - Oracle.ManagedDataAccess
/// - System.Data.SqlServerCe
/// - Sap.Data.Hana
/// </summary>
public partial class GenericBatchingBatcher : AbstractBatcher
{
private readonly int? _maxNumberOfParameters;
private readonly BatchingCommandSet _currentBatch;
private int _totalExpectedRowsAffected;
private StringBuilder _currentBatchCommandsLog;
public GenericBatchingBatcher(ConnectionManager connectionManager, IInterceptor interceptor)
: base(connectionManager, interceptor)
{
BatchSize = Factory.Settings.AdoBatchSize;
_currentBatch = new BatchingCommandSet(this, Factory.Dialect.StatementTerminator);
_maxNumberOfParameters = Factory.Dialect.MaxNumberOfParameters;
// 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
// behind an if(log.IsDebugEnabled) will cause a null reference exception
// at that point.
_currentBatchCommandsLog = new StringBuilder().AppendLine("Batch commands:");
}
public sealed override int BatchSize { get; set; }
protected override int CountOfStatementsInCurrentBatch => _currentBatch.CountOfCommands;
public override void AddToBatch(IExpectation expectation)
{
var batchCommand = CurrentCommand;
if (_maxNumberOfParameters.HasValue &&
_currentBatch.CountOfParameters + batchCommand.Parameters.Count > _maxNumberOfParameters)
{
ExecuteBatchWithTiming(batchCommand);
}
_totalExpectedRowsAffected += expectation.ExpectedRowCount;
Driver.AdjustCommand(batchCommand);
LogBatchCommand(batchCommand);
_currentBatch.Append(batchCommand.Parameters);
if (_currentBatch.CountOfCommands >= BatchSize)
{
ExecuteBatchWithTiming(batchCommand);
}
}
protected override void DoExecuteBatch(DbCommand ps)
{
if (_currentBatch.CountOfCommands == 0)
{
Expectations.VerifyOutcomeBatched(_totalExpectedRowsAffected, 0, ps);
return;
}
try
{
Log.Debug("Executing batch");
CheckReaders();
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();
}
}
private void LogBatchCommand(DbCommand batchCommand)
{
string lineWithParameters = null;
var sqlStatementLogger = Factory.Settings.SqlStatementLogger;
if (sqlStatementLogger.IsDebugEnabled || Log.IsDebugEnabled())
{
lineWithParameters = sqlStatementLogger.GetCommandLineWithParameters(batchCommand);
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);
}
}
private void ClearCurrentBatch()
{
_currentBatch.Clear();
_totalExpectedRowsAffected = 0;
if (Factory.Settings.SqlStatementLogger.IsDebugEnabled)
{
_currentBatchCommandsLog = new StringBuilder().AppendLine("Batch commands:");
}
}
public override void CloseCommands()
{
base.CloseCommands();
ClearCurrentBatch();
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
_currentBatch.Clear();
}
internal override void OnPreparedBatchStatement(SqlString sqlString)
{
_currentBatch.CurrentStatement = sqlString;
}
private partial class BatchingCommandSet
{
private readonly string _statementTerminator;
private readonly GenericBatchingBatcher _batcher;
private readonly SqlStringBuilder _sql = new SqlStringBuilder();
private readonly List<SqlTypes.SqlType> _sqlTypes = new List<SqlTypes.SqlType>();
private readonly List<BatchParameter> _parameters = new List<BatchParameter>();
private CommandType _commandType;
private class BatchParameter
{
public ParameterDirection Direction { get; set; }
public byte Precision { get; set; }
public byte Scale { get; set; }
public int Size { get; set; }
public object Value { get; set; }
}
public BatchingCommandSet(GenericBatchingBatcher batcher, char statementTerminator)
{
_batcher = batcher;
_statementTerminator = statementTerminator.ToString();
}
public int CountOfCommands { get; private set; }
public int CountOfParameters { get; private set; }
public SqlString CurrentStatement { get; set; }
public void Append(DbParameterCollection parameters)
{
if (CountOfCommands > 0)
{
_sql.Add(_statementTerminator);
}
else
{
_commandType = _batcher.CurrentCommand.CommandType;
}
_sql.Add(CurrentStatement);
_sqlTypes.AddRange(_batcher.CurrentCommandParameterTypes);
foreach (DbParameter parameter in parameters)
{
_parameters.Add(new BatchParameter
{
Direction = parameter.Direction,
Precision = parameter.Precision,
Scale = parameter.Scale,
Size = parameter.Size,
Value = parameter.Value
});
}
CountOfCommands++;
CountOfParameters += parameters.Count;
}
public int ExecuteNonQuery()
{
if (CountOfCommands == 0)
{
return 0;
}
using (var batcherCommand = _batcher.Driver.GenerateCommand(
_commandType,
_sql.ToSqlString(),
_sqlTypes.ToArray()))
{
for (var i = 0; i < _parameters.Count; i++)
{
var parameter = _parameters[i];
var cmdParam = batcherCommand.Parameters[i];
cmdParam.Value = parameter.Value;
cmdParam.Direction = parameter.Direction;
cmdParam.Precision = parameter.Precision;
cmdParam.Scale = parameter.Scale;
cmdParam.Size = parameter.Size;
}
_batcher.Prepare(batcherCommand);
return batcherCommand.ExecuteNonQuery();
}
}
public void Clear()
{
CountOfParameters = 0;
CountOfCommands = 0;
_sql.Clear();
_sqlTypes.Clear();
_parameters.Clear();
}
}
}
}