-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSqlHelper.cs
3996 lines (3579 loc) · 177 KB
/
SqlHelper.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
#region Related components
using System;
using System.Linq;
using System.Xml;
using System.Data;
using System.Data.Common;
using System.Transactions;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Configuration;
using System.Reflection;
using System.Diagnostics;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Microsoft.Extensions.Logging;
using net.vieapps.Components.Caching;
using net.vieapps.Components.Utility;
#endregion
namespace net.vieapps.Components.Repository
{
/// <summary>
/// Collection of methods for working with SQL database (support Microsoft SQL Server, Oracle RDBMS, MySQL, and PostgreSQL)
/// </summary>
public static class SqlHelper
{
#region Provider Factory
/// <summary>
/// Gets the database provider factory for working with SQL database
/// </summary>
/// <param name="dataSource">The object that presents related information of a data source in SQL database</param>
/// <returns></returns>
public static DbProviderFactory GetProviderFactory(this DataSource dataSource)
{
var providerName = dataSource?.ProviderName;
if (string.IsNullOrWhiteSpace(providerName))
{
var connectionStringSettings = dataSource != null && dataSource.Mode.Equals(RepositoryMode.SQL)
? RepositoryMediator.GetConnectionStringSettings(dataSource)
: null;
providerName = connectionStringSettings?.ProviderName ?? "System.Data.SqlClient";
}
return DbProvider.GetFactory(providerName);
}
static bool IsSQLServer(this DbProviderFactory dbProviderFactory)
=> (dbProviderFactory?.GetTypeName(true) ?? "").Equals("SqlClientFactory");
static bool IsOracleRDBMS(this DbProviderFactory dbProviderFactory)
=> (dbProviderFactory?.GetTypeName(true) ?? "").Equals("OracleClientFactory");
static bool IsMySQL(this DbProviderFactory dbProviderFactory)
=> (dbProviderFactory?.GetTypeName(true) ?? "").Equals("MySqlConnectorFactory");
static bool IsPostgreSQL(this DbProviderFactory dbProviderFactory)
=> (dbProviderFactory?.GetTypeName(true) ?? "").Equals("NpgsqlFactory");
static bool IsGotRowNumber(this DbProviderFactory dbProviderFactory)
=> dbProviderFactory != null && (dbProviderFactory.IsSQLServer() || dbProviderFactory.IsOracleRDBMS());
static bool IsGotLimitOffset(this DbProviderFactory dbProviderFactory)
=> dbProviderFactory != null && (dbProviderFactory.IsMySQL() || dbProviderFactory.IsPostgreSQL());
static string GetOffsetStatement(this DbProviderFactory dbProviderFactory, int pageSize, int pageNumber = 1)
=> dbProviderFactory != null && dbProviderFactory.IsGotLimitOffset()
? $" LIMIT {pageSize} OFFSET {(pageNumber - 1) * pageSize}"
: "";
static string GetName(this DbProviderFactory dbProviderFactory)
=> dbProviderFactory == null
? "Unknown"
: dbProviderFactory.IsSQLServer()
? "SQLServer"
: dbProviderFactory.IsMySQL()
? "MySQL"
: dbProviderFactory.IsPostgreSQL()
? "PostgreSQL"
: dbProviderFactory.IsOracleRDBMS()
? "OralceRDBMS"
: $"Unknown [{dbProviderFactory.GetType()}]";
#endregion
#region Connection
/// <summary>
/// Creates the connection for working with SQL database
/// </summary>
/// <param name="dbProviderFactory">The object that presents information of a database provider factory</param>
/// <param name="dataSource">The object that presents related information of a data source in SQL database</param>
/// <param name="openWhenItsCreated">true to open the connection when its created</param>
/// <returns></returns>
public static DbConnection CreateConnection(this DbProviderFactory dbProviderFactory, DataSource dataSource, bool openWhenItsCreated = true)
{
var connection = dbProviderFactory.CreateConnection();
connection.ConnectionString = dataSource != null && dataSource.Mode.Equals(RepositoryMode.SQL)
? dataSource.GetConnectionString()?.Replace(StringComparison.OrdinalIgnoreCase, "{database}", dataSource.DatabaseName).Replace(StringComparison.OrdinalIgnoreCase, "{DatabaseName}", dataSource.DatabaseName)
: null;
if (openWhenItsCreated)
{
if (string.IsNullOrWhiteSpace(connection.ConnectionString))
throw new ArgumentException("The connection string is invalid");
connection.Open();
}
return connection;
}
/// <summary>
/// Creates the connection for working with SQL database
/// </summary>
/// <param name="dbProviderFactory">The object that presents information of a database provider factory</param>
/// <param name="dataSource">The object that presents related information of a data source in SQL database</param>
/// <param name="cancellationToken">The cancellation token</param>
/// <param name="openWhenItsCreated">true to open the connection when its created</param>
/// <returns></returns>
public static async Task<DbConnection> CreateConnectionAsync(this DbProviderFactory dbProviderFactory, DataSource dataSource, CancellationToken cancellationToken = default, bool openWhenItsCreated = true)
{
var connection = dbProviderFactory.CreateConnection(dataSource, false);
if (openWhenItsCreated)
{
if (string.IsNullOrWhiteSpace(connection.ConnectionString))
throw new ArgumentException("The connection string is invalid");
await connection.OpenAsync(cancellationToken).ConfigureAwait(false);
}
return connection;
}
/// <summary>
/// Gets the connection of SQL database of a specified data-source
/// </summary>
/// <param name="dataSource">The object that presents related information of a data source of SQL database</param>
/// <returns></returns>
public static DbConnection GetConnection(this DataSource dataSource)
=> dataSource?.GetProviderFactory().CreateConnection(dataSource, false);
/// <summary>
/// Creates new transaction for working with SQL database
/// </summary>
/// <returns></returns>
public static TransactionScope CreateTransaction()
=> new TransactionScope(TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Enabled);
#endregion
#region Command
internal static DbCommand CreateCommand(this DbConnection connection, string commandText, List<DbParameter> commandParameters = null)
{
var command = connection.CreateCommand();
command.CommandText = commandText;
commandParameters?.ForEach(parameter => command.Parameters.Add(parameter));
return command;
}
internal static DbCommand CreateCommand(this DbConnection connection, Tuple<string, List<DbParameter>> info)
=> info != null && !string.IsNullOrWhiteSpace(info.Item1)
? connection.CreateCommand(info.Item1, info.Item2)
: null;
internal static string GetInfo(this DbCommand command, bool addInfo = true)
{
var parameters = new List<DbParameter>();
if (command.Parameters != null)
foreach (DbParameter parameter in command.Parameters)
parameters.Add(parameter);
var statement = command.CommandText ?? "";
parameters.ForEach(parameter =>
{
var pattern = "{0}";
var value = parameter.Value?.ToString() ?? "NULL";
if (parameter.DbType.Equals(DbType.String) || parameter.DbType.Equals(DbType.StringFixedLength)
|| parameter.DbType.Equals(DbType.AnsiString) || parameter.DbType.Equals(DbType.AnsiStringFixedLength) || parameter.DbType.Equals(DbType.DateTime))
{
pattern = "'{0}'";
value = value.Replace(StringComparison.OrdinalIgnoreCase, "'", "''");
}
statement = statement.Replace(StringComparison.OrdinalIgnoreCase, parameter.ParameterName, string.Format(pattern, value));
});
return (addInfo ? $"SQL Info: {command.Connection.Database} [{command.Connection.GetType()}]" + "\r\n" : "")
+ "- Command Text: " + (command.CommandText ?? "") + "\r\n"
+ (parameters.Count < 1 ? "" : "- Command Parameters: \r\n\t+ " + parameters.Select(parameter => $"{parameter.ParameterName} ({parameter.DbType}) => [{parameter.Value ?? "(null)"}]").ToString("\r\n\t+ ") + "\r\n")
+ "- Command Statement: " + statement;
}
#endregion
#region DbTypes
internal static Dictionary<Type, DbType> DbTypes { get; } = new Dictionary<Type, DbType>
{
{ typeof(string), DbType.String },
{ typeof(char), DbType.StringFixedLength },
{ typeof(char?), DbType.StringFixedLength },
{ typeof(byte), DbType.Byte },
{ typeof(byte?), DbType.Byte },
{ typeof(sbyte), DbType.SByte },
{ typeof(sbyte?), DbType.SByte },
{ typeof(short), DbType.Int16 },
{ typeof(short?), DbType.Int16 },
{ typeof(ushort), DbType.UInt16 },
{ typeof(ushort?), DbType.UInt16 },
{ typeof(int), DbType.Int32 },
{ typeof(int?), DbType.Int32 },
{ typeof(uint), DbType.UInt32 },
{ typeof(uint?), DbType.UInt32 },
{ typeof(long), DbType.Int64 },
{ typeof(long?), DbType.Int64 },
{ typeof(ulong), DbType.UInt64 },
{ typeof(ulong?), DbType.UInt64 },
{ typeof(float), DbType.Single },
{ typeof(float?), DbType.Single },
{ typeof(double), DbType.Double },
{ typeof(double?), DbType.Double },
{ typeof(decimal), DbType.Decimal },
{ typeof(decimal?), DbType.Decimal },
{ typeof(bool), DbType.Boolean },
{ typeof(bool?), DbType.Boolean },
{ typeof(byte[]), DbType.Binary },
{ typeof(Guid), DbType.Guid },
{ typeof(Guid?), DbType.Guid },
{ typeof(DateTime), DbType.DateTime },
{ typeof(DateTime?), DbType.DateTime },
{ typeof(DateTimeOffset), DbType.DateTimeOffset },
{ typeof(DateTimeOffset?), DbType.DateTimeOffset }
};
/// <summary>
/// Gets the database type
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public static DbType GetDbType(this Type type)
=> SqlHelper.DbTypes[type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>)) ? Nullable.GetUnderlyingType(type) : type];
/// <summary>
/// Gets the database type
/// </summary>
/// <param name="attribute"></param>
/// <returns></returns>
public static DbType GetDbType(this AttributeInfo attribute)
=> (attribute.Type.IsStringType() && (attribute.MaxLength.Equals(32) || attribute.Name.EndsWith("ID"))) || attribute.IsStoredAsString()
? DbType.AnsiStringFixedLength
: attribute.IsStoredAsJson()
? DbType.String
: attribute.Type.IsEnum
? attribute.IsStringEnum()
? DbType.String
: DbType.Int32
: attribute.Type.GetDbType();
/// <summary>
/// Gets the database type
/// </summary>
/// <param name="attribute"></param>
/// <returns></returns>
public static DbType GetDbType(this ExtendedPropertyDefinition attribute)
=> attribute.Type.Equals(typeof(DateTime))
? DbType.AnsiString
: attribute.Type.GetDbType();
internal static Dictionary<Type, Dictionary<string, string>> DbTypeStrings { get; } = new Dictionary<Type, Dictionary<string, string>>
{
{
typeof(string),
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "SQLServer", "NVARCHAR{0}" },
{ "Default", "VARCHAR{0}" }
}
},
{
typeof(char),
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "Default", "CHAR{0}" }
}
},
{
typeof(char?),
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "SQLServer", "NTEXT" },
{ "Default", "TEXT" }
}
},
{
typeof(byte),
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "PostgreSQL", "SMALLINT" },
{ "Default", "TINYINT" }
}
},
{
typeof(sbyte),
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "PostgreSQL", "SMALLINT" },
{ "MySQL", "TINYINT UNSIGNED" },
{ "Default", "TINYINT" }
}
},
{
typeof(short),
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "Default", "SMALLINT" }
}
},
{
typeof(ushort),
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "Default", "SMALLINT" }
}
},
{
typeof(int),
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "Default", "INT" }
}
},
{
typeof(uint),
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "Default", "INT" },
}
},
{
typeof(long),
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "Default", "BIGINT" }
}
},
{
typeof(ulong),
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "Default", "BIGINT" }
}
},
{
typeof(float),
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "SQLServer", "FLOAT(24)" },
{ "PostgreSQL", "REAL" },
{ "Default", "FLOAT" }
}
},
{
typeof(double),
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "SQLServer", "FLOAT(53)" },
{ "PostgreSQL", "DOUBLE PRECISION" },
{ "Default", "DOUBLE" }
}
},
{
typeof(decimal),
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "SQLServer", "DECIMAL(19,5)" },
{ "Default", "NUMERIC(19,5)" }
}
},
{
typeof(bool),
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "SQLServer", "BIT" },
{ "MySQL", "TINYINT(1)" },
{ "Default", "BOOLEAN" }
}
},
{
typeof(DateTime),
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "PostgreSQL", "TIMESTAMP" },
{ "Default", "DATETIME" }
}
}
};
internal static string GetDbTypeString(this AttributeInfo attribute, DbProviderFactory dbProviderFactory)
=> attribute.Type.IsStringType() && attribute.Name.EndsWith("ID") && (attribute.MaxLength.Equals(0) || attribute.MaxLength.Equals(32))
? typeof(string).GetDbTypeString(dbProviderFactory, 32, true, false)
: attribute.IsStoredAsString()
? typeof(string).GetDbTypeString(dbProviderFactory, attribute.IsStoredAsDateOnlyString() ? 10 : 19, true, false)
: (attribute.IsCLOB != null && attribute.IsCLOB.Value) || attribute.IsStoredAsJson()
? typeof(string).GetDbTypeString(dbProviderFactory, 0, false, true)
: attribute.Type.IsEnum
? attribute.IsStringEnum()
? typeof(string).GetDbTypeString(dbProviderFactory, 50, false, false)
: typeof(int).GetDbTypeString(dbProviderFactory, 0, false, false)
: attribute.Type.GetDbTypeString(dbProviderFactory, attribute.MaxLength != null ? attribute.MaxLength.Value : 0);
internal static string GetDbTypeString(this Type type, DbProviderFactory dbProviderFactory, int precision = 0, bool asFixedLength = false, bool asCLOB = false)
=> type == null || dbProviderFactory == null
? ""
: type.GetDbTypeString(dbProviderFactory.GetName(), precision, asFixedLength, asCLOB);
internal static string GetDbTypeString(this Type type, string dbProviderFactoryName, int precision = 0, bool asFixedLength = false, bool asCLOB = false)
{
type = !type.Equals(typeof(string))
? type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>))
? Nullable.GetUnderlyingType(type)
: type
: asFixedLength
? typeof(char)
: asCLOB
? typeof(char?)
: type;
precision = precision < 1 && type.Equals(typeof(string))
? 4000
: precision;
var dbTypeString = "";
var dbTypeStrings = !string.IsNullOrWhiteSpace(dbProviderFactoryName) && SqlHelper.DbTypeStrings.ContainsKey(type)
? SqlHelper.DbTypeStrings[type]
: null;
if (dbTypeStrings != null)
{
if (!dbTypeStrings.TryGetValue(dbProviderFactoryName, out dbTypeString))
if (!dbTypeStrings.TryGetValue("Default", out dbTypeString))
dbTypeString = "";
}
return dbTypeString.IndexOf("{0}") > 0 && precision > 0
? string.Format(dbTypeString, $"({precision})")
: dbTypeString;
}
#endregion
#region Parameter
/// <summary>
/// Creates a parameter
/// </summary>
/// <param name="dbProviderFactory"></param>
/// <param name="name"></param>
/// <param name="dbType"></param>
/// <param name="value"></param>
/// <returns></returns>
public static DbParameter CreateParameter(this DbProviderFactory dbProviderFactory, string name, DbType dbType, object value)
{
var parameter = dbProviderFactory.CreateParameter();
parameter.ParameterName = (!name.IsStartsWith("@") ? "@" : "") + name;
parameter.DbType = dbType;
parameter.Value = value ?? DBNull.Value;
return parameter;
}
internal static DbParameter CreateParameter(this DbProviderFactory dbProviderFactory, KeyValuePair<string, object> info)
=> dbProviderFactory.CreateParameter(info.Key, info.Key.EndsWith("ID") || info.Key.EndsWith("Id") ? DbType.AnsiStringFixedLength : info.Value.GetType().GetDbType(), info.Value);
internal static DbParameter CreateParameter(this DbProviderFactory dbProviderFactory, AttributeInfo attribute, object value)
=> dbProviderFactory.CreateParameter(attribute.Name, attribute.GetDbType(), attribute.IsStoredAsJson()
? value == null
? ""
: value.ToJson().ToString(Newtonsoft.Json.Formatting.None)
: attribute.IsStoredAsString()
? value == null
? ""
: ((DateTime)value).ToDTString(false, attribute.IsStoredAsDateTimeString())
: value);
internal static DbParameter CreateParameter(this DbProviderFactory dbProviderFactory, ExtendedPropertyDefinition attribute, object value)
=> dbProviderFactory.CreateParameter(attribute.Name, attribute.GetDbType(), attribute.Type.Equals(typeof(DateTime))
? value == null
? ""
: ((DateTime)value).ToDTString()
: value);
#endregion
#region Data Adapter
internal static DbDataAdapter CreateDataAdapter(this DbProviderFactory dbProviderFactory, DbCommand command)
{
var dataAdapter = dbProviderFactory.CreateDataAdapter();
dataAdapter.SelectCommand = command;
return dataAdapter;
}
#endregion
#region Copy (DataReader/DataRow)
/// <summary>
/// Sets the value of an attribute
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="object"></param>
/// <param name="name"></param>
/// <param name="value"></param>
/// <param name="standardAttributes"></param>
/// <param name="extendedAttributes"></param>
/// <param name="changedNotifier"></param>
/// <param name="whenSetAttributeValueGotError"></param>
public static void SetAttributeValue<T>(this T @object, string name, object value, Dictionary<string, AttributeInfo> standardAttributes, Dictionary<string, ExtendedPropertyDefinition> extendedAttributes, IPropertyChangedNotifier changedNotifier = null, Action<T, string, object, Exception> whenSetAttributeValueGotError = null) where T : class
{
try
{
value = value == DBNull.Value ? null : value;
if (standardAttributes != null && standardAttributes.TryGetValue(name, out var standardAttribute))
{
if (value is string @string)
{
if (standardAttribute.IsDateTimeType() && standardAttribute.IsStoredAsString())
value = DateTime.Parse(@string);
else if (standardAttribute.IsStoredAsJson())
try
{
value = new JsonSerializer().Deserialize(new JTokenReader(JToken.Parse(@string)), standardAttribute.Type);
}
catch
{
value = null;
}
else if (standardAttribute.IsEnum())
value = standardAttribute.IsStringEnum()
? @string.ToEnum(standardAttribute.Type)
: value.CastAs<int>().ToEnum(standardAttribute.Type);
else if (standardAttribute.IsGenericListOrHashSet())
value = @string != null
? standardAttribute.IsGenericList()
? @string.ToList() as object
: @string.ToHashSet()
: value;
else if (standardAttribute.IsStringType() && string.IsNullOrWhiteSpace(@string) && !standardAttribute.NotNull)
value = null;
}
else if (value != null && standardAttribute.IsEnum())
value = value.CastAs<int>().ToEnum(standardAttribute.Type);
@object.SetAttributeValue(standardAttribute, value, value != null);
changedNotifier?.NotifyPropertyChanged(name);
}
else if (extendedAttributes != null && extendedAttributes.TryGetValue(name, out var extendedAttribute))
{
if (value != null && extendedAttribute.Type.IsDateTimeType())
value = value is DateTime datetime
? datetime
: DateTime.Parse(value.ToString());
(@object as IBusinessEntity).ExtendedProperties[extendedAttribute.Name] = value?.CastAs(extendedAttribute.Type);
changedNotifier?.NotifyPropertyChanged(name);
}
}
catch (Exception ex)
{
if (whenSetAttributeValueGotError != null)
whenSetAttributeValueGotError(@object, name, value, ex);
else
throw new RepositoryOperationException($"Cannot set the value of an attribute => {ex.Message} [{@object.GetType()}#{@object.GetEntityID()} :: {name} => {value}]", ex);
}
}
/// <summary>
/// Copies data from data-reader into this object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="object"></param>
/// <param name="dataReader"></param>
/// <param name="standardAttributes"></param>
/// <param name="extendedAttributes"></param>
/// <param name="whenSetAttributeValueGotError"></param>
/// <returns></returns>
public static T Copy<T>(this T @object, DbDataReader dataReader, Dictionary<string, AttributeInfo> standardAttributes, Dictionary<string, ExtendedPropertyDefinition> extendedAttributes, Action<T, string, object, Exception> whenSetAttributeValueGotError = null) where T : class
{
@object = @object ?? ObjectService.CreateInstance<T>();
if (@object is IBusinessEntity businessEntity && businessEntity.ExtendedProperties == null && extendedAttributes != null)
businessEntity.ExtendedProperties = new Dictionary<string, object>();
var changedNotifier = @object is IPropertyChangedNotifier
? @object as IPropertyChangedNotifier
: null;
for (var index = 0; index < dataReader.FieldCount; index++)
@object.SetAttributeValue(dataReader.GetName(index), dataReader[index], standardAttributes, extendedAttributes, changedNotifier, whenSetAttributeValueGotError);
return @object;
}
/// <summary>
/// Copies data from data-row into this object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="object"></param>
/// <param name="dataRow"></param>
/// <param name="standardAttributes"></param>
/// <param name="extendedAttributes"></param>
/// <param name="whenSetAttributeValueGotError"></param>
/// <returns></returns>
public static T Copy<T>(this T @object, DataRow dataRow, Dictionary<string, AttributeInfo> standardAttributes, Dictionary<string, ExtendedPropertyDefinition> extendedAttributes, Action<T, string, object, Exception> whenSetAttributeValueGotError = null) where T : class
{
@object = @object ?? ObjectService.CreateInstance<T>();
if (@object is IBusinessEntity businessEntity && businessEntity.ExtendedProperties == null && extendedAttributes != null)
businessEntity.ExtendedProperties = new Dictionary<string, object>();
var changedNotifier = @object is IPropertyChangedNotifier
? @object as IPropertyChangedNotifier
: null;
for (var index = 0; index < dataRow.Table.Columns.Count; index++)
@object.SetAttributeValue(dataRow.Table.Columns[index].ColumnName, dataRow[dataRow.Table.Columns[index].ColumnName], standardAttributes, extendedAttributes, changedNotifier, whenSetAttributeValueGotError);
return @object;
}
#endregion
#region Mappings
static List<Tuple<string, List<DbParameter>>> PrepareUpdateMappings(this DbProviderFactory dbProviderFactory, string tableName, string linkColumn, string mapColumn, string linkValue, IEnumerable<string> mapValues)
{
var statements = new List<Tuple<string, List<DbParameter>>>
{
new Tuple<string, List<DbParameter>>(
$"DELETE FROM {tableName} WHERE {linkColumn}=@{linkColumn}",
new List<DbParameter>
{
dbProviderFactory.CreateParameter(new KeyValuePair<string, object>($"@{linkColumn}", linkValue))
}
)
};
mapValues.ForEach(mapValue => statements.Add(new Tuple<string, List<DbParameter>>(
$"INSERT INTO {tableName} ({linkColumn},{mapColumn}) VALUES (@{linkColumn},@{mapColumn})",
new List<DbParameter>
{
dbProviderFactory.CreateParameter(new KeyValuePair<string, object>($"@{linkColumn}", linkValue)),
dbProviderFactory.CreateParameter(new KeyValuePair<string, object>($"@{mapColumn}", mapValue))
}
)));
return statements;
}
static List<Tuple<string, List<DbParameter>>> PrepareUpdateMappings<T>(this T @object, DbProviderFactory dbProviderFactory) where T : class
{
var statements = new List<Tuple<string, List<DbParameter>>>();
var definition = RepositoryMediator.GetEntityDefinition<T>();
var linkValue = @object is RepositoryBase ? (@object as RepositoryBase).ID : @object.GetEntityID();
definition.Attributes.Where(attribute => attribute.IsMappings()).ForEach(attribute =>
{
var values = @object.GetAttributeValue(attribute);
var mapValues = values != null
? values.IsGenericList() ? values as List<string> : (values as HashSet<string>).ToList()
: new List<string>();
var mapInfo = attribute.GetMapInfo(definition);
statements = statements.Concat(dbProviderFactory.PrepareUpdateMappings(mapInfo.Item1, mapInfo.Item2, mapInfo.Item3, linkValue, mapValues)).ToList();
});
return statements;
}
static string UpdateMappings<T>(this T @object, DbConnection connection, DbProviderFactory dbProviderFactory, bool performCreateNew = true) where T : class
{
var info = "";
var statements = performCreateNew
? @object.PrepareUpdateMappings(dbProviderFactory)
: @object.PrepareUpdateMappings(dbProviderFactory).Where(statement => statement.Item1.IsStartsWith("DELETE")).ToList();
statements.ForEach(statement =>
{
var command = connection.CreateCommand(statement);
command.ExecuteNonQuery();
if (RepositoryMediator.IsDebugEnabled)
info += (info != "" ? "\r\n" : "") + command.GetInfo();
});
return info;
}
static async Task<string> UpdateMappingsAsync<T>(this T @object, DbConnection connection, DbProviderFactory dbProviderFactory, CancellationToken cancellationToken = default, bool performCreateNew = true) where T : class
{
var info = "";
var statements = performCreateNew
? @object.PrepareUpdateMappings(dbProviderFactory)
: @object.PrepareUpdateMappings(dbProviderFactory).Where(statement => statement.Item1.IsStartsWith("DELETE")).ToList();
await statements.ForEachAsync(async (statement, token) =>
{
var command = connection.CreateCommand(statement);
await command.ExecuteNonQueryAsync(token).ConfigureAwait(false);
if (RepositoryMediator.IsDebugEnabled)
info += (info != "" ? "\r\n" : "") + command.GetInfo();
}, cancellationToken, true, false).ConfigureAwait(false);
return info;
}
static Tuple<string, List<DbParameter>> PrepareGetMappings(this DbProviderFactory dbProviderFactory, string tableName, string linkColumn, string mapColumn, string linkValue)
=> new Tuple<string, List<DbParameter>>(
$"SELECT {mapColumn} FROM {tableName} WHERE {linkColumn}=@{linkColumn}",
new List<DbParameter>
{
dbProviderFactory.CreateParameter(new KeyValuePair<string, object>($"@{linkColumn}", linkValue))
}
);
static List<string> GetMappings(this DbProviderFactory dbProviderFactory, DbConnection connection, string tableName, string linkColumn, string mapColumn, string linkValue)
{
var mapValues = new List<string>();
var command = connection.CreateCommand(dbProviderFactory.PrepareGetMappings(tableName, linkColumn, mapColumn, linkValue));
using (var dataReader = command.ExecuteReader())
while (dataReader.Read())
mapValues.Add(dataReader[0]?.ToString());
return mapValues;
}
static void GetMappings<T>(this T @object, DbConnection connection, DbProviderFactory dbProviderFactory) where T : class
{
var definition = RepositoryMediator.GetEntityDefinition<T>();
var linkValue = @object is RepositoryBase ? (@object as RepositoryBase).ID : @object.GetEntityID();
definition.Attributes.Where(attribute => attribute.IsMappings()).ForEach(attribute =>
{
var mapInfo = attribute.GetMapInfo(definition);
var mapValues = dbProviderFactory.GetMappings(connection, mapInfo.Item1, mapInfo.Item2, mapInfo.Item3, linkValue);
@object.SetAttributeValue(attribute, attribute.IsGenericHashSet() ? mapValues.ToHashSet() as object : mapValues);
});
}
static async Task<List<string>> GetMappingsAsync(this DbProviderFactory dbProviderFactory, DbConnection connection, string tableName, string linkColumn, string mapColumn, string linkValue, CancellationToken cancellationToken = default)
{
var mapValues = new List<string>();
var command = connection.CreateCommand(dbProviderFactory.PrepareGetMappings(tableName, linkColumn, mapColumn, linkValue));
using (var dataReader = await command.ExecuteReaderAsync(cancellationToken).ConfigureAwait(false))
while (await dataReader.ReadAsync(cancellationToken).ConfigureAwait(false))
mapValues.Add(dataReader[0]?.ToString());
return mapValues;
}
static async Task GetMappingsAsync<T>(this T @object, DbConnection connection, DbProviderFactory dbProviderFactory, CancellationToken cancellationToken = default) where T : class
{
var definition = RepositoryMediator.GetEntityDefinition<T>();
var linkValue = @object is RepositoryBase ? (@object as RepositoryBase).ID : @object.GetEntityID();
await definition.Attributes.Where(attribute => attribute.IsMappings()).ForEachAsync(async attribute =>
{
var mapInfo = attribute.GetMapInfo(definition);
var mapValues = await dbProviderFactory.GetMappingsAsync(connection, mapInfo.Item1, mapInfo.Item2, mapInfo.Item3, linkValue, cancellationToken).ConfigureAwait(false);
@object.SetAttributeValue(attribute, attribute.IsGenericHashSet() ? mapValues.ToHashSet() as object : mapValues);
}, true, false).ConfigureAwait(false);
}
#endregion
#region Create
static Tuple<string, List<DbParameter>> PrepareCreateOrigin<T>(this T @object, DbProviderFactory dbProviderFactory) where T : class
{
var columns = new List<string>();
var values = new List<string>();
var parameters = new List<DbParameter>();
var definition = RepositoryMediator.GetEntityDefinition<T>();
foreach (var attribute in definition.Attributes.Where(attribute => !attribute.IsMappings()).ToList())
{
var value = @object.GetAttributeValue(attribute.Name);
if (value == null && attribute.IsIgnoredIfNull())
continue;
columns.Add(string.IsNullOrEmpty(attribute.Column) ? attribute.Name : attribute.Column);
values.Add($"@{attribute.Name}");
parameters.Add(dbProviderFactory.CreateParameter(attribute, value));
}
var statement = $"INSERT INTO {definition.TableName} ({columns.Join(", ")}) VALUES ({values.Join(", ")})";
return new Tuple<string, List<DbParameter>>(statement, parameters);
}
static Tuple<string, List<DbParameter>> PrepareCreateExtent<T>(this T @object, DbProviderFactory dbProviderFactory) where T : class
{
var columns = "ID,SystemID,RepositoryID,RepositoryEntityID".ToList();
var values = columns.Select(c => $"@{c}").ToList();
var parameters = new List<DbParameter>
{
dbProviderFactory.CreateParameter(new KeyValuePair<string, object>("@ID", (@object as IBusinessEntity).ID)),
dbProviderFactory.CreateParameter(new KeyValuePair<string, object>("@SystemID", (@object as IBusinessEntity).SystemID)),
dbProviderFactory.CreateParameter(new KeyValuePair<string, object>("@RepositoryID", (@object as IBusinessEntity).RepositoryID)),
dbProviderFactory.CreateParameter(new KeyValuePair<string, object>("@RepositoryEntityID", (@object as IBusinessEntity).RepositoryEntityID))
};
var definition = RepositoryMediator.GetEntityDefinition<T>();
var attributes = definition.BusinessRepositoryEntities[(@object as IBusinessEntity).RepositoryEntityID].ExtendedPropertyDefinitions;
foreach (var attribute in attributes)
{
columns.Add(attribute.Column);
values.Add($"@{attribute.Name}");
var value = (@object as IBusinessEntity).ExtendedProperties != null && (@object as IBusinessEntity).ExtendedProperties.ContainsKey(attribute.Name)
? (@object as IBusinessEntity).ExtendedProperties[attribute.Name]
: attribute.GetDefaultValue();
parameters.Add(dbProviderFactory.CreateParameter(attribute, value));
}
var statement = $"INSERT INTO {definition.RepositoryDefinition.ExtendedPropertiesTableName} ({columns.Join(", ")}) VALUES ({values.Join(", ")})";
return new Tuple<string, List<DbParameter>>(statement, parameters);
}
/// <summary>
/// Creates new the record of an object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="context">The working context</param>
/// <param name="dataSource">The data source</param>
/// <param name="object">The object for creating new instance in storage</param>
public static void Create<T>(this RepositoryContext context, DataSource dataSource, T @object) where T : class
{
if (@object == null)
throw new ArgumentNullException(nameof(@object), "The object is null");
var stopwatch = Stopwatch.StartNew();
dataSource = dataSource ?? context.GetPrimaryDataSource();
var dbProviderFactory = dataSource.GetProviderFactory();
using (var connection = dbProviderFactory.CreateConnection(dataSource))
{
var command = connection.CreateCommand(@object.PrepareCreateOrigin(dbProviderFactory));
try
{
command.ExecuteNonQuery();
var info = !RepositoryMediator.IsDebugEnabled ? "" : command.GetInfo();
if (@object.IsGotExtendedProperties())
{
command = connection.CreateCommand(@object.PrepareCreateExtent(dbProviderFactory));
command.ExecuteNonQuery();
if (RepositoryMediator.IsDebugEnabled)
info += "\r\n" + command.GetInfo();
}
info += "\r\n" + @object.UpdateMappings(connection, dbProviderFactory);
stopwatch.Stop();
if (RepositoryMediator.IsDebugEnabled)
RepositoryMediator.WriteLogs(new[]
{
$"SQL: Perform CREATE command successful [{typeof(T)}#{@object?.GetEntityID()}] @ {dataSource.Name}",
$"Execution times: {stopwatch.GetElapsedTimes()}",
info
});
}
catch (Exception ex)
{
throw new RepositoryOperationException($"Could not perform CREATE command [{typeof(T)}#{@object?.GetEntityID()}]", command.GetInfo(), ex);
}
}
}
/// <summary>
/// Creates new the record of an object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dataSource">The data source</param>
/// <param name="object">The object for creating new instance in storage</param>
public static void Create<T>(DataSource dataSource, T @object) where T : class
{
using (var context = new RepositoryContext())
{
context.Operation = RepositoryOperation.Create;
context.EntityDefinition = RepositoryMediator.GetEntityDefinition<T>();
context.Create(dataSource, @object);
}
}
/// <summary>
/// Creates new the record of an object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="context">The working context</param>
/// <param name="dataSource">The data source</param>
/// <param name="object">The object for creating new instance in storage</param>
/// <param name="cancellationToken">The cancellation token</param>
/// <returns></returns>
public static async Task CreateAsync<T>(this RepositoryContext context, DataSource dataSource, T @object, CancellationToken cancellationToken = default) where T : class
{
if (@object == null)
throw new ArgumentNullException(nameof(@object), "The object is null");
var stopwatch = Stopwatch.StartNew();
dataSource = dataSource ?? context.GetPrimaryDataSource();
var dbProviderFactory = dataSource.GetProviderFactory();
using (var connection = await dbProviderFactory.CreateConnectionAsync(dataSource, cancellationToken).ConfigureAwait(false))
{
var command = connection.CreateCommand(@object.PrepareCreateOrigin(dbProviderFactory));
try
{
await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false);
var info = !RepositoryMediator.IsDebugEnabled ? "" : command.GetInfo();
if (@object.IsGotExtendedProperties())
{
command = connection.CreateCommand(@object.PrepareCreateExtent(dbProviderFactory));
await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false);
if (RepositoryMediator.IsDebugEnabled)
info += "\r\n" + command.GetInfo();
}
info += "\r\n" + await @object.UpdateMappingsAsync(connection, dbProviderFactory, cancellationToken).ConfigureAwait(false);
stopwatch.Stop();
if (RepositoryMediator.IsDebugEnabled)
RepositoryMediator.WriteLogs(new[]
{
$"SQL: Perform CREATE command successful [{typeof(T)}#{@object?.GetEntityID()}] @ {dataSource.Name}",
$"Execution times: {stopwatch.GetElapsedTimes()}",
info
});
}
catch (Exception ex)
{
throw new RepositoryOperationException($"Could not perform CREATE command [{typeof(T)}#{@object?.GetEntityID()}]", command.GetInfo(), ex);
}
}
}
/// <summary>
/// Creates new the record of an object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dataSource">The data source</param>
/// <param name="object">The object for creating new instance in storage</param>
/// <param name="cancellationToken">The cancellation token</param>
/// <returns></returns>
public static async Task CreateAsync<T>(DataSource dataSource, T @object, CancellationToken cancellationToken = default) where T : class
{
using (var context = new RepositoryContext())
{
context.Operation = RepositoryOperation.Create;
context.EntityDefinition = RepositoryMediator.GetEntityDefinition<T>();
await context.CreateAsync(dataSource, @object, cancellationToken).ConfigureAwait(false);
}
}
#endregion
#region Get
static Tuple<string, List<DbParameter>> PrepareGetOrigin<T>(this T @object, string id, DbProviderFactory dbProviderFactory) where T : class
{
var definition = RepositoryMediator.GetEntityDefinition<T>();
var fields = definition.Attributes
.Where(attribute => !attribute.IsMappings())
.Where(attribute => !attribute.IsIgnoredIfNull() || (attribute.IsIgnoredIfNull() && @object.GetAttributeValue(attribute) != null))
.Select(attribute => "Origin." + (string.IsNullOrEmpty(attribute.Column) ? attribute.Name : $"{attribute.Column} AS {attribute.Name}"))
.ToList();
var info = Filters<T>.Equals(definition.PrimaryKey, id).GetSqlStatement();
var statement = $"SELECT {fields.Join(", ")} FROM {definition.TableName} AS Origin WHERE {info.Item1}";
var parameters = info.Item2.Select(param => dbProviderFactory.CreateParameter(param)).ToList();
return new Tuple<string, List<DbParameter>>(statement, parameters);
}
static Tuple<string, List<DbParameter>> PrepareGetExtent<T>(this T @object, string id, DbProviderFactory dbProviderFactory, List<ExtendedPropertyDefinition> extendedProperties) where T : class
{
var fields = extendedProperties.Select(attribute => $"Origin.{attribute.Column} AS {attribute.Name}")
.Concat(new[] { "Origin.ID" })
.ToList();
var info = Filters<T>.Equals("ID", id).GetSqlStatement();
var statement = $"SELECT {fields.Join(", ")} FROM {RepositoryMediator.GetEntityDefinition<T>().RepositoryDefinition.ExtendedPropertiesTableName} AS Origin WHERE {info.Item1}";
var parameters = info.Item2.Select(param => dbProviderFactory.CreateParameter(param)).ToList();
return new Tuple<string, List<DbParameter>>(statement, parameters);
}
/// <summary>
/// Gets the record and construct an object
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="context">The working context</param>
/// <param name="dataSource">The data source</param>
/// <param name="id">The string that presents identity</param>
/// <returns></returns>
public static T Get<T>(this RepositoryContext context, DataSource dataSource, string id) where T : class
{
if (string.IsNullOrEmpty(id))
return default;
var stopwatch = Stopwatch.StartNew();
dataSource = dataSource ?? context.GetPrimaryDataSource();
var dbProviderFactory = dataSource.GetProviderFactory();
using (var connection = dbProviderFactory.CreateConnection(dataSource))
{
var @object = ObjectService.CreateInstance<T>();
var command = connection.CreateCommand(@object.PrepareGetOrigin(id, dbProviderFactory));
try
{
using (var dataReader = command.ExecuteReader())
@object = dataReader.Read() ? @object.Copy(dataReader, context.EntityDefinition.Attributes.ToDictionary(attribute => attribute.Name), null) : null;
var info = !RepositoryMediator.IsDebugEnabled ? "" : command.GetInfo();
if (@object != null && @object.IsGotExtendedProperties())
{
var extendedProperties = context.EntityDefinition.BusinessRepositoryEntities[(@object as IBusinessEntity).RepositoryEntityID].ExtendedPropertyDefinitions;
command = connection.CreateCommand(@object.PrepareGetExtent(id, dbProviderFactory, extendedProperties));
using (var dataReader = command.ExecuteReader())
if (dataReader.Read())