DbHelper.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  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 "OwnerId":
  141. case "CreatedUserId":
  142. if (e.Value == null || (long)e.Value == default || (long?)e.Value == default)
  143. {
  144. e.Value = user.Id;
  145. }
  146. break;
  147. case "CreatedUserName":
  148. if (e.Value == null || ((string)e.Value).IsNull())
  149. {
  150. e.Value = user.UserName;
  151. }
  152. break;
  153. case "OwnerOrgId":
  154. if (e.Value == null || (long)e.Value == default || (long?)e.Value == default)
  155. {
  156. e.Value = user.DataPermission?.OrgId;
  157. }
  158. break;
  159. case "TenantId":
  160. if (e.Value == null || (long)e.Value == default || (long?)e.Value == default)
  161. {
  162. e.Value = user.TenantId;
  163. }
  164. break;
  165. }
  166. }
  167. else if (e.AuditValueType == AuditValueType.Update)
  168. {
  169. switch (e.Property.Name)
  170. {
  171. case "ModifiedUserId":
  172. e.Value = user.Id;
  173. break;
  174. case "ModifiedUserName":
  175. e.Value = user.UserName;
  176. break;
  177. }
  178. }
  179. }
  180. /// <summary>
  181. /// 同步结构
  182. /// </summary>
  183. public static void SyncStructure(IFreeSql db, string msg = null, DbConfig dbConfig = null, AppConfig appConfig = null)
  184. {
  185. //打印结构比对脚本
  186. //var dDL = db.CodeFirst.GetComparisonDDLStatements<PermissionEntity>();
  187. //Console.WriteLine("\r\n " + dDL);
  188. //打印结构同步脚本
  189. //db.Aop.SyncStructureAfter += (s, e) =>
  190. //{
  191. // if (e.Sql.NotNull())
  192. // {
  193. // Console.WriteLine(" sync structure sql:\n" + e.Sql);
  194. // }
  195. //};
  196. // 同步结构
  197. var dbType = dbConfig.Type.ToString();
  198. Console.WriteLine($"\r\n {(msg.NotNull() ? msg : $"sync {dbType} structure")} started");
  199. if (dbConfig.Type == DataType.Oracle)
  200. {
  201. db.CodeFirst.IsSyncStructureToUpper = true;
  202. }
  203. //获得指定程序集表实体
  204. var entityTypes = GetEntityTypes(appConfig);
  205. db.CodeFirst.SyncStructure(entityTypes);
  206. Console.WriteLine($" {(msg.NotNull() ? msg : $"sync {dbType} structure")} succeed");
  207. }
  208. /// <summary>
  209. /// 同步数据审计方法
  210. /// </summary>
  211. /// <param name="s"></param>
  212. /// <param name="e"></param>
  213. private static void SyncDataAuditValue(object s, AuditValueEventArgs e)
  214. {
  215. var user = new { Id = 161223411986501, Name = "admin", TenantId = 161223412138053 };
  216. if (e.Property.GetCustomAttribute<ServerTimeAttribute>(false) != null
  217. && (e.Column.CsType == typeof(DateTime) || e.Column.CsType == typeof(DateTime?))
  218. && (e.Value == null || (DateTime)e.Value == default || (DateTime?)e.Value == default))
  219. {
  220. e.Value = DateTime.Now.Subtract(TimeOffset);
  221. }
  222. if (e.Column.CsType == typeof(long)
  223. && e.Property.GetCustomAttribute<SnowflakeAttribute>(false) != null
  224. && (e.Value == null || (long)e.Value == default || (long?)e.Value == default))
  225. {
  226. e.Value = YitIdHelper.NextId();
  227. }
  228. if (user == null || user.Id <= 0)
  229. {
  230. return;
  231. }
  232. if (e.AuditValueType == AuditValueType.Insert)
  233. {
  234. switch (e.Property.Name)
  235. {
  236. case "CreatedUserId":
  237. if (e.Value == null || (long)e.Value == default || (long?)e.Value == default)
  238. {
  239. e.Value = user.Id;
  240. }
  241. break;
  242. case "CreatedUserName":
  243. if (e.Value == null || ((string)e.Value).IsNull())
  244. {
  245. e.Value = user.Name;
  246. }
  247. break;
  248. case "TenantId":
  249. if (e.Value == null || (long)e.Value == default || (long?)e.Value == default)
  250. {
  251. e.Value = user.TenantId;
  252. }
  253. break;
  254. }
  255. }
  256. else if (e.AuditValueType == AuditValueType.Update)
  257. {
  258. switch (e.Property.Name)
  259. {
  260. case "ModifiedUserId":
  261. e.Value = user.Id;
  262. break;
  263. case "ModifiedUserName":
  264. e.Value = user.Name;
  265. break;
  266. }
  267. }
  268. }
  269. /// <summary>
  270. /// 同步数据
  271. /// </summary>
  272. /// <param name="db"></param>
  273. /// <param name="dbConfig"></param>
  274. /// <param name="appConfig"></param>
  275. /// <returns></returns>
  276. /// <exception cref="Exception"></exception>
  277. public static async Task SyncDataAsync(
  278. IFreeSql db,
  279. DbConfig dbConfig = null,
  280. AppConfig appConfig = null
  281. )
  282. {
  283. try
  284. {
  285. Console.WriteLine("\r\n sync data started");
  286. db.Aop.AuditValue += SyncDataAuditValue;
  287. Assembly[] assemblies = DependencyContext.Default.RuntimeLibraries
  288. .Where(a => appConfig.AssemblyNames.Contains(a.Name) || a.Name == "ZhonTai.Admin")
  289. .Select(o => Assembly.Load(new AssemblyName(o.Name))).ToArray();
  290. List<ISyncData> syncDatas = assemblies.Select(assembly => assembly.GetTypes()
  291. .Where(x => typeof(ISyncData).GetTypeInfo().IsAssignableFrom(x.GetTypeInfo()) && x.GetTypeInfo().IsClass && !x.GetTypeInfo().IsAbstract))
  292. .SelectMany(registerTypes => registerTypes.Select(registerType => (ISyncData)Activator.CreateInstance(registerType))).ToList();
  293. foreach (ISyncData syncData in syncDatas)
  294. {
  295. await syncData.SyncDataAsync(db, dbConfig, appConfig);
  296. }
  297. db.Aop.AuditValue -= SyncDataAuditValue;
  298. Console.WriteLine(" sync data succeed\r\n");
  299. }
  300. catch (Exception ex)
  301. {
  302. throw new Exception($" sync data failed.\n{ex.Message}");
  303. }
  304. }
  305. /// <summary>
  306. /// 生成数据
  307. /// </summary>
  308. /// <param name="db"></param>
  309. /// <param name="appConfig"></param>
  310. /// <returns></returns>
  311. /// <exception cref="Exception"></exception>
  312. public static async Task GenerateDataAsync(IFreeSql db, AppConfig appConfig = null)
  313. {
  314. try
  315. {
  316. Console.WriteLine("\r\n generate data started");
  317. Assembly[] assemblies = DependencyContext.Default.RuntimeLibraries
  318. .Where(a => appConfig.AssemblyNames.Contains(a.Name) || a.Name == "ZhonTai.Admin")
  319. .Select(o => Assembly.Load(new AssemblyName(o.Name))).ToArray();
  320. List<IGenerateData> generateDatas = assemblies.Select(assembly => assembly.GetTypes()
  321. .Where(x => typeof(IGenerateData).GetTypeInfo().IsAssignableFrom(x.GetTypeInfo()) && x.GetTypeInfo().IsClass && !x.GetTypeInfo().IsAbstract))
  322. .SelectMany(registerTypes => registerTypes.Select(registerType => (IGenerateData)Activator.CreateInstance(registerType))).ToList();
  323. foreach (IGenerateData generateData in generateDatas)
  324. {
  325. await generateData.GenerateDataAsync(db, appConfig);
  326. }
  327. Console.WriteLine(" generate data succeed\r\n");
  328. }
  329. catch (Exception ex)
  330. {
  331. throw new Exception($" generate data failed。\n{ex.Message}\r\n");
  332. }
  333. }
  334. }