DbHelper.cs 13 KB

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