-
Notifications
You must be signed in to change notification settings - Fork 0
/
Sequencer.cs
367 lines (294 loc) · 14.7 KB
/
Sequencer.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
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.OleDb;
using System.Threading;
using XTools;
namespace XRepository {
/// <summary>
/// Used to sequence columns of database tables.
/// </summary>
public class Sequencer {
private string backingTableName;
private bool? isBackingTablePresent;
private Func<IDbConnection> openConnection;
private IDictionary<string, long> sequences;
public Sequencer() : this((string)null) {
} // end constructor
public Sequencer(Func<IDbConnection> openConnection) {
this.openConnection = openConnection;
this.sequences = new Dictionary<string, long>(StringComparer.OrdinalIgnoreCase);
} // end constructor
/// <summary>
/// Constructs a Sequencer using the specified connection.
/// <param name="connectionStringName">
/// The name of the connection string as definied in the App.config or Web.config.
/// </param>
/// </summary>
public Sequencer(string connectionStringName) :
this(() => {
if (string.IsNullOrEmpty(connectionStringName))
return null;
return DataTool.OpenConnection(connectionStringName);
}) {
} // end constructor
public string BackingTableName {
get { return backingTableName; }
set {
backingTableName = value;
isBackingTablePresent = null;
} // end set
} // end property
public static Sequencer Create<T>(string connectionString) where T : IDbConnection, new() {
return new Sequencer(() => { return DataTool.OpenConnection<T>(connectionString); });
} // end method
public static Sequencer Create(Func<IDbConnection> openConnection) {
return new Sequencer(openConnection);
} // end method
public static Sequencer Create(string connectionStringName) {
return new Sequencer(connectionStringName);
} // end method
private DataTable GetBackingTableSchema() {
if (string.IsNullOrWhiteSpace(BackingTableName))
return null;
using (var con = openConnection()) {
if (con == null)
return null;
using (var cmd = con.CreateCommand()) {
cmd.CommandText = "SELECT * FROM " + BackingTableName + " WHERE 1 = 0";
try {
using (var dr = cmd.ExecuteReader())
return dr.GetSchemaTable();
} catch (DbException) {
// This exception most likely occurs when the table does not exist.
// Simply return null indicating that the table does not exist.
return null;
} // end try-catch
} // end using
} // end using
} // end method
/// <summary>
/// Selects the max value of the specified table and column.
/// </summary>
/// <param name="table">
/// The name of the table from which to query.
/// </param>
/// <param name="column">
/// The name of the column for which to select the max value.
/// </param>
/// <returns>
/// The maximum value of the column in the table
/// or 0 if the value is null or a non-integer.
/// </returns>
protected virtual long GetMaxValue(IDbCommand command, string table, string column) {
if (command == null)
using (var con = openConnection()) {
if (con == null)
return 0;
using (var cmd = con.CreateCommand())
return GetMaxValue(cmd, table, column);
} // end using
command.CommandText = "SELECT MAX(" + column + ") FROM " + table;
object result = command.ExecuteScalar();
return DataTool.AsLong(result) ?? 0;
} // end method
/// <summary>
/// Gets the next value in the specified sequence and increases the seed by
/// the specified amount. For example, if the seed is currently 10 and
/// increaseBy is 5, the value returned is 11 and the value returned from
/// the next call will be 16.
/// </summary>
/// <param name="table">
/// The name of the table from which to query.
/// </param>
/// <param name="column">
/// The name of the column for which to select the max value.
/// </param>
/// <param name="increaseBy">
/// The amount to increase the sequence by (affecting the next call).
/// </param>
/// <returns>
/// The next value in the specified sequence.
/// </returns>
public virtual long GetNextValues(string table, string column, int increaseBy) {
if (increaseBy < 1)
throw new ArgumentException("The increaesBy parameter must be greater than 0.", "increaseBy");
long sequence;
if (IsBackingTablePresent) {
using (var con = openConnection())
using (var transaction = con.BeginTransaction())
using (var cmd = con.CreateCommand()) {
cmd.AddParameter("TableName", table);
cmd.AddParameter("ColumnName", column);
cmd.CommandText = "UPDATE " + BackingTableName + Environment.NewLine +
"SET SequenceValue = SequenceValue + " + increaseBy + Environment.NewLine +
"WHERE TableName = " + cmd.FormatParameter("TableName") + Environment.NewLine +
"AND ColumnName = " + cmd.FormatParameter("ColumnName");
cmd.Transaction = transaction;
bool loop = true;
while (loop)
try {
cmd.ExecuteNonQuery();
loop = false;
} catch (OleDbException e) {
// Instead of waiting (like every other database in the world)
// MS Access throws this exception. Simulate waiting by
// repeating the query until it works.
if (e.Message == "Could not update; currently locked.")
Thread.Sleep(100);
else
throw;
} // end try-catch
cmd.CommandText = "SELECT SequenceValue " + Environment.NewLine +
"FROM " + BackingTableName + Environment.NewLine +
"WHERE TableName = " + cmd.FormatParameter("TableName") + Environment.NewLine +
"AND ColumnName = " + cmd.FormatParameter("ColumnName");
var result = cmd.ExecuteScalar();
if (result == null || result == DBNull.Value) {
sequence = GetMaxValue(cmd, table, column) + increaseBy;
cmd.CommandText = "INSERT INTO " + BackingTableName + Environment.NewLine +
"(TableName, ColumnName, SequenceValue)" + Environment.NewLine +
"VALUES (" + cmd.FormatParameter("TableName") + ", " +
cmd.FormatParameter("ColumnName") + ", " +
cmd.FormatParameter("SequenceValue") + ")";
cmd.AddParameter("SequenceValue", sequence);
cmd.ExecuteNonQuery();
} else
sequence = DataTool.AsLong(result) ?? -1;
transaction.Commit();
} // end using
} else lock (sequences) {
var key = table + '.' + column;
if (sequences.ContainsKey(key))
sequence = sequences[key];
else
sequence = GetMaxValue(null, table, column);
sequence += increaseBy;
sequences[key] = sequence;
} // end else-lock
return sequence - increaseBy + 1;
} // end method
public virtual bool IsBackingTablePresent {
get {
if (isBackingTablePresent == null)
lock (this)
if (isBackingTablePresent == null) {
var schema = GetBackingTableSchema();
isBackingTablePresent = schema != null;
if (isBackingTablePresent.Value) {
ValidateBackingTableSchema(schema);
ValidateLocking();
} // end if
} // end if
return isBackingTablePresent.Value;
} // end get
} // end method
private string lockKey;
private string LockKey {
get {
if (lockKey != null)
return lockKey;
var now = DateTime.UtcNow;
lockKey = "Sequencer.LockKey:" + (now.Date - now).Milliseconds;
return lockKey;
} // end get
} // get method
private void SetupValidateLockingRecord() {
using (var con = openConnection())
using (var cmd = con.CreateCommand()) {
/*
cmd.CommandText = "DELETE FROM " + BackingTableName + Environment.NewLine +
"WHERE TableName LIKE " + cmd.FormatParameter("TableName") + Environment.NewLine +
"AND ColumnName LIKE " + cmd.FormatParameter("ColumnName");
cmd.AddParameter("TableName", "Sequencer.LockKey:%");
cmd.AddParameter("ColumnName", "Sequencer.LockKey:%");
cmd.ExecuteNonQuery();
*/
cmd.CommandText = "INSERT INTO " + BackingTableName + Environment.NewLine +
"(TableName, ColumnName, SequenceValue)" + Environment.NewLine +
"VALUES (" + cmd.FormatParameter("TableName") + ", " +
cmd.FormatParameter("ColumnName") + ", " +
cmd.FormatParameter("SequenceValue") + ")";
cmd.AddParameter("TableName", LockKey);
cmd.AddParameter("ColumnName", LockKey);
cmd.AddParameter("SequenceValue", 0);
cmd.ExecuteNonQuery();
} // end using
} // end method
private void ValidateBackingTableSchema(DataTable schema) {
var isTableNameExists = false;
var isColumnNameExists = false;
var isSequenceValueExists = false;
for (int i = 0; i < schema.Rows.Count; i++) {
var column = (string)schema.Rows[i]["ColumnName"];
if (column.Is("TableName"))
isTableNameExists = true;
if (column.Is("ColumnName"))
isColumnNameExists = true;
if (column.Is("SequenceValue"))
isSequenceValueExists = true;
} // end for
if (!isTableNameExists || !isColumnNameExists || !isSequenceValueExists)
throw new DataException("The " + BackingTableName +
" does not contain the required columns " +
"(TableName, ColumnName, and SequenceValue).");
} // end method
private void ValidateLocking() {
object sequenceObject;
SetupValidateLockingRecord();
WaitForValidateLockingRecord();
using (var con = openConnection())
using (var cmd = con.CreateCommand()) {
cmd.AddParameter("TableName", LockKey);
cmd.AddParameter("ColumnName", LockKey);
var thread = new Thread(() => {
GetNextValues(LockKey, LockKey, 1);
});
using (var transaction = con.BeginTransaction()) {
cmd.CommandText = "UPDATE " + BackingTableName + Environment.NewLine +
"SET SequenceValue = SequenceValue + 1" + Environment.NewLine +
"WHERE TableName = " + cmd.FormatParameter("TableName") + Environment.NewLine +
"AND ColumnName = " + cmd.FormatParameter("ColumnName");
cmd.Transaction = transaction;
cmd.ExecuteNonQuery();
thread.Start();
Thread.Sleep(300);
cmd.CommandText = "SELECT SequenceValue " + Environment.NewLine +
"FROM " + BackingTableName + Environment.NewLine +
"WHERE TableName = " + cmd.FormatParameter("TableName") + Environment.NewLine +
"AND ColumnName = " + cmd.FormatParameter("ColumnName");
sequenceObject = cmd.ExecuteScalar();
transaction.Commit();
} // end using
thread.Join();
cmd.CommandText = "DELETE FROM " + BackingTableName + Environment.NewLine +
"WHERE TableName = " + cmd.FormatParameter("TableName") + Environment.NewLine +
"AND ColumnName = " + cmd.FormatParameter("ColumnName");
cmd.ExecuteNonQuery();
} // end using
var sequence = DataTool.AsLong(sequenceObject) ?? -1;
if (sequence == -1)
throw new DataException("The SequenceValue column of " + BackingTableName +
" does not appear to be an integer type.");
if (sequence > 1)
throw new DataException("The database or the table " + BackingTableName +
" does not support locking.");
} // end method
private void WaitForValidateLockingRecord() {
bool exists = false;
while (!exists)
using (var con = openConnection())
using (var cmd = con.CreateCommand()) {
cmd.CommandText = "SELECT COUNT(*) FROM " + BackingTableName + Environment.NewLine +
"WHERE TableName = " + cmd.FormatParameter("TableName") + Environment.NewLine +
"AND ColumnName = " + cmd.FormatParameter("ColumnName");
cmd.AddParameter("TableName", LockKey);
cmd.AddParameter("ColumnName", LockKey);
var count = cmd.ExecuteScalar();
exists = (DataTool.AsLong(count) ?? 0) == 1;
Thread.Sleep(50);
} // end using
} // end method
} // end class
} // end namespace