forked from borisdj/EFCore.BulkExtensions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTableInfo.cs
1511 lines (1341 loc) · 73.1 KB
/
TableInfo.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 EFCore.BulkExtensions.SqlAdapters;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking.Internal;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace EFCore.BulkExtensions;
/// <summary>
/// Provides a list of information for EFCore.BulkExtensions that is used internally to know what to do with the data source received
/// </summary>
public class TableInfo
{
#pragma warning disable CS1591 // No XML comments required here.
public string? Schema { get; set; }
public string SchemaFormated => Schema != null ? $"[{Schema}]." : "";
public string? TempSchema { get; set; }
public string TempSchemaFormated => TempSchema != null ? $"[{TempSchema}]." : "";
public string? TableName { get; set; }
public string FullTableName => $"{SchemaFormated}[{TableName}]";
public Dictionary<string, string> PrimaryKeysPropertyColumnNameDict { get; set; } = null!;
public Dictionary<string, string> EntityPKPropertyColumnNameDict { get; set; } = null!;
public bool HasSinglePrimaryKey { get; set; }
public bool UpdateByPropertiesAreNullable { get; set; }
protected string TempDBPrefix => BulkConfig.UseTempDB ? "#" : "";
public string? TempTableSufix { get; set; }
public string? TempTableName { get; set; }
public string FullTempTableName => $"{TempSchemaFormated}[{TempDBPrefix}{TempTableName}]";
public string FullTempOutputTableName => $"{SchemaFormated}[{TempDBPrefix}{TempTableName}Output]";
public bool CreateOutputTable => BulkConfig.SetOutputIdentity || BulkConfig.CalculateStats;
public bool InsertToTempTable { get; set; }
public string? IdentityColumnName { get; set; }
public bool HasIdentity => IdentityColumnName != null;
public ValueConverter? IdentityColumnConverter { get; set; }
public bool HasOwnedTypes { get; set; }
public bool HasJsonTypes { get; set; }
public bool HasAbstractList { get; set; }
public bool ColumnNameContainsSquareBracket { get; set; }
public bool LoadOnlyPKColumn { get; set; }
public bool HasSpatialType { get; set; }
public bool HasTemporalColumns { get; set; }
public int NumberOfEntities { get; set; }
public BulkConfig BulkConfig { get; set; } = null!;
public Dictionary<string, string> OutputPropertyColumnNamesDict { get; set; } = new();
public Dictionary<string, string> PropertyColumnNamesDict { get; set; } = new();
public Dictionary<string, string> ColumnNamesTypesDict { get; set; } = new();
public Dictionary<string, IProperty> ColumnToPropertyDictionary { get; set; } = new();
public Dictionary<string, string> PropertyColumnNamesCompareDict { get; set; } = new();
public Dictionary<string, string> PropertyColumnNamesUpdateDict { get; set; } = new();
public Dictionary<string, FastProperty> FastPropertyDict { get; set; } = new();
public Dictionary<string, INavigation> AllNavigationsDictionary { get; private set; } = null!;
public Dictionary<string, INavigation> OwnedTypesDict { get; set; } = new();
public Dictionary<string, INavigation> OwnedRegularTypesDict { get; set; } = new();
public Dictionary<string, INavigation> OwnedJsonTypesDict { get; set; } = new();
public HashSet<string> ShadowProperties { get; set; } = new HashSet<string>();
public HashSet<string> DefaultValueProperties { get; set; } = new HashSet<string>();
public Dictionary<string, string> ConvertiblePropertyColumnDict { get; set; } = new Dictionary<string, string>();
public Dictionary<string, ValueConverter> ConvertibleColumnConverterDict { get; set; } = new Dictionary<string, ValueConverter>();
public Dictionary<string, int> DateTime2PropertiesPrecisionLessThen7Dict { get; set; } = new Dictionary<string, int>();
public static string TimeStampOutColumnType => "varbinary(8)";
public string? TimeStampPropertyName { get; set; }
public string? TimeStampColumnName { get; set; }
public string? TextValueFirstPK { get; set; }
public string SqlActionIUD => "SqlActionIUD";
protected IEnumerable<object>? EntitiesSortedReference { get; set; } // Operation Merge writes In Output table first Existing that were Updated then for new that were Inserted so this makes sure order is same in list when need to set Output
public StoreObjectIdentifier ObjectIdentifier { get; set; }
////Sqlite
//internal SqliteConnection? SqliteConnection { get; set; }
//internal SqliteTransaction? SqliteTransaction { get; set; }
////PostgreSql
//internal NpgsqlConnection? NpgsqlConnection { get; set; }
////internal NpgsqlTransaction? NpgsqlTransaction { get; set; }
////MySql
//internal MySqlConnection? MySqlConnection { get; set; }
#pragma warning restore CS1591 // No XML comments required here.
/// <summary>
/// Creates an instance of TableInfo
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="context"></param>
/// <param name="type"></param>
/// <param name="entities"></param>
/// <param name="operationType"></param>
/// <param name="bulkConfig"></param>
/// <returns></returns>
/// <exception cref="InvalidOperationException"></exception>
public static TableInfo CreateInstance<T>(DbContext context, Type? type, IEnumerable<T> entities, OperationType operationType, BulkConfig? bulkConfig)
{
var tableInfo = new TableInfo
{
NumberOfEntities = entities.Count(),
BulkConfig = bulkConfig ?? new BulkConfig() { }
};
tableInfo.BulkConfig.OperationType = operationType;
bool isExplicitTransaction = context.Database.GetDbConnection().State == ConnectionState.Open;
if (tableInfo.BulkConfig.UseTempDB == true && !isExplicitTransaction && (operationType != OperationType.Insert || tableInfo.BulkConfig.SetOutputIdentity))
{
throw new InvalidOperationException("When 'UseTempDB' is set then BulkOperation has to be inside Transaction. " +
"Otherwise destination table gets dropped too early because transaction ends before operation is finished.");
} // throws: 'Cannot access destination table'
var isDeleteOperation = operationType == OperationType.Delete;
tableInfo.LoadData(context, type, entities, isDeleteOperation);
return tableInfo;
}
#region Main
/// <summary>
/// Configures the table info based on entity data
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="context"></param>
/// <param name="type"></param>
/// <param name="entities"></param>
/// <param name="loadOnlyPKColumn"></param>
/// <exception cref="InvalidOperationException"></exception>
/// <exception cref="MultiplePropertyListSetException"></exception>
/// <exception cref="InvalidBulkConfigException"></exception>
public void LoadData<T>(DbContext context, Type? type, IEnumerable<T> entities, bool loadOnlyPKColumn)
{
LoadOnlyPKColumn = loadOnlyPKColumn;
var entityType = type is null ? null : context.Model.FindEntityType(type);
if (entityType == null)
{
type = entities.FirstOrDefault()?.GetType() ?? throw new ArgumentNullException(nameof(type));
entityType = context.Model.FindEntityType(type);
HasAbstractList = true;
}
if (entityType == null)
{
throw new InvalidOperationException($"DbContext does not contain EntitySet for Type: {type?.Name}");
}
//var relationalData = entityType.Relational(); relationalData.Schema relationalData.TableName // DEPRECATED in Core3.0
string? providerName = context.Database.ProviderName?.ToLower();
bool isSqlServer = providerName?.EndsWith(SqlType.SqlServer.ToString().ToLower()) ?? false;
bool isNpgsql = providerName?.EndsWith(SqlType.PostgreSql.ToString().ToLower()) ?? false;
bool isSqlite = providerName?.EndsWith(SqlType.Sqlite.ToString().ToLower()) ?? false;
bool isMySql = providerName?.EndsWith(SqlType.MySql.ToString().ToLower()) ?? false;
string? defaultSchema = null;
if (isSqlServer)
{
defaultSchema = "dbo";
}
else if (isNpgsql)
{
var adapter = SqlAdaptersMapping.CreateBulkOperationsAdapter();
defaultSchema = adapter.ReconfigureTableInfo(context, this);
}
string? customSchema = null;
string? customTableName = null;
if (BulkConfig.CustomDestinationTableName != null)
{
customTableName = BulkConfig.CustomDestinationTableName;
if (customTableName.Contains('.'))
{
var tableNameSplitList = customTableName.Split('.');
customSchema = tableNameSplitList[0];
customTableName = tableNameSplitList[1];
}
}
Schema = customTableName != null ? customSchema : entityType.GetSchema() ?? defaultSchema;
var entityTableName = entityType.GetTableName();
TableName = customTableName ?? entityTableName;
string? sourceSchema = null;
string? sourceTableName = null;
if (BulkConfig.CustomSourceTableName != null)
{
sourceTableName = BulkConfig.CustomSourceTableName;
if (sourceTableName.Contains('.'))
{
var tableNameSplitList = sourceTableName.Split('.');
sourceSchema = tableNameSplitList[0];
sourceTableName = tableNameSplitList[1];
}
BulkConfig.UseTempDB = false;
}
TempSchema = sourceSchema ?? (isNpgsql && BulkConfig.UseTempDB ? null : Schema);
TempTableSufix = sourceTableName != null ? "" : "Temp";
if (BulkConfig.UniqueTableNameTempDb)
{
// 8 chars of Guid as tableNameSufix to avoid same name collision with other tables
TempTableSufix += Guid.NewGuid().ToString()[..8];
// TODO Consider Hash
}
TempTableName = sourceTableName ?? $"{TableName}{TempTableSufix}";
if (entityTableName is null)
{
throw new ArgumentException("Entity does not contain a table name");
}
ObjectIdentifier = StoreObjectIdentifier.Table(entityTableName, entityType.GetSchema());
var allProperties = new List<IProperty>();
foreach (var entityProperty in entityType.GetProperties())
{
var columnName = entityProperty.GetColumnName(ObjectIdentifier);
bool isTemporalColumn = columnName is not null
&& entityProperty.IsShadowProperty()
&& entityProperty.ClrType == typeof(DateTime)
&& BulkConfig.TemporalColumns.Contains(columnName);
HasTemporalColumns = HasTemporalColumns || isTemporalColumn;
if (columnName == null || isTemporalColumn)
continue;
allProperties.Add(entityProperty);
ColumnNamesTypesDict.Add(columnName, entityProperty.GetColumnType());
ColumnToPropertyDictionary.Add(columnName, entityProperty);
if (BulkConfig.DateTime2PrecisionForceRound)
{
var columnMappings = entityProperty.GetTableColumnMappings();
var firstMapping = columnMappings.FirstOrDefault();
var columnType = firstMapping?.Column.StoreType;
if ((columnType?.StartsWith("datetime2(") ?? false) && (!columnType?.EndsWith("7)") ?? false))
{
string precisionText = columnType!.Substring(10, 1);
int precision = int.Parse(precisionText);
DateTime2PropertiesPrecisionLessThen7Dict.Add(firstMapping!.Property.Name, precision); // SqlBulkCopy does Floor instead of Round so Rounding done in memory
}
}
}
bool areSpecifiedUpdateByProperties = BulkConfig.UpdateByProperties?.Count > 0;
var primaryKeys = entityType.FindPrimaryKey()?.Properties?.ToDictionary(a => a.Name, b => b.GetColumnName(ObjectIdentifier) ?? string.Empty);
EntityPKPropertyColumnNameDict = primaryKeys ?? new Dictionary<string, string>();
if (BulkConfig.UpdateByProperties?.Any(up => !allProperties.Any(pp => pp.Name == up)) is true)
{
var wrongNames = BulkConfig.UpdateByProperties!.Where(up => !allProperties.Any(pp => pp.Name == up));
throw new ArgumentException($"""
UpdateByProperties contains property names, that doesn't exist in entity properties list.
Wrong properties: {string.Join(", ", wrongNames)}.
All properties: {string.Join(", ", allProperties)}.
""");
}
HasSinglePrimaryKey = primaryKeys?.Count == 1;
PrimaryKeysPropertyColumnNameDict = areSpecifiedUpdateByProperties ? BulkConfig.UpdateByProperties?.ToDictionary(a => a, b => allProperties.First(p => p.Name == b).GetColumnName(ObjectIdentifier) ?? string.Empty) ?? new()
: (primaryKeys ?? new Dictionary<string, string>());
// load all derived type properties
if (entityType.IsAbstract())
{
foreach (var derivedType in entityType.GetDirectlyDerivedTypes())
{
foreach (var derivedProperty in derivedType.GetProperties())
{
if (!allProperties.Contains(derivedProperty))
allProperties.Add(derivedProperty);
}
}
}
var navigations = entityType.GetNavigations();
AllNavigationsDictionary = navigations.ToDictionary(nav => nav.Name, nav => nav);
OwnedTypesDict = navigations.Where(a => a.TargetEntityType.IsOwned()).ToDictionary(a => a.Name, a => a);
HasOwnedTypes = OwnedTypesDict.Count > 0;
#if NET7_0_OR_GREATER
OwnedRegularTypesDict = navigations.Where(a => a.TargetEntityType.IsOwned() && !a.TargetEntityType.IsMappedToJson()).ToDictionary(a => a.Name, a => a);
OwnedJsonTypesDict = navigations.Where(a => a.TargetEntityType.IsMappedToJson()).ToDictionary(a => a.Name, a => a);
#else
OwnedRegularTypesDict = navigations.Where(a => a.TargetEntityType.IsOwned()).ToDictionary(a => a.Name, a => a);
OwnedJsonTypesDict = navigations.Where(a => a.TargetEntityType == null).ToDictionary(a => a.Name, a => a); // should be empty
#endif
HasJsonTypes = OwnedJsonTypesDict.Count > 0;
if (isSqlServer || isNpgsql || isMySql)
{
var strategyName = SqlAdaptersMapping.DbServer.ValueGenerationStrategy;
if (!strategyName.Contains(":Value"))
{
strategyName = strategyName.Replace("Value", ":Value"); //example 'SqlServer:ValueGenerationStrategy'
}
foreach (var property in allProperties)
{
var annotation = property.FindAnnotation(strategyName);
bool hasIdentity = false;
if (annotation != null)
{
hasIdentity = SqlAdaptersMapping.DbServer.PropertyHasIdentity(annotation);
}
if (hasIdentity)
{
IdentityColumnName = property.GetColumnName(ObjectIdentifier);
break;
}
}
}
if (isSqlite) // SQLite no ValueGenerationStrategy
{
// for HiLo on SqlServer was returning True when should be False
IdentityColumnName = allProperties.SingleOrDefault(a => a.IsPrimaryKey() &&
a.ValueGenerated == ValueGenerated.OnAdd && // ValueGenerated equals OnAdd for nonIdentity column like Guid so take only number types
(a.ClrType.Name.StartsWith("Byte") ||
a.ClrType.Name.StartsWith("SByte") ||
a.ClrType.Name.StartsWith("Int") ||
a.ClrType.Name.StartsWith("UInt") ||
(isSqlServer && a.ClrType.Name.StartsWith("Decimal")))
)?.GetColumnName(ObjectIdentifier);
}
// timestamp/row version properties are only set by the Db, the property has a [Timestamp] Attribute or is configured in FluentAPI with .IsRowVersion()
// They can be identified by the columne type "timestamp" or .IsConcurrencyToken in combination with .ValueGenerated == ValueGenerated.OnAddOrUpdate
string timestampDbTypeName = nameof(TimestampAttribute).Replace("Attribute", "").ToLower(); // = "timestamp";
IEnumerable<IProperty> timeStampProperties;
if (BulkConfig.IgnoreRowVersion)
timeStampProperties = new List<IProperty>();
else
timeStampProperties = allProperties.Where(a => a.IsConcurrencyToken && a.ValueGenerated == ValueGenerated.OnAddOrUpdate); // || a.GetColumnType() == timestampDbTypeName // removed as unnecessary and might not be correct
TimeStampColumnName = timeStampProperties.FirstOrDefault()?.GetColumnName(ObjectIdentifier); // can be only One
TimeStampPropertyName = timeStampProperties.FirstOrDefault()?.Name; // can be only One
var allPropertiesExceptTimeStamp = allProperties.Except(timeStampProperties);
var properties = allPropertiesExceptTimeStamp.Where(a => a.GetComputedColumnSql() == null);
var propertiesWithDefaultValues = allPropertiesExceptTimeStamp.Where(a =>
!a.IsShadowProperty() &&
(a.GetDefaultValueSql() != null ||
(a.GetDefaultValue() != null &&
a.ValueGenerated != ValueGenerated.Never &&
a.ClrType != typeof(Guid)) // Since .Net_6.0 in EF 'Guid' type has DefaultValue even when not explicitly defined with Annotation or FluentApi
));
foreach (var propertyWithDefaultValue in propertiesWithDefaultValues)
{
var propertyType = propertyWithDefaultValue.ClrType;
var instance = propertyType.IsValueType || propertyType.GetConstructor(Type.EmptyTypes) != null
? Activator.CreateInstance(propertyType)
: null; // when type does not have parameterless constructor, like String for example, then default value is 'null'
bool listHasAllDefaultValues = !entities.Any(a => GetPropertyUnambiguous(a?.GetType(), propertyWithDefaultValue.Name)?.GetValue(a, null)?.ToString() != instance?.ToString());
// it is not feasible to have in same list simultaneously both entities groups With and Without default values, they are omitted OnInsert only if all have default values or if it is PK (like Guid DbGenerated)
if (listHasAllDefaultValues || (PrimaryKeysPropertyColumnNameDict.ContainsKey(propertyWithDefaultValue.Name) && propertyType == typeof(Guid)))
{
DefaultValueProperties.Add(propertyWithDefaultValue.Name);
}
}
var propertiesOnCompare = allPropertiesExceptTimeStamp.Where(a => a.GetComputedColumnSql() == null);
var propertiesOnUpdate = allPropertiesExceptTimeStamp.Where(a => a.GetComputedColumnSql() == null);
// TimeStamp prop. is last column in OutputTable since it is added later with varbinary(8) type in which Output can be inserted
var outputProperties = allPropertiesExceptTimeStamp.Where(a => a.GetColumnName(ObjectIdentifier) != null).Concat(timeStampProperties);
OutputPropertyColumnNamesDict = outputProperties.ToDictionary(a => a.Name, b => b.GetColumnName(ObjectIdentifier)?.Replace("]", "]]") ?? string.Empty); // square brackets have to be escaped
if (HasTemporalColumns)
{
foreach (var temporalColumns in BulkConfig.TemporalColumns)
OutputPropertyColumnNamesDict.Add(temporalColumns, temporalColumns);
}
bool AreSpecifiedPropertiesToInclude = BulkConfig.PropertiesToInclude?.Count > 0;
bool AreSpecifiedPropertiesToExclude = BulkConfig.PropertiesToExclude?.Count > 0;
bool AreSpecifiedPropertiesToIncludeOnCompare = BulkConfig.PropertiesToIncludeOnCompare?.Count > 0;
bool AreSpecifiedPropertiesToExcludeOnCompare = BulkConfig.PropertiesToExcludeOnCompare?.Count > 0;
bool AreSpecifiedPropertiesToIncludeOnUpdate = BulkConfig.PropertiesToIncludeOnUpdate?.Count > 0;
bool AreSpecifiedPropertiesToExcludeOnUpdate = BulkConfig.PropertiesToExcludeOnUpdate?.Count > 0;
if (AreSpecifiedPropertiesToInclude)
{
if (areSpecifiedUpdateByProperties) // Adds UpdateByProperties to PropertyToInclude if they are not already explicitly listed
{
if (BulkConfig.UpdateByProperties is not null)
{
foreach (var updateByProperty in BulkConfig.UpdateByProperties)
{
if (!BulkConfig.PropertiesToInclude?.Contains(updateByProperty) ?? false)
{
BulkConfig.PropertiesToInclude?.Add(updateByProperty);
}
}
}
}
else // Adds PrimaryKeys to PropertyToInclude if they are not already explicitly listed
{
foreach (var primaryKey in PrimaryKeysPropertyColumnNameDict)
{
if (!BulkConfig.PropertiesToInclude?.Contains(primaryKey.Key) ?? false)
{
BulkConfig.PropertiesToInclude?.Add(primaryKey.Key);
}
}
}
}
foreach (var property in allProperties)
{
if (property.PropertyInfo != null) // skip Shadow Property
{
FastPropertyDict.Add(property.Name, FastProperty.GetOrCreate(property.PropertyInfo));
}
if (property.IsShadowProperty() && property.IsForeignKey())
{
// TODO: Does Shadow ForeignKey Property aways contain only one ForgeignKey?
var navigationProperty = property.GetContainingForeignKeys().FirstOrDefault()?.DependentToPrincipal?.PropertyInfo;
if (navigationProperty is not null)
{
var navigationEntityType = context.Model.FindEntityType(navigationProperty.PropertyType);
var navigationProperties = navigationEntityType?.GetProperties().Where(p => p.IsPrimaryKey()).ToList() ?? new();
foreach (var navEntityProperty in navigationProperties)
{
var fullName = navigationProperty.Name + "_" + navEntityProperty.Name;
if (!FastPropertyDict.ContainsKey(fullName) && navEntityProperty.PropertyInfo is not null)
{
FastPropertyDict.Add(fullName, FastProperty.GetOrCreate(navEntityProperty.PropertyInfo));
}
}
}
}
var converter = property.GetTypeMapping().Converter;
if (converter is not null)
{
var columnName = property.GetColumnName(ObjectIdentifier) ?? string.Empty;
ConvertiblePropertyColumnDict.Add(property.Name, columnName);
if (!ConvertibleColumnConverterDict.ContainsKey(columnName))
{
ConvertibleColumnConverterDict.Add(columnName, converter);
}
if (columnName == IdentityColumnName)
IdentityColumnConverter = converter;
}
}
UpdateByPropertiesAreNullable = properties.Any(a => PrimaryKeysPropertyColumnNameDict.ContainsKey(a.Name) && a.IsNullable);
if (AreSpecifiedPropertiesToInclude || AreSpecifiedPropertiesToExclude)
{
if (AreSpecifiedPropertiesToInclude && AreSpecifiedPropertiesToExclude)
{
throw new MultiplePropertyListSetException(nameof(BulkConfig.PropertiesToInclude), nameof(BulkConfig.PropertiesToExclude));
}
if (AreSpecifiedPropertiesToInclude)
{
properties = properties.Where(a => BulkConfig.PropertiesToInclude?.Contains(a.Name) ?? false);
ValidateSpecifiedPropertiesList(BulkConfig.PropertiesToInclude, nameof(BulkConfig.PropertiesToInclude));
}
if (AreSpecifiedPropertiesToExclude)
{
properties = properties.Where(a => !BulkConfig.PropertiesToExclude?.Contains(a.Name) ?? false);
ValidateSpecifiedPropertiesList(BulkConfig.PropertiesToExclude, nameof(BulkConfig.PropertiesToExclude));
}
}
if (AreSpecifiedPropertiesToIncludeOnCompare || AreSpecifiedPropertiesToExcludeOnCompare)
{
if (AreSpecifiedPropertiesToIncludeOnCompare && AreSpecifiedPropertiesToExcludeOnCompare)
{
throw new MultiplePropertyListSetException(nameof(BulkConfig.PropertiesToIncludeOnCompare), nameof(BulkConfig.PropertiesToExcludeOnCompare));
}
if (AreSpecifiedPropertiesToIncludeOnCompare)
{
propertiesOnCompare = propertiesOnCompare.Where(a => BulkConfig.PropertiesToIncludeOnCompare?.Contains(a.Name) ?? false);
ValidateSpecifiedPropertiesList(BulkConfig.PropertiesToIncludeOnCompare, nameof(BulkConfig.PropertiesToIncludeOnCompare));
}
if (AreSpecifiedPropertiesToExcludeOnCompare)
{
propertiesOnCompare = propertiesOnCompare.Where(a => !BulkConfig.PropertiesToExcludeOnCompare?.Contains(a.Name) ?? false);
ValidateSpecifiedPropertiesList(BulkConfig.PropertiesToExcludeOnCompare, nameof(BulkConfig.PropertiesToExcludeOnCompare));
}
}
else
{
propertiesOnCompare = properties;
}
if (AreSpecifiedPropertiesToIncludeOnUpdate || AreSpecifiedPropertiesToExcludeOnUpdate)
{
if (AreSpecifiedPropertiesToIncludeOnUpdate && AreSpecifiedPropertiesToExcludeOnUpdate)
{
throw new MultiplePropertyListSetException(nameof(BulkConfig.PropertiesToIncludeOnUpdate), nameof(BulkConfig.PropertiesToExcludeOnUpdate));
}
if (AreSpecifiedPropertiesToIncludeOnUpdate)
{
propertiesOnUpdate = propertiesOnUpdate.Where(a => BulkConfig.PropertiesToIncludeOnUpdate?.Contains(a.Name) ?? false);
ValidateSpecifiedPropertiesList(BulkConfig.PropertiesToIncludeOnUpdate, nameof(BulkConfig.PropertiesToIncludeOnUpdate));
}
if (AreSpecifiedPropertiesToExcludeOnUpdate)
{
propertiesOnUpdate = propertiesOnUpdate.Where(a => !BulkConfig.PropertiesToExcludeOnUpdate?.Contains(a.Name) ?? false);
ValidateSpecifiedPropertiesList(BulkConfig.PropertiesToExcludeOnUpdate, nameof(BulkConfig.PropertiesToExcludeOnUpdate));
}
}
else
{
propertiesOnUpdate = properties;
if (BulkConfig.UpdateByProperties != null) // to remove NonIdentity PK like Guid from SET ID = ID, ...
{
propertiesOnUpdate = propertiesOnUpdate.Where(a => !BulkConfig.UpdateByProperties.Contains(a.Name));
}
else if (primaryKeys != null)
{
propertiesOnUpdate = propertiesOnUpdate.Where(a => !primaryKeys.ContainsKey(a.Name));
}
}
PropertyColumnNamesCompareDict = propertiesOnCompare.ToDictionary(a => a.Name, b => b.GetColumnName(ObjectIdentifier)?.Replace("]", "]]") ?? string.Empty);
PropertyColumnNamesUpdateDict = propertiesOnUpdate.ToDictionary(a => a.Name, b => b.GetColumnName(ObjectIdentifier)?.Replace("]", "]]") ?? string.Empty);
if (loadOnlyPKColumn)
{
if (PrimaryKeysPropertyColumnNameDict.Count == 0)
throw new InvalidBulkConfigException("If no PrimaryKey is defined operation requres bulkConfig set with 'UpdatedByProperties'.");
PropertyColumnNamesDict = properties.Where(a => PrimaryKeysPropertyColumnNameDict.ContainsKey(a.Name)).ToDictionary(a => a.Name, b => b.GetColumnName(ObjectIdentifier)?.Replace("]", "]]") ?? string.Empty);
}
else
{
PropertyColumnNamesDict = properties.ToDictionary(a => a.Name, b => b.GetColumnName(ObjectIdentifier)?.Replace("]", "]]") ?? string.Empty);
ShadowProperties = new HashSet<string>(properties.Where(p => p.IsShadowProperty() && !p.IsForeignKey()).Select(p => p.GetColumnName(ObjectIdentifier) ?? string.Empty));
foreach (var navigation in entityType.GetNavigations().Where(a => !a.IsCollection && !a.TargetEntityType.IsOwned()))
{
if (navigation.PropertyInfo is not null)
{
FastPropertyDict.Add(navigation.Name, FastProperty.GetOrCreate(navigation.PropertyInfo));
}
}
if (HasOwnedTypes) // Support owned entity property update. TODO: Optimize
{
foreach (var navigationProperty in OwnedRegularTypesDict.Values.ToList())
{
AddOwnedType(navigationProperty);
void AddOwnedType(INavigation navigationProperty, string prefix = "")
{
// Add it to the dictionary if it doesn't exist already
OwnedRegularTypesDict.TryAdd(prefix + navigationProperty.Name, navigationProperty);
var property = navigationProperty.PropertyInfo;
FastPropertyDict.Add(prefix + property!.Name, FastProperty.GetOrCreate(property));
// If the OwnedType is mapped to the separate table, don't try merge it into its owner
if (OwnedTypeUtil.IsOwnedInSameTableAsOwner(navigationProperty) == false)
return;
prefix += $"{property.Name}_";
var ownedList = context.Model.FindEntityTypes(property.PropertyType).Where(x => x.IsInOwnershipPath(entityType)).ToList();
var ownedEntityType = ownedList.Count == 1
? ownedList[0] // IsInOwnershipPath fix for with multiple parents (issue #1149)
: context.Model.GetEntityTypes().SingleOrDefault(x => x.ClrType == property.PropertyType && x.Name.StartsWith(entityType.Name + "." + property.Name + "#"));
// fix when entity has more then one ownedType (e.g. Address HomeAddress, Address WorkAddress) or one ownedType is in multiple Entities like Audit is usually.
var ownedEntityProperties = ownedEntityType?.GetProperties().ToList() ?? [];
var ownedEntityPropertyNameColumnNameDict = new Dictionary<string, string>();
foreach (var ownedEntityProperty in ownedEntityProperties)
{
string columnName = ownedEntityProperty.GetColumnName(ObjectIdentifier) ?? string.Empty;
if (!ownedEntityProperty.IsPrimaryKey())
{
ownedEntityPropertyNameColumnNameDict.Add(ownedEntityProperty.Name, columnName);
var ownedEntityPropertyFullName = prefix + ownedEntityProperty.Name;
if (!FastPropertyDict.ContainsKey(ownedEntityPropertyFullName) && ownedEntityProperty.PropertyInfo is not null)
{
FastPropertyDict.Add(ownedEntityPropertyFullName, FastProperty.GetOrCreate(ownedEntityProperty.PropertyInfo));
}
}
var converter = ownedEntityProperty.GetValueConverter();
if (converter != null)
{
ConvertibleColumnConverterDict.Add($"{prefix}{ownedEntityProperty.Name}", converter);
}
ColumnNamesTypesDict[columnName] = ownedEntityProperty.GetColumnType();
}
foreach (var ownedProperty in property.PropertyType.GetProperties())
{
if (ownedEntityPropertyNameColumnNameDict.TryGetValue(ownedProperty.Name, out string? columnName))
{
string ownedPropertyFullName = prefix.Replace('_', '.') + ownedProperty.Name;
var ownedPropertyType = Nullable.GetUnderlyingType(ownedProperty.PropertyType) ?? ownedProperty.PropertyType;
bool doAddProperty = true;
if (AreSpecifiedPropertiesToInclude && !(BulkConfig.PropertiesToInclude?.Contains(ownedPropertyFullName) ?? false))
{
doAddProperty = false;
}
if (AreSpecifiedPropertiesToExclude && (BulkConfig.PropertiesToExclude?.Contains(ownedPropertyFullName) ?? false))
{
doAddProperty = false;
}
if (doAddProperty)
{
PropertyColumnNamesDict.Add(ownedPropertyFullName, columnName);
PropertyColumnNamesCompareDict.Add(ownedPropertyFullName, columnName);
PropertyColumnNamesUpdateDict.Add(ownedPropertyFullName, columnName);
OutputPropertyColumnNamesDict.Add(ownedPropertyFullName, columnName);
}
}
}
IEnumerable<INavigation>? ownedTypes;
#if NET6_0
ownedTypes = ownedEntityType?.GetNavigations().Where(a => a.TargetEntityType.IsOwned() && !a.TargetEntityType.IsMappedToJson());
#else
ownedTypes = ownedEntityType?.GetNavigations().Where(a => a.TargetEntityType.IsOwned() && !a.TargetEntityType.IsMappedToJson());
#endif
foreach (var ownedNavigationProperty in ownedTypes ?? [])
{
AddOwnedType(ownedNavigationProperty, prefix);
}
}
}
}
if (HasJsonTypes)
{
var jsonTypes = OwnedJsonTypesDict.Values.ToList();
foreach (var jsonProperty in jsonTypes)
{
var property = jsonProperty.PropertyInfo;
//var value = FastPropertyDict[property?.Name!].Get(jsonProperty);
//var jsonValue = System.Text.Json.JsonSerializer.Serialize(value);
//var j1 = jsonProperty.TargetEntityType.GetJsonPropertyName();
string columnName = property?.Name!;
string propertyName = property?.Name!;
bool skipColumn = (BulkConfig.PropertiesToInclude != null && !BulkConfig.PropertiesToInclude.Contains(propertyName)) ||
(BulkConfig.PropertiesToExclude != null && BulkConfig.PropertiesToExclude.Contains(propertyName));
if (!skipColumn)
{
FastPropertyDict.Add(property!.Name, FastProperty.GetOrCreate(property));
PropertyColumnNamesDict.Add(propertyName, columnName);
PropertyColumnNamesCompareDict.Add(propertyName, columnName);
PropertyColumnNamesUpdateDict.Add(propertyName, columnName);
OutputPropertyColumnNamesDict.Add(propertyName, columnName);
}
}
}
}
if (PrimaryKeysPropertyColumnNameDict.Count == 1)
{
string pkName = PrimaryKeysPropertyColumnNameDict.Keys.First();
if (entities != null && entities.Count() > 0)
{
object? instance = entities.First();
TextValueFirstPK = FastPropertyDict[pkName].Get(instance ?? "")?.ToString();
}
}
}
private static PropertyInfo? GetPropertyUnambiguous(Type? type, string name)
{
if (name == null) throw new ArgumentNullException(nameof(name));
if (type == null) return null;
while (type != null)
{
var property = type.GetProperty(name, BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance);
if (property != null)
{
return property;
}
type = type.BaseType;
}
return null;
}
/// <summary>
/// Validates the specified property list
/// </summary>
/// <param name="specifiedPropertiesList"></param>
/// <param name="specifiedPropertiesListName"></param>
/// <exception cref="InvalidOperationException"></exception>
protected void ValidateSpecifiedPropertiesList(List<string>? specifiedPropertiesList, string specifiedPropertiesListName)
{
if (specifiedPropertiesList is not null)
{
foreach (var configSpecifiedPropertyName in specifiedPropertiesList)
{
if (!FastPropertyDict.Any(a => a.Key == configSpecifiedPropertyName) &&
!configSpecifiedPropertyName.Contains('.') && // Those with dot "." skiped from validating for now since FastPropertyDict here does not contain them
!(specifiedPropertiesListName == nameof(BulkConfig.PropertiesToIncludeOnUpdate) && configSpecifiedPropertyName == "") && // In PropsToIncludeOnUpdate empty is allowed as config for skipping Update
!BulkConfig.TemporalColumns.Contains(configSpecifiedPropertyName)
)
{
throw new InvalidOperationException($"PropertyName '{configSpecifiedPropertyName}' specified in '{specifiedPropertiesListName}' not found in Properties.");
}
}
}
}
#endregion
#region SqlCommands
/// <summary>
/// Checks if the table exists
/// </summary>
/// <param name="context"></param>
/// <param name="tableInfo"></param>
/// <param name="cancellationToken"></param>
/// <param name="isAsync"></param>
/// <returns></returns>
public static async Task<bool> CheckTableExistAsync(DbContext context, TableInfo tableInfo, bool isAsync, CancellationToken cancellationToken)
{
if (isAsync)
{
await context.Database.OpenConnectionAsync(cancellationToken).ConfigureAwait(false);
}
else
{
context.Database.OpenConnection();
}
bool tableExist = false;
try
{
var sqlConnection = context.Database.GetDbConnection();
var currentTransaction = context.Database.CurrentTransaction;
using var command = sqlConnection.CreateCommand();
if (currentTransaction != null)
command.Transaction = currentTransaction.GetDbTransaction();
command.CommandText = SqlQueryBuilder.CheckTableExist(tableInfo.FullTempTableName, tableInfo.BulkConfig.UseTempDB);
if (isAsync)
{
using var reader = await command.ExecuteReaderAsync(cancellationToken).ConfigureAwait(false);
if (reader.HasRows)
{
while (await reader.ReadAsync(cancellationToken).ConfigureAwait(false))
{
tableExist = (int)reader[0] == 1;
}
}
}
else
{
using var reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
tableExist = (int)reader[0] == 1;
}
}
}
}
finally
{
if (isAsync)
{
await context.Database.CloseConnectionAsync().ConfigureAwait(false);
}
else
{
context.Database.CloseConnection();
}
}
return tableExist;
}
/// <summary>
/// Checks the IUD Stats numbers of entities
/// </summary>
/// <param name="context"></param>
/// <param name="cancellationToken"></param>
/// <param name="isAsync"></param>
/// <returns></returns>
protected async Task<int[]> GetStatsNumbersAsync(DbContext context, bool isAsync, CancellationToken cancellationToken)
{
var sqlQueryCountBase = $"SELECT COUNT(*) FROM {FullTempOutputTableName} WHERE [{SqlActionIUD}] = ";
var actionCodes = new List<string> { "I", "U", "D" }; // IUD - Inserted, Updated, Deleted
var sqlQueryCounts = new List<string>();
var sqlParamsNames = new List<string>();
var sqlParams = new List<IDbDataParameter>();
foreach (var actionCode in actionCodes)
{
sqlQueryCounts.Add(sqlQueryCountBase + $"'{actionCode}'");
var resultParameter = SqlAdaptersMapping.DbServer.QueryBuilder.CreateParameter("@result" + actionCode, null);
if (resultParameter is null)
{
throw new ArgumentException("Unable to create an instance of IDbDataParameter");
}
resultParameter.DbType = DbType.Int32;
resultParameter.Direction = ParameterDirection.Output;
sqlParams.Add(resultParameter);
sqlParamsNames.Add(resultParameter.ParameterName);
}
var sqlSetResult = $"SET {sqlParamsNames[0]} = ({sqlQueryCounts[0]}); " +
$"SET {sqlParamsNames[1]} = ({sqlQueryCounts[1]}); " +
$"SET {sqlParamsNames[2]} = ({sqlQueryCounts[2]});";
var sqlParamsArray = sqlParams.ToArray();
if (isAsync)
{
await context.Database.ExecuteSqlRawAsync(sqlSetResult, sqlParamsArray, cancellationToken).ConfigureAwait(false);
}
else
{
context.Database.ExecuteSqlRaw(sqlSetResult, sqlParamsArray);
}
var resultArray = new int[] { (int)sqlParams[0].Value!, (int)sqlParams[1].Value!, (int)sqlParams[2].Value! };
return resultArray;
}
#endregion
/// <summary>
/// Returns the unique property values
/// </summary>
/// <param name="entity"></param>
/// <param name="propertiesNames"></param>
/// <param name="fastPropertyDict"></param>
/// <returns></returns>
public static string GetUniquePropertyValues(object entity, List<string> propertiesNames, Dictionary<string, FastProperty> fastPropertyDict)
{
StringBuilder uniqueBuilder = new(1024);
string delimiter = "_"; // TODO: Consider making it Config-urable
foreach (var propertyName in propertiesNames)
{
var property = fastPropertyDict[propertyName].Get(entity);
if (property is Array propertyArray)
{
foreach (var element in propertyArray)
{
uniqueBuilder.Append(element?.ToString() ?? "null");
}
}
else
{
uniqueBuilder.Append(property?.ToString() ?? "null");
}
uniqueBuilder.Append(delimiter);
}
string result = uniqueBuilder.ToString() == "null" ? "" : uniqueBuilder.ToString();
result = result[0..^1]; // removes last delimiter
return result;
}
#region ReadProcedures
/// <summary>
/// Configures the bulk read column names for the table info
/// </summary>
/// <returns></returns>
public Dictionary<string, string> ConfigureBulkReadTableInfo()
{
InsertToTempTable = true;
var previousPropertyColumnNamesDict = PropertyColumnNamesDict;
BulkConfig.PropertiesToInclude = PrimaryKeysPropertyColumnNameDict.Select(a => a.Key).ToList();
PropertyColumnNamesDict = PropertyColumnNamesDict.Where(a => PrimaryKeysPropertyColumnNameDict.ContainsKey(a.Key)).ToDictionary(a => a.Key, a => a.Value);
return previousPropertyColumnNamesDict;
}
internal void UpdateReadEntities<T>(IEnumerable<T> entities, IList<T> existingEntities, DbContext context)
{
var propColDict = BulkConfig.LoadOnlyIncludedColumns ? PropertyColumnNamesDict : OutputPropertyColumnNamesDict;
List<string> propertyNames = propColDict.Keys.ToList();
if (HasOwnedTypes)
{
foreach (string ownedTypeName in OwnedTypesDict.Keys)
{
var ownedTypeProperties = OwnedTypesDict[ownedTypeName].ClrType.GetProperties();
foreach (var ownedTypeProperty in ownedTypeProperties)
{
propertyNames.Remove(ownedTypeName + "." + ownedTypeProperty.Name);
}
propertyNames.Add(ownedTypeName);
}
}
List<string> selectByPropertyNames = PropertyColumnNamesDict.Keys
.Where(a => PrimaryKeysPropertyColumnNameDict.ContainsKey(a)).ToList();
Dictionary<string, T> existingEntitiesDict = new();
foreach (var existingEntity in existingEntities)
{
string uniqueProperyValues = GetUniquePropertyValues(existingEntity!, selectByPropertyNames, FastPropertyDict);
existingEntitiesDict.TryAdd(uniqueProperyValues, existingEntity);
}
for (int i = 0; i < NumberOfEntities; i++)
{
T entity = entities.ElementAt(i);
string uniqueProperyValues = GetUniquePropertyValues(entity!, selectByPropertyNames, FastPropertyDict);
existingEntitiesDict.TryGetValue(uniqueProperyValues, out T? existingEntity);
bool isPostgreSql = context.Database.ProviderName?.EndsWith(SqlType.PostgreSql.ToString(), StringComparison.InvariantCultureIgnoreCase) ?? false;
if (existingEntity == null && isPostgreSql && i < existingEntities.Count && entities.Count() == existingEntities.Count) // && entities.Count == existingEntities.Count conf fix for READ. TODO change (issue 1027)
{
existingEntity = existingEntities.ElementAt(i); // TODO check if BinaryImport with COPY on Postgres preserves order
}
if (existingEntity != null)
{
foreach (var propertyName in propertyNames)
{
if (FastPropertyDict.ContainsKey(propertyName))
{
var propertyValue = FastPropertyDict[propertyName].Get(existingEntity);
FastPropertyDict[propertyName].Set(entity!, propertyValue);
}
else
{
//TODO: Shadow FK property update
}
}
}
}
}
internal void ReplaceReadEntities<T>(IEnumerable<T> entities, IList<T> existingEntities)
{
if (typeof(T) == existingEntities.FirstOrDefault()?.GetType())
{
var entitiesList = (List<T>)entities;
entitiesList.Clear();
entitiesList.AddRange(existingEntities);
}
else
{
var entitiesObjects = entities.Cast<object>().ToList();
entitiesObjects.Clear();
entitiesObjects.AddRange((IEnumerable<object>)existingEntities);
}
}
#endregion
/// <summary>
/// Sets the identity preserve order
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="tableInfo"></param>
/// <param name="entities"></param>
/// <param name="reset"></param>
public void CheckToSetIdentityForPreserveOrder<T>(TableInfo tableInfo, IEnumerable<T> entities, bool reset = false)
{
string identityPropertyName = PropertyColumnNamesDict.SingleOrDefault(a => a.Value == IdentityColumnName).Key;
bool doSetIdentityColumnsForInsertOrder = BulkConfig.PreserveInsertOrder &&
entities.Count() > 1 &&
PrimaryKeysPropertyColumnNameDict?.Count == 1 &&