-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDB.cs
More file actions
631 lines (575 loc) · 23.7 KB
/
Copy pathDB.cs
File metadata and controls
631 lines (575 loc) · 23.7 KB
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
using System.Data.Common;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text.Json;
using System.Text.Json.Nodes;
using Microsoft.Data.SqlClient;
namespace CLOOPS.microservices;
/// <summary>
/// Defines the functionality required to execute SQL commands within a transaction.
/// </summary>
public interface IDBTransaction : IAsyncDisposable
{
/// <summary>
/// Executes a SQL command (INSERT, UPDATE, DELETE) within the transaction and returns the number of affected rows.
/// </summary>
/// <param name="query">SQL command to execute.</param>
/// <param name="parameters">Optional parameters to bind to the SQL command.</param>
/// <param name="timeout">Command timeout in seconds.</param>
/// <param name="cancellationToken">Cancellation token to cancel the operation.</param>
/// <returns>Number of rows affected by the command.</returns>
Task<int> ExecuteNonQueryAsync(string query, SqlParameter[]? parameters = null, int timeout = 30, CancellationToken cancellationToken = default);
/// <summary>
/// Executes a SQL query asynchronously within the transaction and streams the result set as strongly typed objects.
/// </summary>
/// <typeparam name="T">The result type that each row is mapped to.</typeparam>
/// <param name="query">The SQL query to execute.</param>
/// <param name="parameters">Optional parameters to bind to the SQL command.</param>
/// <param name="timeout">Command timeout in seconds.</param>
/// <param name="cancellationToken">Token used to cancel the operation.</param>
/// <returns>A streamed sequence of results of type <typeparamref name="T"/>.</returns>
IAsyncEnumerable<T> ExecuteReadAsync<T>(string query, SqlParameter[]? parameters = null, int timeout = 30, CancellationToken cancellationToken = default) where T : class;
/// <summary>
/// Commits the transaction asynchronously.
/// </summary>
/// <param name="cancellationToken">Cancellation token to cancel the operation.</param>
Task CommitAsync(CancellationToken cancellationToken = default);
/// <summary>
/// Rolls back the transaction asynchronously.
/// </summary>
/// <param name="cancellationToken">Cancellation token to cancel the operation.</param>
Task RollbackAsync(CancellationToken cancellationToken = default);
}
/// <summary>
/// Defines the functionality required to execute SQL commands against the application's database.
/// </summary>
public interface IDB
{
/// <summary>
/// Gets the connection string used for SQL connections.
/// </summary>
public string cnstr { get; }
/// <summary>
/// Executes a SQL query asynchronously and streams the result set as strongly typed objects.
/// </summary>
/// <typeparam name="T">The result type that each row is mapped to.</typeparam>
/// <param name="query">The SQL query to execute.</param>
/// <param name="parameters">Optional parameters to bind to the SQL command.</param>
/// <param name="infoMessageCallback">Callback used to surface SQL Server informational messages.</param>
/// <param name="timeout">Command timeout in seconds.</param>
/// <param name="cancellationToken">Token used to cancel the operation.</param>
/// <returns>A streamed sequence of results of type <typeparamref name="T"/>.</returns>
IAsyncEnumerable<T> ExecuteReadAsync<T>(
string query,
SqlParameter[]? parameters = null,
Action<string>? infoMessageCallback = null,
int timeout = 30,
CancellationToken cancellationToken = default
) where T : class;
/// <summary>
/// Executes a SQL command (INSERT, UPDATE, DELETE) asynchronously and returns the number of affected rows.
/// </summary>
/// <param name="query">SQL command to execute.</param>
/// <param name="parameters">Optional parameters to bind to the SQL command.</param>
/// <param name="infoMessageCallback">Callback used to surface SQL Server informational messages.</param>
/// <param name="timeout">Command timeout in seconds.</param>
/// <param name="cancellationToken">Cancellation token to cancel the operation.</param>
/// <returns>Number of rows affected by the command.</returns>
Task<int> ExecuteNonQueryAsync(
string query,
SqlParameter[]? parameters = null,
Action<string>? infoMessageCallback = null,
int timeout = 30,
CancellationToken cancellationToken = default
);
/// <summary>
/// Executes a SQL query asynchronously and returns the first column of the first row.
/// </summary>
/// <typeparam name="T">Expected return type.</typeparam>
/// <param name="query">SQL query to execute.</param>
/// <param name="parameters">Optional parameters to bind to the SQL command.</param>
/// <param name="infoMessageCallback">Callback used to surface SQL Server informational messages.</param>
/// <param name="timeout">Command timeout in seconds.</param>
/// <param name="cancellationToken">Cancellation token to cancel the operation.</param>
/// <returns>Scalar value of type T, or default(T) if no result.</returns>
Task<T?> ExecuteScalarAsync<T>(
string query,
SqlParameter[]? parameters = null,
Action<string>? infoMessageCallback = null,
int timeout = 30,
CancellationToken cancellationToken = default
);
/// <summary>
/// Begins a new database transaction asynchronously.
/// </summary>
/// <param name="cancellationToken">Cancellation token to cancel the operation.</param>
/// <returns>A database transaction object that can be used to execute commands atomically.</returns>
Task<IDBTransaction> BeginTransactionAsync(CancellationToken cancellationToken = default);
/// <summary>
/// Executes an action within a database transaction, committing on success and rolling back on failure.
/// </summary>
/// <typeparam name="T">The type of result returned by the action.</typeparam>
/// <param name="action">The action to execute within the transaction.</param>
/// <param name="cancellationToken">Cancellation token to cancel the operation.</param>
/// <returns>The result returned by the action.</returns>
Task<T> RunInTransaction<T>(
Func<IDBTransaction, Task<T>> action,
CancellationToken cancellationToken = default
);
/// <summary>
/// Executes a SQL script that contains <c>GO</c> batch separators.
/// </summary>
/// <param name="sqlScript">The full SQL script to execute.</param>
/// <param name="infoMessageCallback">Callback used to surface SQL Server informational messages.</param>
/// <param name="timeout">Command timeout in seconds for each batch.</param>
/// <param name="cancellationToken">Token used to cancel the operation.</param>
/// <returns>A list of string results produced by the executed batches.</returns>
Task<List<string>> ExecuteSQLScriptWithGo(string sqlScript, Action<string>? infoMessageCallback = null, int timeout = 600, CancellationToken cancellationToken = default);
}
/// <summary>
/// Provides a concrete implementation of a database transaction for executing SQL commands atomically.
/// </summary>
public class DBTransaction : IDBTransaction
{
private readonly SqlConnection _connection;
private SqlTransaction? _transaction;
private bool _disposed = false;
/// <summary>
/// Initializes a new instance of the <see cref="DBTransaction"/> class.
/// </summary>
/// <param name="connection">The SQL connection to use for the transaction.</param>
/// <param name="transaction">The SQL transaction object.</param>
internal DBTransaction(SqlConnection connection, SqlTransaction transaction)
{
_connection = connection;
_transaction = transaction;
}
/// <inheritdoc/>
public async Task<int> ExecuteNonQueryAsync(string query, SqlParameter[]? parameters = null, int timeout = 30, CancellationToken cancellationToken = default)
{
if (_disposed || _transaction == null)
throw new ObjectDisposedException(nameof(DBTransaction));
return await DB.ExecuteNonQueryInternalAsync(
query,
parameters,
timeout,
_connection,
_transaction,
cancellationToken);
}
/// <inheritdoc/>
public async IAsyncEnumerable<T> ExecuteReadAsync<T>(string query, SqlParameter[]? parameters = null, int timeout = 30, [EnumeratorCancellation] CancellationToken cancellationToken = default) where T : class
{
if (_disposed || _transaction == null)
throw new ObjectDisposedException(nameof(DBTransaction));
await foreach (var item in DB.ExecuteReadInternalAsync<T>(
query,
parameters,
timeout,
_connection,
_transaction,
cancellationToken))
{
yield return item;
}
}
/// <inheritdoc/>
public async Task CommitAsync(CancellationToken cancellationToken = default)
{
if (_disposed || _transaction == null)
throw new ObjectDisposedException(nameof(DBTransaction));
await _transaction.CommitAsync(cancellationToken);
}
/// <inheritdoc/>
public async Task RollbackAsync(CancellationToken cancellationToken = default)
{
if (_disposed || _transaction == null)
throw new ObjectDisposedException(nameof(DBTransaction));
await _transaction.RollbackAsync(cancellationToken);
}
/// <inheritdoc/>
public async ValueTask DisposeAsync()
{
if (_disposed)
return;
if (_transaction != null)
{
await _transaction.DisposeAsync();
_transaction = null;
}
if (_connection != null)
{
await _connection.CloseAsync();
await _connection.DisposeAsync();
}
_disposed = true;
}
}
/// <summary>
/// Provides concrete implementations for executing SQL commands against a SQL Server database.
/// </summary>
public class DB : IDB
{
private string _cnstr;
/// <summary>
/// Initializes a new instance of the <see cref="DB"/> class with the provided connection string.
/// </summary>
/// <param name="cnstr">The SQL Server connection string.</param>
public DB(string cnstr)
{
_cnstr = cnstr;
}
/// <inheritdoc/>
public string cnstr
{
get
{
return _cnstr;
}
}
/// <summary>
/// Executes a data extracting SQL statement and streams the result one row at a time.
/// </summary>
/// <typeparam name="T">The result type that each row is mapped to.</typeparam>
/// <param name="query">The SQL query to execute.</param>
/// <param name="parameters">Optional parameters to bind to the SQL command.</param>
/// <param name="infoMessageCallback">Optional callback for handling <see cref="SqlConnection.InfoMessage"/> events.</param>
/// <param name="timeout">Command timeout in seconds.</param>
/// <param name="cancellationToken">Cancellation token to cancel the operation.</param>
/// <returns>A streamed sequence of results of type <typeparamref name="T"/>.</returns>
public async IAsyncEnumerable<T> ExecuteReadAsync<T>(
string query,
SqlParameter[]? parameters = null,
Action<string>? infoMessageCallback = null,
int timeout = 30,
[EnumeratorCancellation] CancellationToken cancellationToken = default
) where T : class
{
using var connection = new SqlConnection(_cnstr);
connection.InfoMessage += (sender, e) =>
{
infoMessageCallback?.Invoke(e.Message);
};
await connection.OpenAsync(cancellationToken);
await foreach (var item in ExecuteReadInternalAsync<T>(
query,
parameters,
timeout,
connection,
transaction: null,
cancellationToken))
{
yield return item;
}
}
/// <inheritdoc/>
public async Task<int> ExecuteNonQueryAsync(
string query,
SqlParameter[]? parameters = null,
Action<string>? infoMessageCallback = null,
int timeout = 30,
CancellationToken cancellationToken = default
)
{
using var connection = new SqlConnection(_cnstr);
connection.InfoMessage += (sender, e) =>
{
infoMessageCallback?.Invoke(e.Message);
};
await connection.OpenAsync(cancellationToken);
return await ExecuteNonQueryInternalAsync(query, parameters, timeout, connection, transaction: null, cancellationToken);
}
/// <inheritdoc/>
public async Task<T?> ExecuteScalarAsync<T>(
string query,
SqlParameter[]? parameters = null,
Action<string>? infoMessageCallback = null,
int timeout = 30,
CancellationToken cancellationToken = default
)
{
using var connection = new SqlConnection(_cnstr);
connection.InfoMessage += (sender, e) =>
{
infoMessageCallback?.Invoke(e.Message);
};
await connection.OpenAsync(cancellationToken);
return await ExecuteScalarInternalAsync<T>(query, parameters, timeout, connection, transaction: null, cancellationToken);
}
/// <inheritdoc/>
public async Task<IDBTransaction> BeginTransactionAsync(CancellationToken cancellationToken = default)
{
var connection = new SqlConnection(_cnstr);
await connection.OpenAsync(cancellationToken);
var transaction = (SqlTransaction)await connection.BeginTransactionAsync(cancellationToken);
return new DBTransaction(connection, transaction);
}
/// <inheritdoc/>
public async Task<T> RunInTransaction<T>(
Func<IDBTransaction, Task<T>> action,
CancellationToken cancellationToken = default
)
{
ArgumentNullException.ThrowIfNull(action);
await using var transaction = await BeginTransactionAsync(cancellationToken);
try
{
var result = await action(transaction);
await transaction.CommitAsync(cancellationToken);
return result;
}
catch
{
await transaction.RollbackAsync(cancellationToken);
throw;
}
}
internal static async IAsyncEnumerable<T> ExecuteReadInternalAsync<T>(
string query,
SqlParameter[]? parameters,
int timeout,
SqlConnection connection,
SqlTransaction? transaction,
[EnumeratorCancellation] CancellationToken cancellationToken
) where T : class
{
var command = transaction != null
? new SqlCommand(query, connection, transaction)
: new SqlCommand(query, connection);
command.CommandTimeout = timeout;
if (parameters != null)
{
command.Parameters.AddRange(parameters);
}
using var reader = await command.ExecuteReaderAsync(cancellationToken);
var type = typeof(T);
Dictionary<string, PropertyInfo> typePropertyCache = GetPropertiesCache(type);
var colSchema = await reader.GetColumnSchemaAsync(cancellationToken);
while (await reader.ReadAsync(cancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
var item = CreateInstance<T>(type);
foreach (var column in colSchema)
{
if (column.ColumnOrdinal is null)
{
continue;
}
var columnValue = reader.GetValue(column.ColumnOrdinal.Value);
if (typePropertyCache.TryGetValue(column.ColumnName, out var cachedPropertyInfo))
{
AddValueToObject(item, cachedPropertyInfo, columnValue);
}
else if (item is JsonObject jsonObject)
{
AddValueToJsonObject(jsonObject, column, columnValue);
}
else if (type == typeof(string))
{
item = (T)(object)(columnValue.ToString() ?? string.Empty);
}
else if (AtomicTypes.Contains(type))
{
item = (T)columnValue;
}
}
yield return item;
}
}
internal static async Task<int> ExecuteNonQueryInternalAsync(
string query,
SqlParameter[]? parameters,
int timeout,
SqlConnection connection,
SqlTransaction? transaction,
CancellationToken cancellationToken
)
{
var command = transaction != null
? new SqlCommand(query, connection, transaction)
: new SqlCommand(query, connection);
command.CommandTimeout = timeout;
if (parameters != null)
{
command.Parameters.AddRange(parameters);
}
return await command.ExecuteNonQueryAsync(cancellationToken);
}
internal static async Task<T?> ExecuteScalarInternalAsync<T>(
string query,
SqlParameter[]? parameters,
int timeout,
SqlConnection connection,
SqlTransaction? transaction,
CancellationToken cancellationToken
)
{
var command = transaction != null
? new SqlCommand(query, connection, transaction)
: new SqlCommand(query, connection);
command.CommandTimeout = timeout;
if (parameters != null)
{
command.Parameters.AddRange(parameters);
}
var result = await command.ExecuteScalarAsync(cancellationToken);
if (result == null || result == DBNull.Value)
{
return default;
}
return (T)Convert.ChangeType(result, typeof(T));
}
/// <summary>
/// Creates an array of <see cref="SqlParameter"/> instances from name-value tuples.
/// </summary>
/// <param name="sqlParams">Comma separated tuples. First item is the parameter name, second item is the parameter value.</param>
/// <returns>An array of <see cref="SqlParameter"/> instances created from the provided tuples.</returns>
public static SqlParameter[] pars(params (string, object?)[] sqlParams)
{
SqlParameter[] retval = new SqlParameter[sqlParams.Length];
for (int i = 0; i < sqlParams.Length; i++)
{
retval[i] = new SqlParameter(sqlParams[i].Item1, sqlParams[i].Item2 ?? DBNull.Value);
}
return retval;
}
/// <summary>
/// Executes a SQL script in batches separated by <c>GO</c> statements.
/// </summary>
/// <param name="sqlScript">The full SQL script to execute.</param>
/// <param name="infoMessageCallback">Optional callback for handling <see cref="SqlConnection.InfoMessage"/> events.</param>
/// <param name="timeout">Command timeout in seconds for each batch.</param>
/// <param name="cancellationToken">Cancellation token to cancel the operation.</param>
/// <returns>A list of string results produced by the executed batches.</returns>
public async Task<List<string>> ExecuteSQLScriptWithGo(string sqlScript, Action<string>? infoMessageCallback = null, int timeout = 600, CancellationToken cancellationToken = default)
{
var batches = System.Text.RegularExpressions.Regex.Split(sqlScript, @"^\s*GO\s*$", System.Text.RegularExpressions.RegexOptions.Multiline | System.Text.RegularExpressions.RegexOptions.IgnoreCase);
var retval = new List<string>();
foreach (var batch in batches)
{
var trimmed = batch.Trim();
if (!string.IsNullOrWhiteSpace(trimmed))
{
var result = await ExecuteReadAsync<string>(trimmed, null, infoMessageCallback, timeout, cancellationToken).ToArrayAsync();
retval.AddRange(result);
Thread.Sleep(500); // Adding wait for server to process the command
}
}
return retval;
}
#region utilityFunctions
internal static Dictionary<string, PropertyInfo> GetPropertiesCache(Type type)
{
Dictionary<string, PropertyInfo> typePropertyCache = new Dictionary<string, PropertyInfo>(StringComparer.OrdinalIgnoreCase);
if (type == typeof(JsonObject))
{
return typePropertyCache;
}
foreach (var prop in type.GetProperties())
{
typePropertyCache.Add(prop.Name, prop);
}
return typePropertyCache;
}
internal static T CreateInstance<T>(Type type) where T : class
{
if (type == typeof(JsonObject))
{
return (T)(object)new JsonObject();
}
else if (type == typeof(string))
{
return (T)(object)string.Empty;
}
else if (AtomicTypes.Contains(type))
{
return (T?)Activator.CreateInstance(type) ?? throw new InvalidOperationException($"Could not create an instance of {type}.");
}
else
{
return (T?)Activator.CreateInstance(type) ?? throw new InvalidOperationException($"Could not create an instance of {type}.");
}
}
internal static void AddValueToJsonObject(JsonObject item, DbColumn column, object columnValue)
{
if (column.DataType == typeof(string))
{
var strValue = columnValue.ToString();
if
(
strValue != null &&
(
(strValue.StartsWith('{') && strValue.EndsWith('}'))
||
(strValue.StartsWith('[') && strValue.EndsWith(']'))
)
)
{
item.Add(new KeyValuePair<string, JsonNode?>(column.ColumnName, JsonNode.Parse(strValue)));
return;
}
}
item.Add(new KeyValuePair<string, JsonNode?>(column.ColumnName, JsonValue.Create(columnValue)));
}
internal static void AddValueToObject<T>(T item, PropertyInfo pinfo, object columnValue)
{
if (AtomicTypes.Contains(pinfo.PropertyType) || pinfo.PropertyType.IsEnum)
{
pinfo.SetValue(item, columnValue == DBNull.Value ? null : columnValue);
}
else if (pinfo.PropertyType == typeof(JsonObject))
{
pinfo.SetValue(item, columnValue == DBNull.Value ? null : JsonNode.Parse(columnValue.ToString() ?? "{}"));
}
else if (pinfo.PropertyType.IsArray || (pinfo.PropertyType.IsGenericType && pinfo.PropertyType.GetGenericTypeDefinition() == typeof(List<>)))
{
var jarr = JsonNode.Parse(columnValue == DBNull.Value ? "[]" : (columnValue.ToString() ?? "[]"));
pinfo.SetValue(item, jarr.Deserialize(pinfo.PropertyType, BaseUtil.JsonSerializerOptions));
}
else
{
var jobj = JsonNode.Parse(columnValue == DBNull.Value ? "{}" : (columnValue.ToString() ?? "{}"));
pinfo.SetValue(item, jobj.Deserialize(pinfo.PropertyType, BaseUtil.JsonSerializerOptions));
}
}
internal static readonly HashSet<Type> AtomicTypes = new HashSet<Type>
{
typeof(string),
typeof(int),
typeof(float),
typeof(double),
typeof(decimal),
typeof(bool),
typeof(byte),
typeof(sbyte),
typeof(short),
typeof(ushort),
typeof(uint),
typeof(long),
typeof(ulong),
typeof(char),
typeof(DateTime),
typeof(DateTimeOffset),
typeof(TimeSpan),
typeof(Guid),
//nullables
typeof(int?),
typeof(float?),
typeof(double?),
typeof(decimal?),
typeof(bool?),
typeof(byte?),
typeof(sbyte?),
typeof(short?),
typeof(ushort?),
typeof(uint?),
typeof(long?),
typeof(ulong?),
typeof(char?),
typeof(DateTime?),
typeof(DateTimeOffset?),
typeof(TimeSpan?),
typeof(Guid?),
};
}
#endregion