/
CommandInfo.cs
1861 lines (1557 loc) · 64.4 KB
/
CommandInfo.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
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Dynamic;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
#if NETFRAMEWORK || NETCOREAPP3_1 || NETSTANDARD2_0 || NETSTANDARD2_1
using System.Text;
#endif
using JetBrains.Annotations;
namespace LinqToDB.Data
{
using Async;
using Common;
using Common.Internal;
using Common.Internal.Cache;
using Expressions;
using Extensions;
using Linq;
using Mapping;
using Reflection;
using Tools;
/// <summary>
/// Provides database connection command abstraction.
/// </summary>
[PublicAPI]
public class CommandInfo
{
/// <summary>
/// Instance of database connection, associated with command.
/// </summary>
public DataConnection DataConnection;
/// <summary>
/// Command text.
/// </summary>
public string CommandText;
/// <summary>
/// Command parameters.
/// </summary>
public DataParameter[]? Parameters;
/// <summary>
/// Type of command. See <see cref="System.Data.CommandType"/> for all supported types.
/// Default value: <see cref="CommandType.Text"/>.
/// </summary>
public CommandType CommandType = CommandType.Text;
/// <summary>
/// Command behavior flags. See <see cref="System.Data.CommandBehavior"/> for more details.
/// Default value: <see cref="CommandBehavior.Default"/>.
/// </summary>
public CommandBehavior CommandBehavior;
#region Init
/// <summary>
/// Creates database command instance using provided database connection and command text.
/// </summary>
/// <param name="dataConnection">Database connection instance.</param>
/// <param name="commandText">Command text.</param>
public CommandInfo(DataConnection dataConnection, string commandText)
{
DataConnection = dataConnection;
CommandText = commandText;
}
/// <summary>
/// Creates database command instance using provided database connection, command text and parameters.
/// </summary>
/// <param name="dataConnection">Database connection instance.</param>
/// <param name="commandText">Command text.</param>
/// <param name="parameters">List of command parameters.</param>
public CommandInfo(DataConnection dataConnection, string commandText, params DataParameter[] parameters)
{
DataConnection = dataConnection;
CommandText = commandText;
Parameters = parameters;
}
/// <summary>
/// Creates database command instance using provided database connection, command text and single parameter.
/// </summary>
/// <param name="dataConnection">Database connection instance.</param>
/// <param name="commandText">Command text.</param>
/// <param name="parameter">Command parameter.</param>
public CommandInfo(DataConnection dataConnection, string commandText, DataParameter parameter)
{
DataConnection = dataConnection;
CommandText = commandText;
Parameters = new[] { parameter };
}
/// <summary>
/// Creates database command instance using provided database connection, command text and parameters.
/// </summary>
/// <param name="dataConnection">Database connection instance.</param>
/// <param name="commandText">Command text.</param>
/// <param name="parameters">Command parameters. Supported values:
/// <para> - <c>null</c> for command without parameters;</para>
/// <para> - single <see cref="DataParameter"/> instance;</para>
/// <para> - array of <see cref="DataParameter"/> parameters;</para>
/// <para> - mapping class entity.</para>
/// <para>Last case will convert all mapped columns to <see cref="DataParameter"/> instances using following logic:</para>
/// <para> - if column is of <see cref="DataParameter"/> type, column value will be used. If parameter name (<see cref="DataParameter.Name"/>) is not set, column name will be used;</para>
/// <para> - if converter from column type to <see cref="DataParameter"/> is defined in mapping schema, it will be used to create parameter with colum name passed to converter;</para>
/// <para> - otherwise column value will be converted to <see cref="DataParameter"/> using column name as parameter name and column value will be converted to parameter value using conversion, defined by mapping schema.</para>
/// </param>
public CommandInfo(DataConnection dataConnection, string commandText, object? parameters)
{
DataConnection = dataConnection;
CommandText = commandText;
Parameters = GetDataParameters(dataConnection, parameters);
}
private CommandBehavior GetCommandBehavior()
{
return DataConnection.GetCommandBehavior(CommandBehavior);
}
#endregion
#region Query with object reader
/// <summary>
/// Executes command using <see cref="CommandType.StoredProcedure"/> command type and returns results as collection of values, mapped using provided mapping function.
/// </summary>
/// <typeparam name="T">Result record type.</typeparam>
/// <param name="objectReader">Record mapping function from data reader.</param>
/// <returns>Returns collection of query result records.</returns>
public IEnumerable<T> QueryProc<T>(Func<DbDataReader,T> objectReader)
{
CommandType = CommandType.StoredProcedure;
return Query(objectReader);
}
/// <summary>
/// Executes command asynchronously using <see cref="CommandType.StoredProcedure"/> command type and returns results as collection of values, mapped using provided mapping function.
/// </summary>
/// <typeparam name="T">Result record type.</typeparam>
/// <param name="objectReader">Record mapping function from data reader.</param>
/// <param name="cancellationToken">Asynchronous operation cancellation token.</param>
/// <returns>Returns collection of query result records.</returns>
public Task<IEnumerable<T>> QueryProcAsync<T>(Func<DbDataReader, T> objectReader, CancellationToken cancellationToken = default)
{
CommandType = CommandType.StoredProcedure;
return QueryAsync(objectReader, cancellationToken);
}
/// <summary>
/// Executes command and returns results as collection of values, mapped using provided mapping function.
/// </summary>
/// <typeparam name="T">Result record type.</typeparam>
/// <param name="objectReader">Record mapping function from data reader.</param>
/// <returns>Returns collection of query result records.</returns>
public IEnumerable<T> Query<T>(Func<DbDataReader, T> objectReader)
{
InitCommand();
return ReadEnumerator(
DataConnection.ExecuteDataReader(GetCommandBehavior()),
objectReader,
DataConnection.DataProvider.ExecuteScope(DataConnection));
}
/// <summary>
/// Executes command asynchronously and returns results as collection of values, mapped using provided mapping function.
/// </summary>
/// <typeparam name="T">Result record type.</typeparam>
/// <param name="objectReader">Record mapping function from data reader.</param>
/// <param name="cancellationToken">Asynchronous operation cancellation token.</param>
/// <returns>Returns collection of query result records.</returns>
public async Task<IEnumerable<T>> QueryAsync<T>(Func<DbDataReader, T> objectReader, CancellationToken cancellationToken = default)
{
InitCommand();
return ReadEnumerator(
await DataConnection.ExecuteDataReaderAsync(GetCommandBehavior(), cancellationToken).ConfigureAwait(Configuration.ContinueOnCapturedContext),
objectReader,
DataConnection.DataProvider.ExecuteScope(DataConnection));
}
IEnumerable<T> ReadEnumerator<T>(DataReaderWrapper rd, Func<DbDataReader, T> objectReader, IExecutionScope? scope)
{
using (scope)
using (rd)
{
while (rd.DataReader!.Read())
yield return objectReader(rd.DataReader!);
SetRebindParameters(rd);
}
}
#endregion
#region Query with object reader async
/// <summary>
/// Executes command asynchronously and returns list of values, mapped using provided mapping function.
/// </summary>
/// <typeparam name="T">Result record type.</typeparam>
/// <param name="objectReader">Record mapping function from data reader.</param>
/// <param name="cancellationToken">Asynchronous operation cancellation token.</param>
/// <returns>Returns task with list of query result records.</returns>
public async Task<List<T>> QueryToListAsync<T>(Func<DbDataReader, T> objectReader, CancellationToken cancellationToken = default)
{
var list = new List<T>();
await QueryForEachAsync(objectReader, list.Add, cancellationToken).ConfigureAwait(Configuration.ContinueOnCapturedContext);
return list;
}
/// <summary>
/// Executes command asynchronously and returns array of values, mapped using provided mapping function.
/// </summary>
/// <typeparam name="T">Result record type.</typeparam>
/// <param name="objectReader">Record mapping function from data reader.</param>
/// <param name="cancellationToken">Asynchronous operation cancellation token.</param>
/// <returns>Returns task with array of query result records.</returns>
public async Task<T[]> QueryToArrayAsync<T>(Func<DbDataReader, T> objectReader, CancellationToken cancellationToken = default)
{
var list = new List<T>();
await QueryForEachAsync(objectReader, list.Add, cancellationToken).ConfigureAwait(Configuration.ContinueOnCapturedContext);
return list.ToArray();
}
/// <summary>
/// Executes command asynchronously and apply provided action to each record, mapped using provided mapping function.
/// </summary>
/// <typeparam name="T">Result record type.</typeparam>
/// <param name="objectReader">Record mapping function from data reader.</param>
/// <param name="action">Action, applied to each result record.</param>
/// <param name="cancellationToken">Asynchronous operation cancellation token.</param>
/// <returns>Returns task.</returns>
public async Task QueryForEachAsync<T>(Func<DbDataReader, T> objectReader, Action<T> action, CancellationToken cancellationToken = default)
{
await DataConnection.EnsureConnectionAsync(cancellationToken).ConfigureAwait(Configuration.ContinueOnCapturedContext);
InitCommand();
#if !NATIVE_ASYNC
using (DataConnection.DataProvider.ExecuteScope(DataConnection))
#else
await using ((DataConnection.DataProvider.ExecuteScope(DataConnection) ?? EmptyIAsyncDisposable.Instance).ConfigureAwait(Configuration.ContinueOnCapturedContext))
#endif
{
#if NETSTANDARD2_1PLUS
var rd = await DataConnection.ExecuteDataReaderAsync(GetCommandBehavior(), cancellationToken).ConfigureAwait(Configuration.ContinueOnCapturedContext);
await using (rd.ConfigureAwait(Configuration.ContinueOnCapturedContext))
#else
using (var rd = await DataConnection.ExecuteDataReaderAsync(GetCommandBehavior(), cancellationToken).ConfigureAwait(Configuration.ContinueOnCapturedContext))
#endif
while (await rd.DataReader!.ReadAsync(cancellationToken).ConfigureAwait(Configuration.ContinueOnCapturedContext))
action(objectReader(rd.DataReader!));
}
}
#endregion
#region Query
/// <summary>
/// Executes command using <see cref="CommandType.StoredProcedure"/> command type and returns results as collection of values of specified type.
/// </summary>
/// <typeparam name="T">Result record type.</typeparam>
/// <returns>Returns collection of query result records.</returns>
public IEnumerable<T> QueryProc<T>()
{
CommandType = CommandType.StoredProcedure;
return Query<T>();
}
/// <summary>
/// Executes command asynchronously using <see cref="CommandType.StoredProcedure"/> command type and returns results as collection of values of specified type.
/// </summary>
/// <typeparam name="T">Result record type.</typeparam>
/// <param name="cancellationToken">Asynchronous operation cancellation token.</param>
/// <returns>Returns collection of query result records.</returns>
public Task<IEnumerable<T>> QueryProcAsync<T>(CancellationToken cancellationToken = default)
{
CommandType = CommandType.StoredProcedure;
return QueryAsync<T>(cancellationToken);
}
/// <summary>
/// Executes command and returns results as collection of values of specified type.
/// </summary>
/// <typeparam name="T">Result record type.</typeparam>
/// <returns>Returns collection of query result records.</returns>
public IEnumerable<T> Query<T>()
{
InitCommand();
return ReadEnumerator<T>(
DataConnection.ExecuteDataReader(GetCommandBehavior()),
DataConnection.DataProvider.ExecuteScope(DataConnection));
}
/// <summary>
/// Executes command asynchronously and returns results as collection of values of specified type.
/// </summary>
/// <typeparam name="T">Result record type.</typeparam>
/// <param name="cancellationToken">Asynchronous operation cancellation token.</param>
/// <returns>Returns collection of query result records.</returns>
public async Task<IEnumerable<T>> QueryAsync<T>(CancellationToken cancellationToken = default)
{
InitCommand();
return ReadEnumerator<T>(
await DataConnection.ExecuteDataReaderAsync(GetCommandBehavior(), cancellationToken).ConfigureAwait(Configuration.ContinueOnCapturedContext),
DataConnection.DataProvider.ExecuteScope(DataConnection));
}
static bool IsDynamicType(Type type)
{
return typeof(object) == type || typeof(ExpandoObject) == type;
}
IEnumerable<T> ReadEnumerator<T>(DataReaderWrapper rd, IExecutionScope? scope, bool disposeReader = true)
{
var startedOn = DateTime.UtcNow;
var stopwatch = Stopwatch.StartNew();
var rowCount = 0;
using (scope)
try
{
if (rd.DataReader!.Read())
{
var additionalKey = GetCommandAdditionalKey(rd.DataReader!, typeof(T));
DbDataReader reader;
if (((IDataContext)DataConnection).UnwrapDataObjectInterceptor is {} interceptor)
{
using (ActivityService.Start(ActivityID.UnwrapDataObjectInterceptorUnwrapDataReader))
reader = interceptor.UnwrapDataReader(DataConnection, rd.DataReader!);
}
else
{
reader = rd.DataReader!;
}
var objectReader = GetObjectReader<T>(DataConnection, reader, CommandText, additionalKey);
var isFaulted = false;
do
{
T result;
try
{
result = objectReader(reader);
}
catch (InvalidCastException)
{
if (isFaulted)
throw;
isFaulted = true;
objectReader = GetObjectReader2<T>(DataConnection, reader, CommandText, additionalKey);
result = objectReader(reader);
}
rowCount++;
yield return result;
} while (rd.DataReader!.Read());
}
SetRebindParameters(rd);
}
finally
{
stopwatch.Stop();
if (disposeReader)
{
rd.Dispose();
if (DataConnection.TraceSwitchConnection.TraceInfo)
{
DataConnection.OnTraceConnection(new TraceInfo(DataConnection, TraceInfoStep.Completed, TraceOperation.DisposeQuery, isAsync: false)
{
TraceLevel = TraceLevel.Info,
Command = rd.Command,
StartTime = startedOn,
ExecutionTime = stopwatch.Elapsed,
RecordsAffected = rowCount
});
}
}
}
}
#endregion
#region Query async
/// <summary>
/// Executes command asynchronously and returns list of values.
/// </summary>
/// <typeparam name="T">Result record type.</typeparam>
/// <param name="cancellationToken">Asynchronous operation cancellation token.</param>
/// <returns>Returns task with list of query result records.</returns>
public async Task<List<T>> QueryToListAsync<T>(CancellationToken cancellationToken = default)
{
var list = new List<T>();
await QueryForEachAsync<T>(list.Add, cancellationToken).ConfigureAwait(Configuration.ContinueOnCapturedContext);
return list;
}
/// <summary>
/// Executes command asynchronously and returns array of values.
/// </summary>
/// <typeparam name="T">Result record type.</typeparam>
/// <param name="cancellationToken">Asynchronous operation cancellation token.</param>
/// <returns>Returns task with array of query result records.</returns>
public async Task<T[]> QueryToArrayAsync<T>(CancellationToken cancellationToken = default)
{
var list = new List<T>();
await QueryForEachAsync<T>(list.Add, cancellationToken).ConfigureAwait(Configuration.ContinueOnCapturedContext);
return list.ToArray();
}
/// <summary>
/// Executes command asynchronously and apply provided action to each record.
/// </summary>
/// <typeparam name="T">Result record type.</typeparam>
/// <param name="action">Action, applied to each result record.</param>
/// <param name="cancellationToken">Asynchronous operation cancellation token.</param>
/// <returns>Returns task.</returns>
public async Task QueryForEachAsync<T>(Action<T> action, CancellationToken cancellationToken = default)
{
await DataConnection.EnsureConnectionAsync(cancellationToken).ConfigureAwait(Configuration.ContinueOnCapturedContext);
InitCommand();
#if !NATIVE_ASYNC
using (DataConnection.DataProvider.ExecuteScope(DataConnection))
#else
await using ((DataConnection.DataProvider.ExecuteScope(DataConnection) ?? EmptyIAsyncDisposable.Instance).ConfigureAwait(Configuration.ContinueOnCapturedContext))
#endif
{
#if NETSTANDARD2_1PLUS
var rd = await DataConnection.ExecuteDataReaderAsync(GetCommandBehavior(), cancellationToken).ConfigureAwait(Configuration.ContinueOnCapturedContext);
await using (rd.ConfigureAwait(Configuration.ContinueOnCapturedContext))
#else
using (var rd = await DataConnection.ExecuteDataReaderAsync(GetCommandBehavior(), cancellationToken).ConfigureAwait(Configuration.ContinueOnCapturedContext))
#endif
{
if (await rd.DataReader!.ReadAsync(cancellationToken).ConfigureAwait(Configuration.ContinueOnCapturedContext))
{
var additionalKey = GetCommandAdditionalKey(rd.DataReader!, typeof(T));
DbDataReader reader;
if (((IDataContext)DataConnection).UnwrapDataObjectInterceptor is {} interceptor)
{
using (ActivityService.Start(ActivityID.UnwrapDataObjectInterceptorUnwrapDataReader))
reader = interceptor.UnwrapDataReader(DataConnection, rd.DataReader!);
}
else
{
reader = rd.DataReader!;
}
var objectReader = GetObjectReader<T>(DataConnection, reader, CommandText, additionalKey);
var isFaulted = false;
do
{
T result;
try
{
result = objectReader(reader);
}
catch (InvalidCastException)
{
if (isFaulted)
throw;
isFaulted = true;
objectReader = GetObjectReader2<T>(DataConnection, reader, CommandText, additionalKey);
result = objectReader(reader);
}
action(result);
} while (await rd.DataReader!.ReadAsync(cancellationToken).ConfigureAwait(Configuration.ContinueOnCapturedContext));
}
}
}
}
#endregion
#region Query with template
/// <summary>
/// Executes command and returns results as collection of values of specified type.
/// </summary>
/// <typeparam name="T">Result record type.</typeparam>
/// <param name="template">This value used only for <typeparamref name="T"/> parameter type inference, which makes this method usable with anonymous types.</param>
/// <returns>Returns collection of query result records.</returns>
public IEnumerable<T> Query<T>(T template)
{
return Query<T>();
}
/// <summary>
/// Executes command using <see cref="CommandType.StoredProcedure"/> command type and returns results as collection of values of specified type.
/// </summary>
/// <typeparam name="T">Result record type.</typeparam>
/// <param name="template">This value used only for <typeparamref name="T"/> parameter type inference, which makes this method usable with anonymous types.</param>
/// <returns>Returns collection of query result records.</returns>
public IEnumerable<T> QueryProc<T>(T template)
{
return QueryProc<T>();
}
/// <summary>
/// Executes command asynchronously using <see cref="CommandType.StoredProcedure"/> command type and returns results as collection of values of specified type.
/// </summary>
/// <typeparam name="T">Result record type.</typeparam>
/// <param name="template">This value used only for <typeparamref name="T"/> parameter type inference, which makes this method usable with anonymous types.</param>
/// <param name="cancellationToken">Asynchronous operation cancellation token.</param>
/// <returns>Returns collection of query result records.</returns>
public Task<IEnumerable<T>> QueryProcAsync<T>(T template, CancellationToken cancellationToken = default)
{
return QueryProcAsync<T>(cancellationToken);
}
#endregion
#region Query with multiple result sets
/// <summary>
/// Executes command using <see cref="CommandType.StoredProcedure"/> command type and returns a result containing multiple result sets.
/// Saves result values for output and reference parameters to corresponding <see cref="DataParameter"/> object.
/// </summary>
/// <typeparam name="T">Result set type.</typeparam>
/// <returns>Returns result.</returns>
public T QueryProcMultiple<T>()
where T : class
{
CommandType = CommandType.StoredProcedure;
return QueryMultiple<T>();
}
/// <summary>
/// Executes command asynchronously using <see cref="CommandType.StoredProcedure"/> command type and returns a result containing multiple result sets.
/// </summary>
/// <param name="cancellationToken">Asynchronous operation cancellation token.</param>
/// <typeparam name="T">Result set type.</typeparam>
/// <returns>
/// A task that represents the asynchronous operation.
/// The task result contains object with multiply result sets.
/// </returns>
public Task<T> QueryProcMultipleAsync<T>(CancellationToken cancellationToken = default)
where T : class
{
CommandType = CommandType.StoredProcedure;
return QueryMultipleAsync<T>(cancellationToken);
}
/// <summary>
/// Executes command and returns a result containing multiple result sets.
/// </summary>
/// <typeparam name="T">Result set type.</typeparam>
/// <returns>Returns result.</returns>
public T QueryMultiple<T>()
where T : class
{
InitCommand();
T result;
using (DataConnection.DataProvider.ExecuteScope(DataConnection))
using (var rd = DataConnection.ExecuteDataReader(GetCommandBehavior()))
{
result = ReadMultipleResultSets<T>(rd);
SetRebindParameters(rd);
}
return result;
}
/// <summary>
/// Executes command asynchronously and returns a result containing multiple result sets.
/// Saves result values for output and reference parameters to corresponding <see cref="DataParameter"/> object.
/// </summary>
/// <typeparam name="T">Result set type.</typeparam>
/// <param name="cancellationToken">Asynchronous operation cancellation token.</param>
/// <returns>
/// A task that represents the asynchronous operation.
/// The task result contains object with multiply result sets.
/// </returns>
public async Task<T> QueryMultipleAsync<T>(CancellationToken cancellationToken = default)
where T : class
{
await DataConnection.EnsureConnectionAsync(cancellationToken).ConfigureAwait(Configuration.ContinueOnCapturedContext);
InitCommand();
T result;
#if !NATIVE_ASYNC
using (DataConnection.DataProvider.ExecuteScope(DataConnection))
#else
await using ((DataConnection.DataProvider.ExecuteScope(DataConnection) ?? EmptyIAsyncDisposable.Instance).ConfigureAwait(Configuration.ContinueOnCapturedContext))
#endif
{
#if NETSTANDARD2_1PLUS
var rd = await DataConnection.ExecuteDataReaderAsync(GetCommandBehavior(), cancellationToken).ConfigureAwait(Configuration.ContinueOnCapturedContext);
await using (rd.ConfigureAwait(Configuration.ContinueOnCapturedContext))
#else
using (var rd = await DataConnection.ExecuteDataReaderAsync(GetCommandBehavior(), cancellationToken).ConfigureAwait(Configuration.ContinueOnCapturedContext))
#endif
{
result = await ReadMultipleResultSetsAsync<T>(rd.DataReader!, cancellationToken).ConfigureAwait(Configuration.ContinueOnCapturedContext);
SetRebindParameters(rd);
}
}
return result;
}
static Dictionary<int, MemberAccessor> GetMultipleQueryIndexMap<T>(TypeAccessor<T> typeAccessor)
{
var indexMap = new Dictionary<int, MemberAccessor>();
// Use attribute labels if any exist.
foreach (var m in typeAccessor.Members)
{
if (!m.HasGetter)
continue;
var attr = m.MemberInfo.GetAttribute<ResultSetIndexAttribute>();
if (attr != null)
indexMap.Add(attr.Index, m);
}
if (indexMap.Count == 0)
{
// Use ordering of properties according to reflection.
var i = 0;
foreach (var m in typeAccessor.Members)
{
if (m.HasGetter)
{
indexMap[i] = m;
i++;
}
}
}
return indexMap;
}
static readonly MethodInfo _readAsArrayMethodInfo =
MemberHelper.MethodOf<CommandInfo>(ci => ci.ReadAsArray<int>(null!)).GetGenericMethodDefinition();
static readonly MethodInfo _readAsListMethodInfo =
MemberHelper.MethodOf<CommandInfo>(ci => ci.ReadAsList<int>(null!)).GetGenericMethodDefinition();
static readonly MethodInfo _readSingletMethodInfo =
MemberHelper.MethodOf<CommandInfo>(ci => ci.ReadSingle<int>(null!)).GetGenericMethodDefinition();
T[] ReadAsArray<T>(DataReaderWrapper rd)
{
return ReadEnumerator<T>(rd, null, false).ToArray();
}
List<T> ReadAsList<T>(DataReaderWrapper rd)
{
return ReadEnumerator<T>(rd, null, false).ToList();
}
T? ReadSingle<T>(DataReaderWrapper rd)
{
return ReadEnumerator<T>(rd, null, false).FirstOrDefault();
}
T ReadMultipleResultSets<T>(DataReaderWrapper rd)
where T : class
{
var typeAccessor = TypeAccessor.GetAccessor<T>();
var indexMap = GetMultipleQueryIndexMap(typeAccessor);
var resultIndex = 0;
var result = typeAccessor.Create();
do
{
// Only process the field if we're reading it into a property.
if (indexMap.TryGetValue(resultIndex, out var member))
{
MethodInfo valueMethodInfo;
Type elementType;
if (member.Type.IsArray)
{
valueMethodInfo = _readAsArrayMethodInfo;
elementType = member.Type.GetItemType()!;
}
else if (member.Type.IsGenericEnumerableType())
{
valueMethodInfo = _readAsListMethodInfo;
elementType = member.Type.GetGenericArguments()[0];
}
else
{
valueMethodInfo = _readSingletMethodInfo;
elementType = member.Type;
}
var genericMethod = valueMethodInfo.MakeGenericMethod(elementType);
var value = genericMethod.Invoke(this, new object[] { rd });
member.SetValue(result, value);
}
resultIndex++;
} while (rd.DataReader!.NextResult());
return result;
}
static readonly MethodInfo _readAsArrayAsyncMethodInfo =
MemberHelper.MethodOf<CommandInfo>(ci => ci.ReadAsArrayAsync<int>(null!, default)).GetGenericMethodDefinition();
static readonly MethodInfo _readAsListAsyncMethodInfo =
MemberHelper.MethodOf<CommandInfo>(ci => ci.ReadAsListAsync<int>(null!, default)).GetGenericMethodDefinition();
static readonly MethodInfo _readSingletAsyncMethodInfo =
MemberHelper.MethodOf<CommandInfo>(ci => ci.ReadSingleAsync<int>(null!, default)).GetGenericMethodDefinition();
sealed class ReaderAsyncEnumerable<T> : IAsyncEnumerable<T>
{
readonly CommandInfo _commandInfo;
readonly DbDataReader _rd;
public ReaderAsyncEnumerable(CommandInfo commandInfo, DbDataReader rd)
{
_commandInfo = commandInfo;
_rd = rd;
}
public IAsyncEnumerator<T> GetAsyncEnumerator(CancellationToken cancellationToken)
{
return new ReaderAsyncEnumerator<T>(_commandInfo, _rd, cancellationToken);
}
}
sealed class ReaderAsyncEnumerator<T> : IAsyncEnumerator<T>
{
readonly CommandInfo _commandInfo;
readonly DbDataReader _rd;
readonly string? _additionalKey;
Func<DbDataReader, T> _objectReader;
bool _isFaulted;
bool _isFinished;
CancellationToken _cancellationToken;
public ReaderAsyncEnumerator(CommandInfo commandInfo, DbDataReader rd, CancellationToken cancellationToken)
{
_commandInfo = commandInfo;
_rd = rd;
_additionalKey = commandInfo.GetCommandAdditionalKey(rd, typeof(T));
_objectReader = GetObjectReader<T>(commandInfo.DataConnection, rd, commandInfo.CommandText, _additionalKey);
_isFaulted = false;
_cancellationToken = cancellationToken;
}
public void Dispose()
{
}
#if !NATIVE_ASYNC
public Task DisposeAsync() => TaskEx.CompletedTask;
#else
public ValueTask DisposeAsync() => default;
#endif
public T Current { get; private set; } = default!;
#if !NATIVE_ASYNC
public async Task<bool> MoveNextAsync()
#else
public async ValueTask<bool> MoveNextAsync()
#endif
{
if (_isFinished)
return false;
if (!await _rd.ReadAsync(_cancellationToken).ConfigureAwait(Configuration.ContinueOnCapturedContext))
{
_isFinished = true;
return false;
}
try
{
Current = _objectReader(_rd);
}
catch (InvalidCastException)
{
if (_isFaulted)
throw;
_isFaulted = true;
_objectReader = GetObjectReader2<T>(_commandInfo.DataConnection, _rd,
_commandInfo.CommandText,
_additionalKey);
Current = _objectReader(_rd);
}
return true;
}
}
Task<T[]> ReadAsArrayAsync<T>(DbDataReader rd, CancellationToken cancellationToken)
{
return new ReaderAsyncEnumerable<T>(this, rd).ToArrayAsync(cancellationToken: cancellationToken);
}
Task<List<T>> ReadAsListAsync<T>(DbDataReader rd, CancellationToken cancellationToken)
{
return new ReaderAsyncEnumerable<T>(this, rd).ToListAsync(cancellationToken: cancellationToken);
}
Task<T> ReadSingleAsync<T>(DbDataReader rd, CancellationToken cancellationToken)
{
return new ReaderAsyncEnumerable<T>(this, rd).FirstOrDefaultAsync(cancellationToken: cancellationToken);
}
async Task<T> ReadMultipleResultSetsAsync<T>(DbDataReader rd, CancellationToken cancellationToken)
where T : class
{
var typeAccessor = TypeAccessor.GetAccessor<T>();
var indexMap = GetMultipleQueryIndexMap(typeAccessor);
var resultIndex = 0;
var result = typeAccessor.Create();
do
{
// Only process the field if we're reading it into a property.
if (indexMap.TryGetValue(resultIndex, out var member))
{
MethodInfo valueMethodInfo;
Type elementType;
if (member.Type.IsArray)
{
valueMethodInfo = _readAsArrayAsyncMethodInfo;
elementType = member.Type.GetItemType()!;
}
else if (member.Type.IsGenericEnumerableType())
{
valueMethodInfo = _readAsListAsyncMethodInfo;
elementType = member.Type.GetGenericArguments()[0];
}
else
{
valueMethodInfo = _readSingletAsyncMethodInfo;
elementType = member.Type;
}
var genericMethod = valueMethodInfo.MakeGenericMethod(elementType);
var task = (Task)genericMethod.Invoke(this, new object[] { rd, cancellationToken })!;
await task.ConfigureAwait(Configuration.ContinueOnCapturedContext);
// Task<T>.Result
var value = ((dynamic)task).Result;
member.SetValue(result, value);
}
resultIndex++;
} while (await rd.NextResultAsync(cancellationToken).ConfigureAwait(Configuration.ContinueOnCapturedContext));
return result;
}
#endregion
#region Execute
/// <summary>
/// Executes command using <see cref="CommandType.StoredProcedure"/> command type and returns number of affected records.
/// Saves result values for output and reference parameters to corresponding <see cref="DataParameter"/> object.
/// </summary>
/// <returns>Number of records, affected by command execution.</returns>
public int ExecuteProc()
{
CommandType = CommandType.StoredProcedure;
return Execute();
}
/// <summary>
/// Executes command and returns number of affected records.
/// </summary>
/// <returns>Number of records, affected by command execution.</returns>
public int Execute()
{
using var m = ActivityService.Start(ActivityID.CommandInfoExecute);
var startedOn = DateTime.UtcNow;
var stopwatch = Stopwatch.StartNew();
InitCommand();
var commandResult = DataConnection.ExecuteNonQuery();
stopwatch.Stop();
if (DataConnection.TraceSwitchConnection.TraceInfo)
{
DataConnection.OnTraceConnection(new TraceInfo(DataConnection, TraceInfoStep.Completed, TraceOperation.DisposeQuery, isAsync: false)
{
TraceLevel = TraceLevel.Info,
Command = DataConnection.CurrentCommand,
StartTime = startedOn,
ExecutionTime = stopwatch.Elapsed,
RecordsAffected = commandResult,
});
}
if (DataConnection.CurrentCommand?.Parameters.Count > 0 && Parameters?.Length > 0)
RebindParameters(DataConnection.CurrentCommand);
return commandResult;
}
/// <summary>
/// Executes command using custom execute method and returns number of affected records.
/// </summary>
/// <param name="customExecute">Custom execute method.</param>
/// <returns>Number of records, affected by command execution.</returns>
internal int ExecuteCustom(Func<DbCommand, int> customExecute)
{
using var m = ActivityService.Start(ActivityID.CommandInfoExecuteCustom);
var startedOn = DateTime.UtcNow;
var stopwatch = Stopwatch.StartNew();
InitCommand();
var commandResult = DataConnection.ExecuteNonQueryCustom(customExecute);
stopwatch.Stop();
if (DataConnection.TraceSwitchConnection.TraceInfo)
{
DataConnection.OnTraceConnection(new TraceInfo(DataConnection, TraceInfoStep.Completed, TraceOperation.DisposeQuery, isAsync: false)
{
TraceLevel = TraceLevel.Info,
Command = DataConnection.CurrentCommand,
StartTime = startedOn,
ExecutionTime = stopwatch.Elapsed,
RecordsAffected = commandResult,
});
}
if (DataConnection.CurrentCommand?.Parameters.Count > 0 && Parameters?.Length > 0)
RebindParameters(DataConnection.CurrentCommand);
return commandResult;
}
#endregion
#region Execute async
/// <summary>
/// Executes command using <see cref="CommandType.StoredProcedure"/> command type asynchronously and returns number of affected records.
/// Saves result values for output and reference parameters to corresponding <see cref="DataParameter"/> object.
/// </summary>
/// <param name="cancellationToken">Asynchronous operation cancellation token.</param>
/// <returns>Task with number of records, affected by command execution.</returns>
public Task<int> ExecuteProcAsync(CancellationToken cancellationToken = default)
{
CommandType = CommandType.StoredProcedure;
return ExecuteAsync(cancellationToken);
}
/// <summary>
/// Executes command asynchronously and returns number of affected records.
/// </summary>
/// <param name="cancellationToken">Asynchronous operation cancellation token.</param>
/// <returns>Task with number of records, affected by command execution.</returns>
public async Task<int> ExecuteAsync(CancellationToken cancellationToken = default)
{