DbHelper.cs 12 KB

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