forked from AmpScm/RepoDb
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDbCommandExtension.cs
More file actions
1093 lines (953 loc) · 36.8 KB
/
Copy pathDbCommandExtension.cs
File metadata and controls
1093 lines (953 loc) · 36.8 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
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.Collections;
using System.Data;
using System.Data.Common;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Reflection;
using RepoDb.Attributes.Parameter;
using RepoDb.DbSettings;
using RepoDb.Enumerations;
using RepoDb.Exceptions;
using RepoDb.Interfaces;
using RepoDb.Options;
using RepoDb.Resolvers;
namespace RepoDb.Extensions;
/// <summary>
/// Contains the extension methods for <see cref="IDbCommand"/> object.
/// </summary>
public static class DbCommandExtension
{
#region CreateParameter
/// <summary>
/// Creates a parameter for a command object.
/// </summary>
/// <param name="command">The command object instance to be used.</param>
/// <param name="name">The name of the parameter.</param>
/// <param name="value">The value of the parameter.</param>
/// <param name="dbType">The database type of the parameter.</param>
/// <returns>An instance of the newly created parameter object.</returns>
public static IDbDataParameter CreateParameter(this IDbCommand command,
string name,
object? value,
DbType? dbType) =>
CreateParameter(command, name, value, dbType, null);
/// <summary>
/// Creates a parameter for a command object.
/// </summary>
/// <param name="command">The command object instance to be used.</param>
/// <param name="name">The name of the parameter.</param>
/// <param name="value">The value of the parameter.</param>
/// <param name="dbType">The database type of the parameter.</param>
/// <param name="parameterDirection">The direction of the parameter.</param>
/// <returns>An instance of the newly created parameter object.</returns>
public static IDbDataParameter CreateParameter(this IDbCommand command,
string name,
object? value,
DbType? dbType,
ParameterDirection? parameterDirection)
{
ArgumentNullException.ThrowIfNull(command);
var parameter = command.CreateParameter();
// Set the values
parameter.ParameterName = name.AsParameter(index: 0, dbSetting: DbSettingMapper.Get(command.Connection!));
command.SetValue(parameter, value);
// The DB Type is auto set when setting the values
if (dbType is { } type)
{
// Prepare() requires an explicit assignment
parameter.DbType = type;
}
// Set the direction
if (parameterDirection is { } direction)
{
parameter.Direction = direction;
}
// Return the parameter
return parameter;
}
/// <summary>
///
/// </summary>
/// <param name="command"></param>
/// <param name="parameter"></param>
/// <param name="value"></param>
public static void SetValue(this IDbCommand command, IDbDataParameter parameter, object? value)
{
ArgumentNullException.ThrowIfNull(command);
ArgumentNullException.ThrowIfNull(parameter);
if (value is { } && DbHelperMapper.Get(command.Connection!) is BaseDbHelper dbh)
{
value = dbh.ParameterValueToDb(value, parameter);
}
parameter.Value = value ?? DBNull.Value;
}
internal static void CreateParametersFromArray(
this DbCommand command,
CommandArrayParametersText commandArrayParametersText)
{
if (commandArrayParametersText?.CommandArrayParameters?.Count is not > 0)
{
return;
}
var dbSetting = command.Connection!.GetDbSetting();
foreach (var commandArrayParameter in commandArrayParametersText.CommandArrayParameters)
{
var dbType = commandArrayParametersText.DbType;
var values = commandArrayParameter.Values.AsTypedSet();
if (values.Count == 0)
{
command.Parameters.Add(
command.CreateParameter(commandArrayParameter.ParameterName, null, dbType));
}
else if (values.Count > 5 && dbSetting.UseArrayParameterTreshold < values.Count
&& command.Connection?.GetDbHelper().CreateTableParameter(command.Connection, command.Transaction, null,
values, commandArrayParameter.ParameterName) is { } tableParameter)
{
command.Parameters.Add(tableParameter);
}
else
{
var i = 0;
foreach (var value in values)
{
var name = string.Concat(commandArrayParameter.ParameterName, i.ToString(CultureInfo.InvariantCulture));
dbType ??= value?.GetType().GetDbType();
command.Parameters.Add(
command.CreateParameter(name, value, dbType));
i++;
}
}
}
}
/// <summary>
/// Creates a parameter from object by mapping the property from the target entity type.
/// </summary>
/// <param name="command">The command object to be used.</param>
/// <param name="param">The object to be used when creating the parameters.</param>
public static void CreateParameters(this IDbCommand command,
object param) =>
CreateParameters(command, param, param?.GetType());
/// <summary>
/// Creates a parameter from object by mapping the property from the target entity type.
/// </summary>
/// <param name="command">The command object to be used.</param>
/// <param name="param">The object to be used when creating the parameters.</param>
/// <param name="entityType">The type of the data entity.</param>
public static void CreateParameters(this IDbCommand command,
object? param,
Type? entityType) =>
CreateParameters(command, param, null, entityType, null);
internal static void CreateParameters(this IDbCommand command,
object? param,
HashSet<string>? propertiesToSkip,
Type? entityType,
DbFieldCollection? dbFields = null)
{
// Check
if (param is null)
{
return;
}
// IDictionary<string, object?>
switch (param)
{
case IDictionary<string, object?> objects:
CreateParameters(command, objects, propertiesToSkip, dbFields);
break;
// QueryField
case QueryField field:
command.CreateParameters(field, propertiesToSkip, entityType, dbFields);
break;
// IEnumerable<QueryField>
case IEnumerable<QueryField> fields:
command.CreateParameters(fields, propertiesToSkip, entityType, dbFields);
break;
// QueryGroup
case QueryGroup group:
CreateParameters(command, group, propertiesToSkip, entityType, dbFields);
break;
// Other
default:
CreateParametersInternal(command, param, propertiesToSkip, entityType, dbFields);
break;
}
}
private static IDbDataParameter CreateParameter(IDbCommand command,
string name,
object? value,
int? size,
ClassProperty? classProperty,
DbField? dbField,
ParameterDirection? parameterDirection,
DbType? dbType,
Type? fallbackType)
{
if (value is IDbDataParameter parameter)
{
// If the value is already a parameter, just set the name and return it
parameter.ParameterName = name.AsParameter(index: 0, dbSetting: DbSettingMapper.Get(command.Connection!));
return parameter;
}
var valueType = TypeCache.Get(value?.GetType() ?? classProperty?.PropertyInfo.PropertyType).UnderlyingType;
if (valueType?.IsEnum == true)
{
return CreateParameterForEnum(command,
valueType,
name,
value,
size,
classProperty,
dbField,
parameterDirection,
dbType);
}
else
{
return CreateParameterForNonEnum(command,
valueType,
name,
value,
size,
classProperty,
dbField,
parameterDirection,
dbType,
fallbackType);
}
}
private static IDbDataParameter CreateParameterForNonEnum(IDbCommand command,
Type? valueType,
string name,
object? value,
int? size,
ClassProperty? classProperty,
DbField? dbField,
ParameterDirection? parameterDirection,
DbType? dbType,
Type? fallbackType)
{
bool haveDbtype = dbType is { };
// DbType
valueType ??= TypeCache.Get(dbField?.Type).UnderlyingType ?? fallbackType;
dbType ??= classProperty?.DbType ?? (dbField?.Type ?? fallbackType ?? valueType)?.GetDbType();
// Create the parameter
var parameter = command.CreateParameter(name, value, dbType, parameterDirection);
// Property Handler
InvokePropertyHandler(classProperty, parameter, ref valueType, ref value);
// Automatic Conversion
var converted = !haveDbtype && AutomaticConvert(dbField, ref valueType, ref value);
command.SetValue(parameter, value);
if (converted
&& valueType is { }
&& (TypeMapCache.Get(valueType) ?? ClientTypeToDbTypeResolver.Instance.Resolve(valueType)) is { } typeValue)
{
parameter.DbType = typeValue;
}
// Set the size
if ((size ?? dbField?.Size) is { } parameterSize)
{
parameter.Size = parameterSize;
}
// Parameter values
InvokePropertyValueAttributes(parameter, GetPropertyValueAttributes(classProperty, valueType));
// Return the parameter
return parameter;
}
private static IDbDataParameter CreateParameterForEnum(IDbCommand command,
Type? valueType,
string name,
object? value,
int? size,
ClassProperty? classProperty,
DbField? dbField,
ParameterDirection? parameterDirection,
DbType? dbType)
{
// DbType
dbType ??= IsPostgreSqlUserDefined(dbField) ? default :
classProperty?.DbType ??
valueType?.GetDbType() ??
(dbField?.Type is { } dt ? TypeMapCache.Get(dt) ?? ClientTypeToDbTypeResolver.Instance.Resolve(dt) : null) ??
(DbType?)GlobalConfiguration.Options.EnumDefaultDatabaseType;
// Create the parameter
if (dbType == DbType.String)
{
// The database needs the value as string for an operation
value = value?.ToString();
}
var parameter = command.CreateParameter(name, value, dbType, parameterDirection);
// Property handler
InvokePropertyHandler(classProperty, parameter, ref valueType, ref value);
// Set the parameter value (in case)
SetValue(command, parameter, value);
// Set the size
if ((size ?? dbField?.Size) is { } paramSize)
parameter.Size = paramSize;
// Type map attributes
InvokePropertyValueAttributes(parameter, GetPropertyValueAttributes(classProperty, valueType));
// Return the parameter
return parameter;
}
private static IDbDataParameter? CreateParameterIf(string name,
object? value)
{
if (value is IDbDataParameter parameter)
{
parameter.ParameterName = name;
return parameter;
}
return null;
}
private static void CreateParametersInternal(IDbCommand command,
object param,
HashSet<string>? propertiesToSkip,
Type? entityType,
DbFieldCollection? dbFields = null)
{
var type = param.GetType();
// Check
if (type.IsGenericType && type.GetGenericTypeDefinition() == StaticType.Dictionary)
{
throw new InvalidParameterException("The supported type of dictionary object must be of type IDictionary<string, object?>.");
}
// Variables
var entityClassProperties = entityType != null ? PropertyCache.Get(entityType) : default;
var paramClassProperties = TypeCache.Get(type).IsClassType ? PropertyCache.Get(type) : type.GetClassProperties();
// Skip
if (propertiesToSkip is not null)
{
paramClassProperties = paramClassProperties.Where(p => !propertiesToSkip.Contains(p.PropertyInfo.Name));
}
// Iterate
foreach (var paramClassProperty in paramClassProperties)
{
var entityClassProperty = (entityType == paramClassProperty.DeclaringType) ?
paramClassProperty :
entityClassProperties.GetByFieldName(paramClassProperty.FieldName);
var name = paramClassProperty
.FieldName
.AsUnquoted(command.Connection!.GetDbSetting());
var dbField = GetDbField(name, dbFields);
var value = paramClassProperty.PropertyInfo.GetValue(param);
var parameter = CreateParameterIf(name, value) ??
CreateParameter(command,
name,
value,
dbField?.Size,
entityClassProperty ?? paramClassProperty,
dbField,
null,
null,
null);
command.Parameters.Add(parameter);
}
}
private static void CreateParameters(IDbCommand command,
IDictionary<string, object?> dictionary,
HashSet<string>? propertiesToSkip,
DbFieldCollection? dbFields = null)
{
var kvps = dictionary.Where(kvp =>
propertiesToSkip?.Contains(kvp.Key) != true);
// Iterate the key value pairs
foreach (var kvp in kvps)
{
var dbField = GetDbField(kvp.Key, dbFields);
var value = kvp.Value;
ClassProperty? classProperty = null;
DbType? dbType = null;
try
{
// CommandParameter
if (kvp.Value is CommandParameter commandParameter)
{
value = commandParameter.Value;
dbField ??= GetDbField(commandParameter.Field.FieldName, dbFields);
classProperty = PropertyCache.Get(commandParameter.MappedToType, commandParameter.Field.FieldName, true);
dbType = commandParameter.DbType;
}
var parameter = CreateParameterIf(kvp.Key, value) ??
CreateParameter(command,
kvp.Key,
value,
dbField?.Size,
classProperty,
dbField,
null,
dbType,
null);
command.Parameters.Add(parameter);
}
catch (ArgumentException ex)
{
throw new ArgumentException($"While setting {kvp.Key} to {value} ({value?.GetType()})", ex);
}
}
}
internal static void CreateParameters(IDbCommand command,
QueryGroup? queryGroup,
HashSet<string>? propertiesToSkip,
Type? entityType,
DbFieldCollection? dbFields = null)
{
if (queryGroup is null)
{
return;
}
CreateParameters(command, queryGroup.GetFields(true), propertiesToSkip, entityType, dbFields);
}
internal static void CreateParameters(this IDbCommand command,
IEnumerable<QueryField>? queryFields,
HashSet<string>? propertiesToSkip,
Type? entityType,
DbFieldCollection? dbFields = null)
{
if (queryFields is null)
{
return;
}
// Filter the query fields
var filteredQueryFields = queryFields
.Where(qf => propertiesToSkip?.Contains(qf.Field.FieldName) != true);
// Iterate the filtered query fields
foreach (var queryField in filteredQueryFields)
{
if (queryField.NoParametersNeeded)
{
}
else if (queryField.Operation is Operation.In or Operation.NotIn)
{
var dbField = GetDbField(queryField.Field.FieldName, dbFields);
CreateParametersForInOperation(command, queryField, dbField);
}
else if (queryField.Operation is Operation.Between or Operation.NotBetween)
{
var dbField = GetDbField(queryField.Field.FieldName, dbFields);
CreateParametersForBetweenOperation(command, queryField, dbField);
}
else if (queryField.Operation is not Operation.IsNotNull and not Operation.IsNull)
{
CreateParameters(command, queryField, null, entityType, dbFields);
}
}
}
private static void CreateParameters(this IDbCommand command,
QueryField queryField,
HashSet<string>? propertiesToSkip,
Type? entityType,
DbFieldCollection? dbFields = null)
{
if (queryField is null)
{
return;
}
var fieldName = queryField.Field.FieldName;
// Skip
if (propertiesToSkip?.Contains(fieldName) == true)
{
return;
}
// Variables
var dbField = GetDbField(fieldName, dbFields);
var value = queryField.Parameter.Value;
var classProperty = PropertyCache.Get(entityType, queryField.Field, true);
var (direction, fallbackType, size) = queryField is DirectionalQueryField n ?
(
n.Direction,
n.Parameter.DbType.HasValue ?
DbTypeToClientTypeResolver.Instance.Resolve(n.Parameter.DbType.Value) : null,
n.Size ?? dbField?.Size
) : default;
// Create the parameter
var parameter = CreateParameterIf(queryField.Parameter.Name, value) ??
CreateParameter(command,
queryField.Parameter.Name,
value,
size,
classProperty,
dbField,
direction,
queryField.Parameter.DbType,
fallbackType);
command.Parameters.Add(parameter);
// Set the parameter
queryField.DbParameter = parameter;
}
private static void CreateParametersForInOperation(this IDbCommand command,
QueryField queryField,
DbField? dbField = null)
{
var enumerable = (System.Collections.IEnumerable?)queryField.Parameter.Value;
if (!queryField.TableParameterMode)
{
var values = (queryField.Parameter.Value as System.Collections.IEnumerable)?.AsTypedSet();
if (!(values?.Count > 0))
return;
var i = 0;
foreach (var value in values)
{
var name = string.Concat(queryField.Parameter.Name, "_In_", i.ToString(CultureInfo.InvariantCulture));
var parameter = CreateParameter(command,
name,
value,
dbField?.Size,
null,
dbField,
null,
queryField.Parameter.DbType,
null);
command.Parameters.Add(parameter);
i++;
}
var mp = QueryField.RoundUpInLength(i);
while (i < mp)
{
var name = string.Concat(queryField.Parameter.Name, "_In_", i.ToString(CultureInfo.InvariantCulture));
var parameter = CreateParameter(command,
name,
null,
dbField?.Size,
null,
dbField,
null,
queryField.Parameter.DbType,
null);
command.Parameters.Add(parameter);
i++;
}
}
else
{
var connection = command.Connection ?? throw new InvalidOperationException("The command connection cannot be null.");
var param = connection.GetDbHelper().CreateTableParameter(command.Connection!, null, null, enumerable ?? Enumerable.Empty<object>(), queryField.Parameter.Name.AsParameter(0, connection.GetDbSetting(), suffix: "_In_"));
command.Parameters.Add(param);
}
}
private static void CreateParametersForBetweenOperation(this IDbCommand command,
QueryField queryField,
DbField? dbField = null)
{
var values = (queryField?.Parameter.Value as System.Collections.IEnumerable)?.WithType<object>().ToList();
if (values?.Count == 2)
{
// Left
var leftParameter = CreateParameter(command,
string.Concat(queryField!.Parameter.Name, "_Left"),
values[0],
dbField?.Size,
null, dbField,
null,
queryField.Parameter.DbType,
null);
command.Parameters.Add(leftParameter);
// Right
var rightParameter = CreateParameter(command,
string.Concat(queryField.Parameter.Name, "_Right"),
values[1],
dbField?.Size,
null,
dbField,
null,
queryField.Parameter.DbType,
null);
command.Parameters.Add(rightParameter);
}
else
{
throw new InvalidParameterException("The values for 'Between' and 'NotBetween' operations must be 2.");
}
}
private static void InvokePropertyHandler(ClassProperty? classProperty,
IDbDataParameter parameter,
ref Type? valueType,
ref object? value)
{
var propertyHandler = classProperty?.GetPropertyHandler() ??
(valueType == null ? null : PropertyHandlerCache.Get<object>(valueType));
if (propertyHandler is not null)
{
var propertyHandlerSetMethod = Reflection.Compiler.GetPropertyHandlerInterfaceOrHandlerType(propertyHandler)?.GetMethod(nameof(IPropertyHandler<,>.Set))!;
value = propertyHandlerSetMethod
.Invoke(propertyHandler, [ value,
PropertyHandlerSetOptions.Create(parameter, classProperty!) ]);
valueType = TypeCache.Get(propertyHandlerSetMethod.ReturnType).UnderlyingType;
}
}
private static bool IsPostgreSqlUserDefined(DbField? dbField) =>
string.Equals(dbField?.DatabaseType, "USER-DEFINED", StringComparison.OrdinalIgnoreCase) &&
string.Equals(dbField?.Provider, "PGSQL", StringComparison.OrdinalIgnoreCase);
private static IEnumerable<PropertyValueAttribute>? GetPropertyValueAttributes(ClassProperty? classProperty,
Type? fallbackType) =>
classProperty?.GetPropertyValueAttributes() ?? fallbackType?.GetPropertyValueAttributes();
private static void InvokePropertyValueAttributes(IDbDataParameter parameter,
IEnumerable<PropertyValueAttribute>? attributes)
{
if (attributes?.Any() != true)
{
return;
}
// In RepoDb, the only way the parameter has '@_' is when the time you call the QueryField.IsForUpdate()
// method and it is only happening on update operations.
var isForUpdate = parameter.ParameterName.StartsWith('_') || parameter.ParameterName.StartsWith("@_", StringComparison.Ordinal);
foreach (var attribute in attributes)
{
var exclude = isForUpdate &&
(
attribute is NameAttribute ||
string.Equals(nameof(IDbDataParameter.ParameterName), attribute.PropertyName, StringComparison.OrdinalIgnoreCase)
);
if (exclude)
{
continue;
}
attribute.SetValue(parameter);
}
}
private static bool AutomaticConvert(DbField? dbField,
[NotNullWhen(true)]
ref Type? valueType,
ref object? value)
{
if (valueType != null && dbField != null && dbField.Type != null)
{
var dbFieldType = TypeCache.Get(dbField.Type).UnderlyingType;
if (dbFieldType != valueType)
{
if (value is not null)
{
value = AutomaticConvert(value, valueType, dbFieldType);
}
valueType = dbFieldType;
return true;
}
}
return false;
static object? AutomaticConvert(object? value, Type fromType, Type targetType)
{
if (fromType == null || targetType == null || fromType == targetType)
{
return value;
}
else if (targetType.IsAssignableFrom(fromType))
{
return value;
}
else if (fromType == StaticType.String && targetType == StaticType.Guid)
{
if (value is string { } str
&& Guid.TryParse(str, out var result))
{
return result;
}
return Guid.Empty;
}
else if (fromType == StaticType.Guid && targetType == StaticType.String)
{
return value?.ToString();
}
else if (fromType == StaticType.DateTimeOffset && targetType == StaticType.DateTime && value is DateTimeOffset dto)
{
return dto.DateTime;
}
else if (targetType == StaticType.DateTime && value is DateTime dt)
{
return dt;
}
else if (fromType == StaticType.DateTime && targetType == StaticType.String)
{
return ((DateTime)value!).ToString("o", CultureInfo.InvariantCulture);
}
else if (fromType == StaticType.DateTimeOffset && targetType == StaticType.String)
{
return ((DateTimeOffset)value!).ToString("o", CultureInfo.InvariantCulture);
}
#if NET
else if (fromType == StaticType.DateOnly && targetType == StaticType.DateTime)
{
return AutomaticConvertDateOnlyToDateTime(value);
}
else if (fromType == StaticType.TimeOnly && targetType == StaticType.String)
{
return ((TimeOnly)value!).ToString("o", CultureInfo.InvariantCulture);
}
else if (fromType == StaticType.DateOnly && targetType == StaticType.String)
{
return ((DateOnly)value!).ToString("d", CultureInfo.InvariantCulture);
}
#endif
else if (targetType == StaticType.String && value is IFormattable fmt)
{
return fmt.ToString(null, CultureInfo.InvariantCulture);
}
else if (targetType.IsJsonNode() && value is IDbJsonValue jv)
{
return jv.JsonNode;
}
else if (fromType == StaticType.String && targetType.ImplementsIParsable()
&& targetType.GetMethod("Parse", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, [StaticType.String, typeof(IFormatProvider)]) is { } parser)
{
return parser.Invoke(null, [value as string, CultureInfo.InvariantCulture]);
}
#if NET
else if (targetType == typeof(Half))
{
return (Half?)(float?)Convert.ChangeType(value, typeof(float), CultureInfo.InvariantCulture);
}
else if (fromType == typeof(Half))
{
return AutomaticConvert((float?)(Half?)value, typeof(float), targetType);
}
#endif
else if (value == DBNull.Value)
{
return TypeCache.Get(targetType).HasNullValue ? null : Activator.CreateInstance(targetType);
}
else if (targetType == StaticType.Object)
{
return value;
}
try
{
return Convert.ChangeType(value, targetType, CultureInfo.InvariantCulture);
}
catch (InvalidCastException)
{
// No conversion available — return the original value unchanged.
// The ADO.NET provider may handle this type natively (e.g. Npgsql
// with UseNodaTime() handles LocalDate/Instant for date/timestamptz).
return value;
}
}
}
private static DbField? GetDbField(string fieldName,
DbFieldCollection? dbFields)
{
if (dbFields is null || dbFields.IsEmpty()) return null;
if (string.IsNullOrWhiteSpace(fieldName))
{
return null;
}
var index = fieldName.IndexOf("_In_", StringComparison.OrdinalIgnoreCase);
if (index >= 0)
{
fieldName = fieldName.Substring(0, index);
}
return dbFields.GetByFieldName(fieldName);
}
private static object? AutomaticConvertStringToGuid(object? value)
{
if (value is string { } str)
{
value = Guid.Parse(str);
}
return value;
}
internal static int ExecuteNonQueryInternal(this DbCommand command, ITrace? trace, string? traceKey)
{
// Before Execution
var traceResult = Tracer
.InvokeBeforeExecution(traceKey, trace, command);
// Silent cancellation
if (traceResult?.CancellableTraceLog?.IsCancelled == true)
{
return default;
}
var result = command.ExecuteNonQuery();
// After Execution
Tracer
.InvokeAfterExecution(traceResult, trace, result);
return result;
}
internal static async ValueTask<int> ExecuteNonQueryInternalAsync(this DbCommand command, ITrace? trace, string? traceKey, CancellationToken cancellationToken = default)
{
// Before Execution
var traceResult = await Tracer
.InvokeBeforeExecutionAsync(traceKey, trace, command, cancellationToken).ConfigureAwait(false);
// Silent cancellation
if (traceResult?.CancellableTraceLog?.IsCancelled == true)
{
return default;
}
var result = await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false);
// After Execution
await Tracer
.InvokeAfterExecutionAsync(traceResult, trace, result, cancellationToken).ConfigureAwait(false);
return result;
}
internal static object? ExecuteScalarInternal(this DbCommand command, ITrace? trace, string? traceKey)
{
// Before Execution
var traceResult = Tracer
.InvokeBeforeExecution(traceKey, trace, command);
// Silent cancellation
if (traceResult?.CancellableTraceLog?.IsCancelled == true)
{
return default;
}
var result = command.ExecuteScalar();
// After Execution
Tracer
.InvokeAfterExecution(traceResult, trace, result);
return result;
}
internal static async ValueTask<object?> ExecuteScalarInternalAsync(this DbCommand command, ITrace? trace, string? traceKey, CancellationToken cancellationToken = default)
{
// Before Execution
var traceResult = await Tracer
.InvokeBeforeExecutionAsync(traceKey, trace, command, cancellationToken).ConfigureAwait(false);
// Silent cancellation
if (traceResult?.CancellableTraceLog?.IsCancelled == true)
{
return default;
}
var result = await command.ExecuteScalarAsync(cancellationToken).ConfigureAwait(false);
// After Execution
await Tracer
.InvokeAfterExecutionAsync(traceResult, trace, result, cancellationToken).ConfigureAwait(false);
return result;
}
internal static DbDataReader ExecuteReaderInternal(this DbCommand command, ITrace? trace, string? traceKey)
{
// Before Execution
var traceResult = Tracer
.InvokeBeforeExecution(traceKey, trace, command);
// Silent cancellation
if (traceResult?.CancellableTraceLog?.IsCancelled == true)
{
return new EmptyReader();
}
var result = command.ExecuteReader();
// After Execution
Tracer
.InvokeAfterExecution(traceResult, trace, result);
return result;
}
internal static async ValueTask<DbDataReader> ExecuteReaderInternalAsync(this DbCommand command, ITrace? trace, string? traceKey, CancellationToken cancellationToken = default)
{
// Before Execution
var traceResult = await Tracer
.InvokeBeforeExecutionAsync(traceKey, trace, command, cancellationToken).ConfigureAwait(false);
// Silent cancellation
if (traceResult?.CancellableTraceLog?.IsCancelled == true)
{
return new EmptyReader();
}
var result = await command.ExecuteReaderAsync(cancellationToken).ConfigureAwait(false);
// After Execution
await Tracer
.InvokeAfterExecutionAsync(traceResult, trace, result, cancellationToken).ConfigureAwait(false);
return result;
}
#if NET
private static DateTime? AutomaticConvertDateOnlyToDateTime(object? value) =>
value is DateOnly dateOnly ? dateOnly.ToDateTime(default(TimeOnly)) : null;
#endif
#endregion
private sealed class EmptyReader : DbDataReader
{
public override object this[int ordinal] => null!;
public override object this[string name] => null!;
public override int Depth => 0;
public override int FieldCount => 0;
public override bool HasRows => false;
public override bool IsClosed => true;
public override int RecordsAffected => 0;
public override bool GetBoolean(int ordinal)
{
throw new NotImplementedException();
}
public override byte GetByte(int ordinal)
{
throw new NotImplementedException();
}
public override long GetBytes(int ordinal, long dataOffset, byte[]? buffer, int bufferOffset, int length)
{
throw new NotImplementedException();
}
public override char GetChar(int ordinal)
{
throw new NotImplementedException();
}
public override long GetChars(int ordinal, long dataOffset, char[]? buffer, int bufferOffset, int length)
{
throw new NotImplementedException();
}
public override string GetDataTypeName(int ordinal)
{
throw new NotImplementedException();
}