DbHelper.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. using Microsoft.Extensions.DependencyModel;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Reflection;
  6. using System.Threading.Tasks;
  7. using FreeSql;
  8. using FreeSql.Aop;
  9. using FreeSql.DataAnnotations;
  10. using Yitter.IdGenerator;
  11. using ZhonTai.Admin.Core.Configs;
  12. using ZhonTai.Admin.Core.Entities;
  13. using ZhonTai.Admin.Core.Attributes;
  14. using ZhonTai.Admin.Core.Auth;
  15. using System.IO;
  16. using ZhonTai.Common.Helpers;
  17. namespace ZhonTai.Admin.Core.Db;
  18. public class DbHelper
  19. {
  20. /// <summary>
  21. /// 偏移时间
  22. /// </summary>
  23. public static TimeSpan TimeOffset;
  24. /// <summary>
  25. /// 创建数据库
  26. /// </summary>
  27. /// <param name="dbConfig"></param>
  28. /// <returns></returns>
  29. public async static Task CreateDatabaseAsync(DbConfig dbConfig)
  30. {
  31. if (!dbConfig.CreateDb || dbConfig.Type == DataType.Sqlite)
  32. {
  33. return;
  34. }
  35. var db = new FreeSqlBuilder()
  36. .UseConnectionString(dbConfig.Type, dbConfig.CreateDbConnectionString)
  37. .Build();
  38. try
  39. {
  40. Console.WriteLine("\r\n create database started");
  41. var filePath = Path.Combine(AppContext.BaseDirectory, "Configs/createdbsql.txt").ToPath();
  42. if (File.Exists(filePath))
  43. {
  44. var createDbSql = FileHelper.ReadFile(filePath);
  45. if (createDbSql.NotNull())
  46. {
  47. dbConfig.CreateDbSql = createDbSql;
  48. }
  49. }
  50. await db.Ado.ExecuteNonQueryAsync(dbConfig.CreateDbSql);
  51. Console.WriteLine(" create database succeed");
  52. }
  53. catch (Exception e)
  54. {
  55. Console.WriteLine($" create database failed.\n {e.Message}");
  56. }
  57. }
  58. /// <summary>
  59. /// 获得指定程序集表实体
  60. /// </summary>
  61. /// <param name="appConfig"></param>
  62. /// <returns></returns>
  63. public static Type[] GetEntityTypes(AppConfig appConfig)
  64. {
  65. Assembly[] assemblies = DependencyContext.Default.RuntimeLibraries
  66. .Where(a => appConfig.AssemblyNames.Contains(a.Name) || a.Name == "ZhonTai.Admin")
  67. .Select(o => Assembly.Load(new AssemblyName(o.Name))).ToArray();
  68. var entityTypes = new List<Type>();
  69. foreach (var assembly in assemblies)
  70. {
  71. foreach (Type type in assembly.GetExportedTypes())
  72. {
  73. foreach (Attribute attribute in type.GetCustomAttributes())
  74. {
  75. if (attribute is TableAttribute tableAttribute)
  76. {
  77. if (tableAttribute.DisableSyncStructure == false)
  78. {
  79. entityTypes.Add(type);
  80. }
  81. }
  82. }
  83. }
  84. }
  85. return entityTypes.ToArray();
  86. }
  87. /// <summary>
  88. /// 配置实体
  89. /// </summary>
  90. public static void ConfigEntity(IFreeSql db, AppConfig appConfig = null)
  91. {
  92. //租户生成和操作租户Id
  93. if (!appConfig.Tenant)
  94. {
  95. var iTenant = nameof(ITenant);
  96. var tenantId = nameof(ITenant.TenantId);
  97. //获得指定程序集表实体
  98. var entityTypes = GetEntityTypes(appConfig);
  99. foreach (var entityType in entityTypes)
  100. {
  101. if (entityType.GetInterfaces().Any(a => a.Name == iTenant))
  102. {
  103. db.CodeFirst.Entity(entityType, a =>
  104. {
  105. a.Ignore(tenantId);
  106. });
  107. }
  108. }
  109. }
  110. }
  111. /// <summary>
  112. /// 审计数据
  113. /// </summary>
  114. /// <param name="e"></param>
  115. /// <param name="timeOffset"></param>
  116. /// <param name="user"></param>
  117. public static void AuditValue(AuditValueEventArgs e, TimeSpan timeOffset, IUser user)
  118. {
  119. if (e.Property.GetCustomAttribute<ServerTimeAttribute>(false) != null
  120. && (e.Column.CsType == typeof(DateTime) || e.Column.CsType == typeof(DateTime?))
  121. && (e.Value == null || (DateTime)e.Value == default || (DateTime?)e.Value == default))
  122. {
  123. e.Value = DateTime.Now.Subtract(timeOffset);
  124. }
  125. if (e.Column.CsType == typeof(long)
  126. && e.Property.GetCustomAttribute<SnowflakeAttribute>(false) is SnowflakeAttribute snowflakeAttribute
  127. && snowflakeAttribute.Enable && (e.Value == null || (long)e.Value == default || (long?)e.Value == default))
  128. {
  129. e.Value = YitIdHelper.NextId();
  130. }
  131. if (user == null || user.Id <= 0)
  132. {
  133. return;
  134. }
  135. if (e.AuditValueType == AuditValueType.Insert)
  136. {
  137. switch (e.Property.Name)
  138. {
  139. case "CreatedUserId":
  140. if (e.Value == null || (long)e.Value == default || (long?)e.Value == default)
  141. {
  142. e.Value = user.Id;
  143. }
  144. break;
  145. case "CreatedUserName":
  146. if (e.Value == null || ((string)e.Value).IsNull())
  147. {
  148. e.Value = user.UserName;
  149. }
  150. break;
  151. case "TenantId":
  152. if (e.Value == null || (long)e.Value == default || (long?)e.Value == default)
  153. {
  154. e.Value = user.TenantId;
  155. }
  156. break;
  157. }
  158. }
  159. else if (e.AuditValueType == AuditValueType.Update)
  160. {
  161. switch (e.Property.Name)
  162. {
  163. case "ModifiedUserId":
  164. e.Value = user.Id;
  165. break;
  166. case "ModifiedUserName":
  167. e.Value = user.UserName;
  168. break;
  169. }
  170. }
  171. }
  172. /// <summary>
  173. /// 同步结构
  174. /// </summary>
  175. public static void SyncStructure(IFreeSql db, string msg = null, DbConfig dbConfig = null, AppConfig appConfig = null)
  176. {
  177. //打印结构比对脚本
  178. //var dDL = db.CodeFirst.GetComparisonDDLStatements<PermissionEntity>();
  179. //Console.WriteLine("\r\n " + dDL);
  180. //打印结构同步脚本
  181. //db.Aop.SyncStructureAfter += (s, e) =>
  182. //{
  183. // if (e.Sql.NotNull())
  184. // {
  185. // Console.WriteLine(" sync structure sql:\n" + e.Sql);
  186. // }
  187. //};
  188. // 同步结构
  189. var dbType = dbConfig.Type.ToString();
  190. Console.WriteLine($"\r\n {(msg.NotNull() ? msg : $"sync {dbType} structure")} started");
  191. if (dbConfig.Type == DataType.Oracle)
  192. {
  193. db.CodeFirst.IsSyncStructureToUpper = true;
  194. }
  195. //获得指定程序集表实体
  196. var entityTypes = GetEntityTypes(appConfig);
  197. db.CodeFirst.SyncStructure(entityTypes);
  198. Console.WriteLine($" {(msg.NotNull() ? msg : $"sync {dbType} structure")} succeed");
  199. }
  200. /// <summary>
  201. /// 同步数据审计方法
  202. /// </summary>
  203. /// <param name="s"></param>
  204. /// <param name="e"></param>
  205. private static void SyncDataAuditValue(object s, AuditValueEventArgs e)
  206. {
  207. var user = new { Id = 161223411986501, Name = "admin", TenantId = 161223412138053 };
  208. if (e.Property.GetCustomAttribute<ServerTimeAttribute>(false) != null
  209. && (e.Column.CsType == typeof(DateTime) || e.Column.CsType == typeof(DateTime?))
  210. && (e.Value == null || (DateTime)e.Value == default || (DateTime?)e.Value == default))
  211. {
  212. e.Value = DateTime.Now.Subtract(TimeOffset);
  213. }
  214. if (e.Column.CsType == typeof(long)
  215. && e.Property.GetCustomAttribute<SnowflakeAttribute>(false) != null
  216. && (e.Value == null || (long)e.Value == default || (long?)e.Value == default))
  217. {
  218. e.Value = YitIdHelper.NextId();
  219. }
  220. if (user == null || user.Id <= 0)
  221. {
  222. return;
  223. }
  224. if (e.AuditValueType == AuditValueType.Insert)
  225. {
  226. switch (e.Property.Name)
  227. {
  228. case "CreatedUserId":
  229. if (e.Value == null || (long)e.Value == default || (long?)e.Value == default)
  230. {
  231. e.Value = user.Id;
  232. }
  233. break;
  234. case "CreatedUserName":
  235. if (e.Value == null || ((string)e.Value).IsNull())
  236. {
  237. e.Value = user.Name;
  238. }
  239. break;
  240. case "TenantId":
  241. if (e.Value == null || (long)e.Value == default || (long?)e.Value == default)
  242. {
  243. e.Value = user.TenantId;
  244. }
  245. break;
  246. }
  247. }
  248. else if (e.AuditValueType == AuditValueType.Update)
  249. {
  250. switch (e.Property.Name)
  251. {
  252. case "ModifiedUserId":
  253. e.Value = user.Id;
  254. break;
  255. case "ModifiedUserName":
  256. e.Value = user.Name;
  257. break;
  258. }
  259. }
  260. }
  261. /// <summary>
  262. /// 同步数据
  263. /// </summary>
  264. /// <param name="db"></param>
  265. /// <param name="dbConfig"></param>
  266. /// <param name="appConfig"></param>
  267. /// <returns></returns>
  268. /// <exception cref="Exception"></exception>
  269. public static async Task SyncDataAsync(
  270. IFreeSql db,
  271. DbConfig dbConfig = null,
  272. AppConfig appConfig = null
  273. )
  274. {
  275. try
  276. {
  277. Console.WriteLine("\r\n sync data started");
  278. db.Aop.AuditValue += SyncDataAuditValue;
  279. Assembly[] assemblies = DependencyContext.Default.RuntimeLibraries
  280. .Where(a => appConfig.AssemblyNames.Contains(a.Name) || a.Name == "ZhonTai.Admin")
  281. .Select(o => Assembly.Load(new AssemblyName(o.Name))).ToArray();
  282. List<ISyncData> syncDatas = assemblies.Select(assembly => assembly.GetTypes()
  283. .Where(x => typeof(ISyncData).GetTypeInfo().IsAssignableFrom(x.GetTypeInfo()) && x.GetTypeInfo().IsClass && !x.GetTypeInfo().IsAbstract))
  284. .SelectMany(registerTypes => registerTypes.Select(registerType => (ISyncData)Activator.CreateInstance(registerType))).ToList();
  285. foreach (ISyncData syncData in syncDatas)
  286. {
  287. await syncData.SyncDataAsync(db, dbConfig, appConfig);
  288. }
  289. db.Aop.AuditValue -= SyncDataAuditValue;
  290. Console.WriteLine(" sync data succeed\r\n");
  291. }
  292. catch (Exception ex)
  293. {
  294. throw new Exception($" sync data failed.\n{ex.Message}");
  295. }
  296. }
  297. /// <summary>
  298. /// 生成数据
  299. /// </summary>
  300. /// <param name="db"></param>
  301. /// <param name="appConfig"></param>
  302. /// <returns></returns>
  303. /// <exception cref="Exception"></exception>
  304. public static async Task GenerateDataAsync(IFreeSql db, AppConfig appConfig = null)
  305. {
  306. try
  307. {
  308. Console.WriteLine("\r\n generate data started");
  309. Assembly[] assemblies = DependencyContext.Default.RuntimeLibraries
  310. .Where(a => appConfig.AssemblyNames.Contains(a.Name) || a.Name == "ZhonTai.Admin")
  311. .Select(o => Assembly.Load(new AssemblyName(o.Name))).ToArray();
  312. List<IGenerateData> generateDatas = assemblies.Select(assembly => assembly.GetTypes()
  313. .Where(x => typeof(IGenerateData).GetTypeInfo().IsAssignableFrom(x.GetTypeInfo()) && x.GetTypeInfo().IsClass && !x.GetTypeInfo().IsAbstract))
  314. .SelectMany(registerTypes => registerTypes.Select(registerType => (IGenerateData)Activator.CreateInstance(registerType))).ToList();
  315. foreach (IGenerateData generateData in generateDatas)
  316. {
  317. await generateData.GenerateDataAsync(db, appConfig);
  318. }
  319. Console.WriteLine(" generate data succeed\r\n");
  320. }
  321. catch (Exception ex)
  322. {
  323. throw new Exception($" generate data failed。\n{ex.Message}\r\n");
  324. }
  325. }
  326. }