generated from Avanade/avanade-template
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathDatabaseCommand.cs
More file actions
639 lines (562 loc) · 42.6 KB
/
DatabaseCommand.cs
File metadata and controls
639 lines (562 loc) · 42.6 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
632
633
634
635
636
637
638
639
// Copyright (c) Avanade. Licensed under the MIT License. See https://github.com/Avanade/CoreEx
using CoreEx.Entities;
using CoreEx.Results;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace CoreEx.Database
{
/// <summary>
/// Provides extended database command capabilities.
/// </summary>
/// <remarks>As the underlying <see cref="DbCommand"/> implements <see cref="IDisposable"/> this is only created (and automatically disposed) where executing the command proper.</remarks>
/// <param name="db">The <see cref="IDatabase"/>.</param>
/// <param name="commandType">The <see cref="System.Data.CommandType"/>.</param>
/// <param name="commandText">The command text.</param>
public sealed class DatabaseCommand(IDatabase db, CommandType commandType, string commandText) : IDatabaseParameters<DatabaseCommand>
{
/// <summary>
/// Gets the underlying <see cref="IDatabase"/>.
/// </summary>
public IDatabase Database { get; } = db.ThrowIfNull(nameof(db));
/// <inheritdoc/>
public DatabaseParameterCollection Parameters { get; } = new DatabaseParameterCollection(db);
/// <summary>
/// Gets the <see cref="System.Data.CommandType"/>.
/// </summary>
public CommandType CommandType { get; } = commandType;
/// <summary>
/// Gets the command text.
/// </summary>
public string CommandText { get; } = commandText.ThrowIfNull(nameof(commandText));
/// <summary>
/// Creates the corresponding <see cref="DbCommand"/>.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param>
/// <returns>The <see cref="DbCommand"/>.</returns>
private async Task<DbCommand> CreateDbCommandAsync(CancellationToken cancellationToken = default)
{
var cmd = (await Database.GetConnectionAsync(cancellationToken).ConfigureAwait(false)).CreateCommand();
cmd.CommandType = CommandType;
cmd.CommandText = CommandText;
cmd.Parameters.AddRange(Parameters.ToArray());
return cmd;
}
/// <summary>
/// Executes a multi-dataset query command with one or more <see cref="IMultiSetArgs"/>.
/// </summary>
/// <param name="multiSetArgs">One or more <see cref="IMultiSetArgs"/>.</param>
/// <remarks>The number of <see cref="IMultiSetArgs"/> specified must match the number of returned datasets. A null dataset indicates to ignore (skip) a dataset.</remarks>
public async Task SelectMultiSetAsync(params IMultiSetArgs[] multiSetArgs)
=> (await SelectMultiSetWithResultInternalAsync(multiSetArgs, nameof(SelectMultiSetAsync), default).ConfigureAwait(false)).ThrowOnError();
/// <summary>
/// Executes a multi-dataset query command with one or more <see cref="IMultiSetArgs"/> with a <see cref="Result{T}"/>.
/// </summary>
/// <param name="multiSetArgs">One or more <see cref="IMultiSetArgs"/>.</param>
/// <remarks>The number of <see cref="IMultiSetArgs"/> specified must match the number of returned datasets. A null dataset indicates to ignore (skip) a dataset.</remarks>
public Task<Result> SelectMultiSetWithResultAsync(params IMultiSetArgs[] multiSetArgs)
=> SelectMultiSetWithResultInternalAsync(multiSetArgs, nameof(SelectMultiSetWithResultAsync), default);
/// <summary>
/// Executes a multi-dataset query command with one or more <see cref="IMultiSetArgs"/>.
/// </summary>
/// <param name="multiSetArgs">One or more <see cref="IMultiSetArgs"/>.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param>
/// <remarks>The number of <see cref="IMultiSetArgs"/> specified must match the number of returned datasets. A null dataset indicates to ignore (skip) a dataset.</remarks>
public async Task SelectMultiSetAsync(IEnumerable<IMultiSetArgs> multiSetArgs, CancellationToken cancellationToken = default)
=> (await SelectMultiSetWithResultInternalAsync(multiSetArgs, nameof(SelectMultiSetAsync), cancellationToken).ConfigureAwait(false)).ThrowOnError();
/// <summary>
/// Executes a multi-dataset query command with one or more <see cref="IMultiSetArgs"/> with a <see cref="Result{T}"/>.
/// </summary>
/// <param name="multiSetArgs">One or more <see cref="IMultiSetArgs"/>.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param>
/// <remarks>The number of <see cref="IMultiSetArgs"/> specified must match the number of returned datasets. A null dataset indicates to ignore (skip) a dataset.</remarks>
public Task<Result> SelectMultiSetWithResultAsync(IEnumerable<IMultiSetArgs> multiSetArgs, CancellationToken cancellationToken = default)
=> SelectMultiSetWithResultInternalAsync(multiSetArgs, nameof(SelectMultiSetWithResultAsync), cancellationToken);
/// <summary>
/// Executes a multi-dataset query command with one or more <see cref="IMultiSetArgs"/> with a <see cref="Result{T}"/> internal.
/// </summary>
private Task<Result> SelectMultiSetWithResultInternalAsync(IEnumerable<IMultiSetArgs> multiSetArgs, string memberName, CancellationToken cancellationToken = default)
{
var multiSetList = multiSetArgs?.ToList() ?? null;
if (multiSetList == null || multiSetList.Count == 0)
throw new ArgumentException($"At least one {nameof(IMultiSetArgs)} must be supplied.", nameof(multiSetArgs));
return Database.Invoker.InvokeAsync(Database, multiSetArgs, multiSetList, async (_, multiSetArgs, multiSetList, ct) =>
{
// Create and execute the command.
using var cmd = await CreateDbCommandAsync(ct).ConfigureAwait(false);
using var dr = await cmd.ExecuteReaderAsync(ct).ConfigureAwait(false);
// Iterate through the dataset(s).
var index = 0;
var records = 0;
IMultiSetArgs? multiSetArg = null;
do
{
if (index >= multiSetList.Count)
return Result.Fail(new InvalidOperationException($"{nameof(SelectMultiSetAsync)} has returned more record sets than expected ({multiSetList.Count})."));
if (multiSetList[index] != null)
{
records = 0;
multiSetArg = multiSetList[index];
while (await dr.ReadAsync(ct).ConfigureAwait(false))
{
records++;
if (multiSetArg.MaxRows.HasValue && records > multiSetArg.MaxRows.Value)
return Result.Fail(new InvalidOperationException($"{nameof(SelectMultiSetAsync)} (msa[{index}]) has returned more records than expected ({multiSetArg.MaxRows.Value})."));
multiSetArg.DatasetRecord(new DatabaseRecord(Database, dr));
}
if (records < multiSetArg.MinRows)
return Result.Fail(new InvalidOperationException($"{nameof(SelectMultiSetAsync)} (msa[{index}]) has returned less records ({records}) than expected ({multiSetArg.MinRows})."));
if (records == 0 && multiSetArg.StopOnNull)
return Result.Success;
multiSetArg.InvokeResult();
}
index++;
} while (dr.NextResult());
return index < multiSetList.Count && !multiSetList[index].StopOnNull
? Result.Fail(new InvalidOperationException($"{nameof(SelectMultiSetAsync)} has returned less ({index}) record sets than expected ({multiSetList.Count})."))
: Result.Success;
}, cancellationToken, memberName);
}
/// <summary>
/// Executes a multi-dataset query command with one or more <see cref="IMultiSetArgs"/> that supports <paramref name="paging"/>.
/// </summary>
/// <param name="paging">The <see cref="PagingArgs"/> or <see cref="PagingResult"/> to add to the <see cref="Parameters"/>.</param>
/// <param name="multiSetArgs">One or more <see cref="IMultiSetArgs"/>.</param>
/// <remarks>The number of <see cref="IMultiSetArgs"/> specified must match the number of returned datasets. A null dataset indicates to ignore (skip) a dataset.</remarks>
public async Task SelectMultiSetAsync(PagingArgs? paging, params IMultiSetArgs[] multiSetArgs)
=> (await SelectMultiSetWithResultInternalAsync(paging, multiSetArgs, nameof(SelectMultiSetAsync), default).ConfigureAwait(false)).ThrowOnError();
/// <summary>
/// Executes a multi-dataset query command with one or more <see cref="IMultiSetArgs"/> that supports <paramref name="paging"/> with a <see cref="Result"/>.
/// </summary>
/// <param name="paging">The <see cref="PagingArgs"/> or <see cref="PagingResult"/> to add to the <see cref="Parameters"/>.</param>
/// <param name="multiSetArgs">One or more <see cref="IMultiSetArgs"/>.</param>
/// <remarks>The number of <see cref="IMultiSetArgs"/> specified must match the number of returned datasets. A null dataset indicates to ignore (skip) a dataset.</remarks>
public Task<Result> SelectMultiSetWithResultAsync(PagingArgs? paging, params IMultiSetArgs[] multiSetArgs)
=> SelectMultiSetWithResultInternalAsync(paging, multiSetArgs, nameof(SelectMultiSetWithResultAsync), default);
/// <summary>
/// Executes a multi-dataset query command with one or more <see cref="IMultiSetArgs"/> that supports <paramref name="paging"/>.
/// </summary>
/// <param name="paging">The <see cref="PagingArgs"/> or <see cref="PagingResult"/> to add to the <see cref="Parameters"/>.</param>
/// <param name="multiSetArgs">One or more <see cref="IMultiSetArgs"/>.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param>
/// <remarks>The number of <see cref="IMultiSetArgs"/> specified must match the number of returned datasets. A null dataset indicates to ignore (skip) a dataset.</remarks>
public async Task SelectMultiSetAsync(PagingArgs? paging, IEnumerable<IMultiSetArgs> multiSetArgs, CancellationToken cancellationToken = default)
=> (await SelectMultiSetWithResultInternalAsync(paging, multiSetArgs, nameof(SelectMultiSetAsync), cancellationToken).ConfigureAwait(false)).ThrowOnError();
/// <summary>
/// Executes a multi-dataset query command with one or more <see cref="IMultiSetArgs"/> that supports <paramref name="paging"/> with a <see cref="Result"/>.
/// </summary>
/// <param name="paging">The <see cref="PagingArgs"/> or <see cref="PagingResult"/> to add to the <see cref="Parameters"/>.</param>
/// <param name="multiSetArgs">One or more <see cref="IMultiSetArgs"/>.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param>
/// <remarks>The number of <see cref="IMultiSetArgs"/> specified must match the number of returned datasets. A null dataset indicates to ignore (skip) a dataset.</remarks>
public Task<Result> SelectMultiSetWithResultAsync(PagingArgs? paging, IEnumerable<IMultiSetArgs> multiSetArgs, CancellationToken cancellationToken = default)
=> SelectMultiSetWithResultInternalAsync(paging, multiSetArgs, nameof(SelectMultiSetWithResultAsync), cancellationToken);
/// <summary>
/// Executes a multi-dataset query command with one or more <see cref="IMultiSetArgs"/> that supports <paramref name="paging"/> with a <see cref="Result"/> internal.
/// </summary>
private async Task<Result> SelectMultiSetWithResultInternalAsync(PagingArgs? paging, IEnumerable<IMultiSetArgs> multiSetArgs, string memberName, CancellationToken cancellationToken)
{
Parameters.PagingParams(paging);
var result = await SelectMultiSetWithValueResultInternalAsync(multiSetArgs, memberName, cancellationToken).ConfigureAwait(false);
return result.ThenAs(rv =>
{
if (paging is PagingResult pr && pr.IsGetCount && rv >= 0)
pr.TotalCount = rv;
});
}
/// <summary>
/// Executes a multi-dataset query command with one or more <see cref="IMultiSetArgs"/>; whilst also outputing the resulting <see cref="int"/> <see cref="ParameterDirection.ReturnValue"/>.
/// </summary>
/// <param name="multiSetArgs">One or more <see cref="IMultiSetArgs"/>.</param>
/// <returns>The resultant return value.</returns>
/// <remarks>The number of <see cref="IMultiSetArgs"/> specified must match the number of returned datasets. A null dataset indicates to ignore (skip) a dataset.</remarks>
public async Task<int> SelectMultiSetWithValueAsync(params IMultiSetArgs[] multiSetArgs)
=> await SelectMultiSetWithValueResultInternalAsync(multiSetArgs, nameof(SelectMultiSetWithValueAsync), default).ConfigureAwait(false);
/// <summary>
/// Executes a multi-dataset query command with one or more <see cref="IMultiSetArgs"/>; whilst also outputing the resulting <see cref="int"/> <see cref="ParameterDirection.ReturnValue"/> with a <see cref="Result{T}"/>.
/// </summary>
/// <param name="multiSetArgs">One or more <see cref="IMultiSetArgs"/>.</param>
/// <returns>The resultant return value.</returns>
/// <remarks>The number of <see cref="IMultiSetArgs"/> specified must match the number of returned datasets. A null dataset indicates to ignore (skip) a dataset.</remarks>
public Task<Result<int>> SelectMultiSetWithValueResultAsync(params IMultiSetArgs[] multiSetArgs)
=> SelectMultiSetWithValueResultInternalAsync(multiSetArgs, nameof(SelectMultiSetWithValueResultAsync), default);
/// <summary>
/// Executes a multi-dataset query command with one or more <see cref="IMultiSetArgs"/>; whilst also outputing the resulting <see cref="int"/> <see cref="ParameterDirection.ReturnValue"/>.
/// </summary>
/// <param name="multiSetArgs">One or more <see cref="IMultiSetArgs"/>.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param>
/// <returns>The resultant return value.</returns>
/// <remarks>The number of <see cref="IMultiSetArgs"/> specified must match the number of returned datasets. A null dataset indicates to ignore (skip) a dataset.</remarks>
public async Task<int> SelectMultiSetWithValueAsync(IEnumerable<IMultiSetArgs> multiSetArgs, CancellationToken cancellationToken = default)
=> await SelectMultiSetWithValueResultInternalAsync(multiSetArgs, nameof(SelectMultiSetWithValueAsync), cancellationToken).ConfigureAwait(false);
/// <summary>
/// Executes a multi-dataset query command with one or more <see cref="IMultiSetArgs"/>; whilst also outputing the resulting <see cref="int"/> <see cref="ParameterDirection.ReturnValue"/> with a <see cref="Result{T}"/>.
/// </summary>
/// <param name="multiSetArgs">One or more <see cref="IMultiSetArgs"/>.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param>
/// <returns>The resultant return value.</returns>
/// <remarks>The number of <see cref="IMultiSetArgs"/> specified must match the number of returned datasets. A null dataset indicates to ignore (skip) a dataset.</remarks>
public Task<Result<int>> SelectMultiSetWithValueResultAsync(IEnumerable<IMultiSetArgs> multiSetArgs, CancellationToken cancellationToken = default)
=> SelectMultiSetWithValueResultInternalAsync(multiSetArgs, nameof(SelectMultiSetWithValueResultAsync), cancellationToken);
/// <summary>
/// Executes a multi-dataset query command with one or more <see cref="IMultiSetArgs"/>; whilst also outputing the resulting <see cref="int"/> <see cref="ParameterDirection.ReturnValue"/> with a <see cref="Result{T}"/> internal.
/// </summary>
private async Task<Result<int>> SelectMultiSetWithValueResultInternalAsync(IEnumerable<IMultiSetArgs> multiSetArgs, string memberName, CancellationToken cancellationToken)
{
var rvp = Parameters.AddReturnValueParameter();
var result = await SelectMultiSetWithResultInternalAsync(multiSetArgs, memberName, cancellationToken).ConfigureAwait(false);
return result.ThenAs(() => rvp.Value == null ? -1 : (int)rvp.Value);
}
/// <summary>
/// Executes a non-query command.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param>
/// <returns>The number of rows affected.</returns>
public async Task<int> NonQueryAsync(CancellationToken cancellationToken = default)
=> await NonQueryWithResultInternalAsync(null, nameof(NonQueryAsync), cancellationToken).ConfigureAwait(false);
/// <summary>
/// Executes a non-query command with a <see cref="Result{T}"/>.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param>
/// <returns>The number of rows affected.</returns>
public Task<Result<int>> NonQueryWithResultAsync(CancellationToken cancellationToken = default)
=> NonQueryWithResultInternalAsync(null, nameof(NonQueryWithResultAsync), cancellationToken);
/// <summary>
/// Executes a non-query command.
/// </summary>
/// <param name="parameters">The post-execution delegate to enable parameter access.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param>
/// <returns>The number of rows affected.</returns>
public async Task<int> NonQueryAsync(Action<DbParameterCollection>? parameters, CancellationToken cancellationToken = default)
=> await NonQueryWithResultInternalAsync(parameters, nameof(NonQueryAsync), cancellationToken).ConfigureAwait(false);
/// <summary>
/// Executes a non-query command with a <see cref="Result{T}"/>.
/// </summary>
/// <param name="parameters">The post-execution delegate to enable parameter access.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param>
/// <returns>The number of rows affected.</returns>
public Task<Result<int>> NonQueryWithResultAsync(Action<DbParameterCollection>? parameters, CancellationToken cancellationToken = default)
=> NonQueryWithResultInternalAsync(parameters, nameof(NonQueryWithResultAsync), cancellationToken);
/// <summary>
/// Executes a non-query command with a <see cref="Result{T}"/> internal.
/// </summary>
private Task<Result<int>> NonQueryWithResultInternalAsync(Action<DbParameterCollection>? parameters, string memberName, CancellationToken cancellationToken = default) => Database.Invoker.InvokeAsync(Database, parameters, async (_, parameters, ct) =>
{
using var cmd = await CreateDbCommandAsync(ct).ConfigureAwait(false);
parameters?.Invoke(cmd.Parameters);
var result = await cmd.ExecuteNonQueryAsync(ct).ConfigureAwait(false);
return Result.Ok(result);
}, cancellationToken, memberName);
/// <summary>
/// Executes the query and returns the first column of the first row in the result set returned by the query.
/// </summary>
/// <typeparam name="T">The result <see cref="Type"/>.</typeparam>
/// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param>
/// <returns>The value of the first column of the first row in the result set.</returns>
public async Task<T> ScalarAsync<T>(CancellationToken cancellationToken = default)
=> await ScalarWithResultInternalAsync<T>(null, nameof(ScalarAsync), cancellationToken).ConfigureAwait(false);
/// <summary>
/// Executes the query and returns the first column of the first row in the result set returned by the query with a <see cref="Result{T}"/>.
/// </summary>
/// <typeparam name="T">The result <see cref="Type"/>.</typeparam>
/// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param>
/// <returns>The value of the first column of the first row in the result set.</returns>
public Task<Result<T>> ScalarWithResultAsync<T>(CancellationToken cancellationToken = default)
=> ScalarWithResultInternalAsync<T>(null, nameof(ScalarWithResultAsync), cancellationToken);
/// <summary>
/// Executes the query and returns the first column of the first row in the result set returned by the query.
/// </summary>
/// <typeparam name="T">The result <see cref="Type"/>.</typeparam>
/// <param name="parameters">The post-execution delegate to enable parameter access.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param>
/// <returns>The value of the first column of the first row in the result set.</returns>
public async Task<T> ScalarAsync<T>(Action<DbParameterCollection>? parameters, CancellationToken cancellationToken = default)
=> await ScalarWithResultInternalAsync<T>(parameters, nameof(ScalarAsync), cancellationToken).ConfigureAwait(false);
/// <summary>
/// Executes the query and returns the first column of the first row in the result set returned by the query with a <see cref="Result{T}"/>.
/// </summary>
/// <typeparam name="T">The result <see cref="Type"/>.</typeparam>
/// <param name="parameters">The post-execution delegate to enable parameter access.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param>
/// <returns>The value of the first column of the first row in the result set.</returns>
public Task<Result<T>> ScalarWithResultAsync<T>(Action<DbParameterCollection>? parameters, CancellationToken cancellationToken = default)
=> ScalarWithResultInternalAsync<T>(parameters, nameof(ScalarWithResultAsync), cancellationToken);
/// <summary>
/// Executes the query and returns the first column of the first row in the result set returned by the query with a <see cref="Result{T}"/> internal.
/// </summary>
private Task<Result<T>> ScalarWithResultInternalAsync<T>(Action<DbParameterCollection>? parameters, string memberName, CancellationToken cancellationToken = default) => Database.Invoker.InvokeAsync(Database, parameters, async (_, parameters, ct) =>
{
using var cmd = await CreateDbCommandAsync(ct).ConfigureAwait(false);
parameters?.Invoke(cmd.Parameters);
var result = await cmd.ExecuteScalarAsync(ct).ConfigureAwait(false);
T value = result is null ? default! : result is DBNull ? default! : (T)result;
return Result.Ok(value);
}, cancellationToken, memberName);
/// <summary>
/// Selects none or more items from the first result set using a <paramref name="mapper"/>.
/// </summary>
/// <typeparam name="T">The item <see cref="Type"/>.</typeparam>
/// <param name="mapper">The <see cref="IDatabaseMapper{T}"/>.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param>
/// <returns>The item sequence.</returns>
public async Task<IEnumerable<T>> SelectQueryAsync<T>(IDatabaseMapper<T> mapper, CancellationToken cancellationToken = default)
=> (await SelectQueryWithResultInternalAsync<T>(mapper, nameof(SelectQueryAsync), cancellationToken).ConfigureAwait(false)).Value;
/// <summary>
/// Selects none or more items from the first result set using a <paramref name="mapper"/> with a <see cref="Result{T}"/>.
/// </summary>
/// <typeparam name="T">The item <see cref="Type"/>.</typeparam>
/// <param name="mapper">The <see cref="IDatabaseMapper{T}"/>.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param>
/// <returns>The item sequence.</returns>
public Task<Result<IEnumerable<T>>> SelectQueryWithResultAsync<T>(IDatabaseMapper<T> mapper, CancellationToken cancellationToken = default)
=> SelectQueryWithResultInternalAsync(mapper, nameof(SelectQueryWithResultAsync), cancellationToken);
/// <summary>
/// Selects none or more items from the first result set using a <paramref name="mapper"/> with a <see cref="Result{T}"/> internal.
/// </summary>
private async Task<Result<IEnumerable<T>>> SelectQueryWithResultInternalAsync<T>(IDatabaseMapper<T> mapper, string memberName, CancellationToken cancellationToken)
{
var coll = new List<T>();
var result = await SelectQueryWithResultInternalAsync(coll, mapper, memberName, cancellationToken).ConfigureAwait(false);
return result.ThenAs(() => (IEnumerable<T>)coll);
}
/// <summary>
/// Selects none or more items from the first result set.
/// </summary>
/// <typeparam name="T">The item <see cref="Type"/>.</typeparam>
/// <param name="func">The <see cref="DatabaseRecord"/> mapping function.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param>
/// <returns>The resulting set.</returns>
public async Task<IEnumerable<T>> SelectQueryAsync<T>(Func<DatabaseRecord, T> func, CancellationToken cancellationToken = default)
=> (await SelectQueryWithResultInternalAsync<T>(func, nameof(SelectQueryAsync), cancellationToken).ConfigureAwait(false)).Value;
/// <summary>
/// Selects none or more items from the first result set with a <see cref="Result{T}"/>.
/// </summary>
/// <typeparam name="T">The item <see cref="Type"/>.</typeparam>
/// <param name="func">The <see cref="DatabaseRecord"/> mapping function.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param>
/// <returns>The resulting set.</returns>
public Task<Result<IEnumerable<T>>> SelectQueryWithResultAsync<T>(Func<DatabaseRecord, T> func, CancellationToken cancellationToken = default)
=> SelectQueryWithResultInternalAsync(func, nameof(SelectQueryWithResultAsync), cancellationToken);
/// <summary>
/// Selects none or more items from the first result set with a <see cref="Result{T}"/> internal.
/// </summary>
private async Task<Result<IEnumerable<T>>> SelectQueryWithResultInternalAsync<T>(Func<DatabaseRecord, T> func, string memberName, CancellationToken cancellationToken = default)
{
var coll = new List<T>();
var result = await SelectInternalAsync(coll, new DatabaseRecordMapper<T>(func), false, false, memberName, cancellationToken).ConfigureAwait(false);
return result.ThenAs(() => (IEnumerable<T>)coll);
}
/// <summary>
/// Selects none or more items from the first result set and adds to the <paramref name="collection"/>.
/// </summary>
/// <typeparam name="T">The item <see cref="Type"/>.</typeparam>
/// <typeparam name="TColl">The collection <see cref="Type"/>.</typeparam>
/// <param name="collection">The collection.</param>
/// <param name="mapper">The <see cref="IDatabaseMapper{T}"/>.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param>
public async Task SelectQueryAsync<T, TColl>(TColl collection, IDatabaseMapper<T> mapper, CancellationToken cancellationToken = default) where TColl : ICollection<T>
=> (await SelectQueryWithResultInternalAsync(collection, mapper, nameof(SelectQueryAsync), cancellationToken).ConfigureAwait(false)).ThrowOnError();
/// <summary>
/// Selects none or more items from the first result set and adds to the <paramref name="collection"/> with a <see cref="Result{T}"/>.
/// </summary>
/// <typeparam name="T">The item <see cref="Type"/>.</typeparam>
/// <typeparam name="TColl">The collection <see cref="Type"/>.</typeparam>
/// <param name="collection">The collection.</param>
/// <param name="mapper">The <see cref="IDatabaseMapper{T}"/>.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param>
public async Task<Result> SelectQueryWithResultAsync<T, TColl>(TColl collection, IDatabaseMapper<T> mapper, CancellationToken cancellationToken = default) where TColl : ICollection<T>
=> await SelectQueryWithResultInternalAsync(collection, mapper, nameof(SelectQueryWithResultAsync), cancellationToken).ConfigureAwait(false);
/// <summary>
/// Selects none or more items from the first result set and adds to the <paramref name="collection"/> with a <see cref="Result{T}"/> internal.
/// </summary>
private async Task<Result> SelectQueryWithResultInternalAsync<T, TColl>(TColl collection, IDatabaseMapper<T> mapper, string memberName, CancellationToken cancellationToken) where TColl : ICollection<T>
=> await SelectInternalAsync(collection, mapper, false, false, memberName, cancellationToken).ConfigureAwait(false);
/// <summary>
/// Selects none or more items from the first result set and adds to the <paramref name="collection"/>.
/// </summary>
/// <typeparam name="T">The item <see cref="Type"/>.</typeparam>
/// <typeparam name="TColl">The collection <see cref="Type"/>.</typeparam>
/// <param name="collection">The collection.</param>
/// <param name="func">The <see cref="DatabaseRecord"/> mapping function.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param>
public async Task SelectQueryAsync<T, TColl>(TColl collection, Func<DatabaseRecord, T> func, CancellationToken cancellationToken = default) where TColl : ICollection<T>
=> (await SelectInternalAsync(collection, new DatabaseRecordMapper<T>(func), false, false, nameof(SelectQueryAsync), cancellationToken)).ThrowOnError();
/// <summary>
/// Selects none or more items from the first result set and adds to the <paramref name="collection"/> with a <see cref="Result{T}"/>.
/// </summary>
/// <typeparam name="T">The item <see cref="Type"/>.</typeparam>
/// <typeparam name="TColl">The collection <see cref="Type"/>.</typeparam>
/// <param name="collection">The collection.</param>
/// <param name="func">The <see cref="DatabaseRecord"/> mapping function.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param>
public Task<Result> SelectQueryWithResultAsync<T, TColl>(TColl collection, Func<DatabaseRecord, T> func, CancellationToken cancellationToken = default) where TColl : ICollection<T>
=> SelectInternalAsync(collection, new DatabaseRecordMapper<T>(func), false, false, nameof(SelectQueryWithResultAsync), cancellationToken);
/// <summary>
/// Selects a single item.
/// </summary>
/// <typeparam name="T">The resultant <see cref="Type"/>.</typeparam>
/// <param name="mapper">The <see cref="IDatabaseMapper{T}"/>.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param>
/// <returns>The single item.</returns>
public async Task<T> SelectSingleAsync<T>(IDatabaseMapper<T> mapper, CancellationToken cancellationToken = default)
=> (await SelectSingleWithResultInternalAsync(mapper, nameof(SelectSingleAsync), cancellationToken).ConfigureAwait(false)).Value;
/// <summary>
/// Selects a single item with a <see cref="Result{T}"/>.
/// </summary>
/// <typeparam name="T">The resultant <see cref="Type"/>.</typeparam>
/// <param name="mapper">The <see cref="IDatabaseMapper{T}"/>.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param>
/// <returns>The single item.</returns>
public Task<Result<T>> SelectSingleWithResultAsync<T>(IDatabaseMapper<T> mapper, CancellationToken cancellationToken = default)
=> SelectSingleWithResultInternalAsync(mapper, nameof(SelectSingleWithResultAsync), cancellationToken);
/// <summary>
/// Selects a single item with a <see cref="Result{T}"/> internal.
/// </summary>
private async Task<Result<T>> SelectSingleWithResultInternalAsync<T>(IDatabaseMapper<T> mapper, string memberName, CancellationToken cancellationToken)
{
var result = await SelectSingleFirstWithResultInternalAsync(mapper, true, memberName, cancellationToken).ConfigureAwait(false);
return result.When(item => Comparer<T>.Default.Compare(item, default!) == 0, _ => Result<T>.Fail(new InvalidOperationException("SelectSingle request has not returned a row.")));
}
/// <summary>
/// Selects a single item or default.
/// </summary>
/// <typeparam name="T">The resultant <see cref="Type"/>.</typeparam>
/// <param name="mapper">The <see cref="IDatabaseMapper{T}"/>.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param>
/// <returns>The single item or default.</returns>
public async Task<T?> SelectSingleOrDefaultAsync<T>(IDatabaseMapper<T> mapper, CancellationToken cancellationToken = default)
=> await SelectSingleFirstWithResultInternalAsync(mapper, false, nameof(SelectSingleOrDefaultAsync), cancellationToken).ConfigureAwait(false);
/// <summary>
/// Selects a single item or default with a <see cref="Result{T}"/>.
/// </summary>
/// <typeparam name="T">The resultant <see cref="Type"/>.</typeparam>
/// <param name="mapper">The <see cref="IDatabaseMapper{T}"/>.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param>
/// <returns>The single item or default.</returns>
public async Task<Result<T?>> SelectSingleOrDefaultWithResultAsync<T>(IDatabaseMapper<T> mapper, CancellationToken cancellationToken = default)
=> await SelectSingleFirstWithResultInternalAsync(mapper, false, nameof(SelectSingleOrDefaultWithResultAsync), cancellationToken).ConfigureAwait(false);
/// <summary>
/// Selects first item.
/// </summary>
/// <typeparam name="T">The resultant <see cref="Type"/>.</typeparam>
/// <param name="mapper">The <see cref="IDatabaseMapper{T}"/>.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param>
/// <returns>The single item.</returns>
public async Task<T> SelectFirstAsync<T>(IDatabaseMapper<T> mapper, CancellationToken cancellationToken = default)
=> await SelectFirstWithResultInternalAsync(mapper, nameof(SelectFirstAsync), cancellationToken).ConfigureAwait(false);
/// <summary>
/// Selects first item with a <see cref="Result{T}"/>.
/// </summary>
/// <typeparam name="T">The resultant <see cref="Type"/>.</typeparam>
/// <param name="mapper">The <see cref="IDatabaseMapper{T}"/>.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param>
/// <returns>The single item.</returns>
public Task<Result<T>> SelectFirstWithResultAsync<T>(IDatabaseMapper<T> mapper, CancellationToken cancellationToken = default)
=> SelectFirstWithResultInternalAsync(mapper, nameof(SelectFirstWithResultAsync), cancellationToken);
/// <summary>
/// Selects first item with a <see cref="Result{T}"/> internal.
/// </summary>
private async Task<Result<T>> SelectFirstWithResultInternalAsync<T>(IDatabaseMapper<T> mapper, string memberName, CancellationToken cancellationToken = default)
{
var result = await SelectSingleFirstWithResultInternalAsync(mapper, false, memberName, cancellationToken).ConfigureAwait(false);
return result.When(item => Comparer<T>.Default.Compare(item, default!) == 0, _ => new InvalidOperationException("SelectFirst request has not returned a row."));
}
/// <summary>
/// Selects first item or default.
/// </summary>
/// <typeparam name="T">The resultant <see cref="Type"/>.</typeparam>
/// <param name="mapper">The <see cref="IDatabaseMapper{T}"/>.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param>
/// <returns>The single item or default.</returns>
public async Task<T?> SelectFirstOrDefaultAsync<T>(IDatabaseMapper<T> mapper, CancellationToken cancellationToken = default)
=> await SelectSingleFirstWithResultInternalAsync(mapper, false, nameof(SelectFirstOrDefaultAsync), cancellationToken).ConfigureAwait(false);
/// <summary>
/// Selects first item or default with a <see cref="Result{T}"/>.
/// </summary>
/// <typeparam name="T">The resultant <see cref="Type"/>.</typeparam>
/// <param name="mapper">The <see cref="IDatabaseMapper{T}"/>.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param>
/// <returns>The single item or default.</returns>
public async Task<Result<T?>> SelectFirstOrDefaultWithResultAsync<T>(IDatabaseMapper<T> mapper, CancellationToken cancellationToken = default)
=> await SelectSingleFirstWithResultInternalAsync(mapper, false, nameof(SelectFirstOrDefaultWithResultAsync), cancellationToken).ConfigureAwait(false);
/// <summary>
/// Select first row result only (where exists) internal.
/// </summary>
private async Task<Result<T>> SelectSingleFirstWithResultInternalAsync<T>(IDatabaseMapper<T> mapper, bool throwWhereMulti, string memberName, CancellationToken cancellationToken)
{
var coll = new List<T>();
var result = await SelectInternalAsync(coll, mapper, throwWhereMulti, true, memberName, cancellationToken).ConfigureAwait(false);
return result.ThenAs(() => coll.Count == 0 ? default! : coll[0]);
}
/// <summary>
/// Select the rows from the query internal.
/// </summary>
private async Task<Result> SelectInternalAsync<T, TColl>(TColl coll, IDatabaseMapper<T> mapper, bool throwWhereMulti, bool stopAfterOneRow, string memberName, CancellationToken cancellationToken) where TColl : ICollection<T>
{
mapper.ThrowIfNull(nameof(mapper));
return await Database.Invoker.InvokeAsync(Database, mapper, throwWhereMulti, stopAfterOneRow, async (_, mapper, throwWhereMulti, stopAfterOneRow, ct) =>
{
int i = 0;
using var cmd = await CreateDbCommandAsync(ct).ConfigureAwait(false);
using var dr = await cmd.ExecuteReaderAsync(ct).ConfigureAwait(false);
while (await dr.ReadAsync(ct).ConfigureAwait(false))
{
if (++i == 2)
{
if (throwWhereMulti)
Result.Fail(new InvalidOperationException("SelectSingle request has returned more than one row."));
if (stopAfterOneRow)
return Result.Success;
}
var val = mapper.MapFromDb(new DatabaseRecord(Database, dr));
if (val == null)
return Result.Fail(new InvalidOperationException("A null must not be returned from the mapper."));
coll.Add(val);
if (!throwWhereMulti && stopAfterOneRow)
return Result.Success;
}
return Result.Success;
}, cancellationToken, memberName).ConfigureAwait(false);
}
/// <summary>
/// Selects from the first result set using a <paramref name="func"/> to handle each <see cref="DatabaseRecord"/>.
/// </summary>
/// <param name="func">The <see cref="DatabaseRecord"/> handling function.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param>
/// <remarks>The <paramref name="func"/> returns a <see cref="bool"/> that controls whether the next <see cref="DatabaseRecord"/> should be read. A value of <c>true</c> indicates that
/// reading should continue; otherwise, <c>false</c> to stop.</remarks>
public async Task SelectAsync(Func<DatabaseRecord, bool> func, CancellationToken cancellationToken = default)
=> (await SelectInternalAsync(func, nameof(SelectAsync), cancellationToken).ConfigureAwait(false)).ThrowOnError();
/// <summary>
/// Selects from the first result set using a <paramref name="func"/> to handle each <see cref="DatabaseRecord"/> with a <see cref="Result{T}"/>.
/// </summary>
/// <param name="func">The <see cref="DatabaseRecord"/> handling function.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param>
/// <remarks>The <paramref name="func"/> returns a <see cref="bool"/> that controls whether the next <see cref="DatabaseRecord"/> should be read. A value of <c>true</c> indicates that
/// reading should continue; otherwise, <c>false</c> to stop.</remarks>
public Task<Result> SelectWithResultAsync(Func<DatabaseRecord, bool> func, CancellationToken cancellationToken = default)
=> SelectInternalAsync(func, nameof(SelectWithResultAsync), cancellationToken);
/// <summary>
/// Select the rows from the query internal.
/// </summary>
private async Task<Result> SelectInternalAsync(Func<DatabaseRecord, bool> func, string memberName, CancellationToken cancellationToken)
{
func.ThrowIfNull(nameof(func));
return await Database.Invoker.InvokeAsync(Database, func, async (_, action, ct) =>
{
using var cmd = await CreateDbCommandAsync(ct).ConfigureAwait(false);
using var dr = await cmd.ExecuteReaderAsync(ct).ConfigureAwait(false);
while (await dr.ReadAsync(ct).ConfigureAwait(false))
{
if (!action(new DatabaseRecord(Database, dr)))
break;
}
return Result.Success;
}, cancellationToken, memberName).ConfigureAwait(false);
}
}
}