DbHelper.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  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. using StackExchange.Profiling;
  19. using ZhonTai.Admin.Core.Consts;
  20. using ZhonTai.Admin.Core.Startup;
  21. using ZhonTai.Admin.Domain.Role;
  22. using ZhonTai.Admin.Domain.User;
  23. namespace ZhonTai.Admin.Core.Db;
  24. public class DbHelper
  25. {
  26. /// <summary>
  27. /// 偏移时间
  28. /// </summary>
  29. public static TimeSpan TimeOffset;
  30. /// <summary>
  31. /// 创建数据库
  32. /// </summary>
  33. /// <param name="dbConfig"></param>
  34. /// <returns></returns>
  35. public async static Task CreateDatabaseAsync(DbConfig dbConfig)
  36. {
  37. if (!dbConfig.CreateDb || dbConfig.Type == DataType.Sqlite)
  38. {
  39. return;
  40. }
  41. var db = new FreeSqlBuilder()
  42. .UseConnectionString(dbConfig.Type, dbConfig.CreateDbConnectionString)
  43. .Build();
  44. try
  45. {
  46. Console.WriteLine($"{Environment.NewLine} create database started");
  47. var filePath = Path.Combine(AppContext.BaseDirectory, "Configs/createdbsql.txt").ToPath();
  48. if (File.Exists(filePath))
  49. {
  50. var createDbSql = FileHelper.ReadFile(filePath);
  51. if (createDbSql.NotNull())
  52. {
  53. dbConfig.CreateDbSql = createDbSql;
  54. }
  55. }
  56. await db.Ado.ExecuteNonQueryAsync(dbConfig.CreateDbSql);
  57. Console.WriteLine(" create database succeed");
  58. }
  59. catch (Exception e)
  60. {
  61. Console.WriteLine($" create database failed.\n {e.Message}");
  62. }
  63. }
  64. /// <summary>
  65. /// 获得指定程序集表实体
  66. /// </summary>
  67. /// <param name="assemblyNames"></param>
  68. /// <returns></returns>
  69. public static Type[] GetEntityTypes(string[] assemblyNames)
  70. {
  71. if(!(assemblyNames?.Length > 0))
  72. {
  73. return null;
  74. }
  75. Assembly[] assemblies = DependencyContext.Default.RuntimeLibraries
  76. .Where(a => assemblyNames.Contains(a.Name))
  77. .Select(o => Assembly.Load(new AssemblyName(o.Name))).ToArray();
  78. var entityTypes = new List<Type>();
  79. foreach (var assembly in assemblies)
  80. {
  81. foreach (Type type in assembly.GetExportedTypes())
  82. {
  83. foreach (Attribute attribute in type.GetCustomAttributes())
  84. {
  85. if (attribute is TableAttribute tableAttribute)
  86. {
  87. if (tableAttribute.DisableSyncStructure == false)
  88. {
  89. entityTypes.Add(type);
  90. }
  91. }
  92. }
  93. }
  94. }
  95. return entityTypes.ToArray();
  96. }
  97. /// <summary>
  98. /// 配置实体
  99. /// </summary>
  100. /// <param name="db"></param>
  101. /// <param name="appConfig"></param>
  102. /// <param name="dbConfig"></param>
  103. public static void ConfigEntity(IFreeSql db, AppConfig appConfig = null, DbConfig dbConfig = null)
  104. {
  105. //租户生成和操作租户Id
  106. if (!appConfig.Tenant)
  107. {
  108. var iTenant = nameof(ITenant);
  109. var tenantId = nameof(ITenant.TenantId);
  110. //获得指定程序集表实体
  111. var entityTypes = GetEntityTypes(dbConfig.AssemblyNames);
  112. foreach (var entityType in entityTypes)
  113. {
  114. if (entityType.GetInterfaces().Any(a => a.Name == iTenant))
  115. {
  116. db.CodeFirst.Entity(entityType, a =>
  117. {
  118. a.Ignore(tenantId);
  119. });
  120. }
  121. }
  122. }
  123. }
  124. /// <summary>
  125. /// 审计数据
  126. /// </summary>
  127. /// <param name="e"></param>
  128. /// <param name="timeOffset"></param>
  129. /// <param name="user"></param>
  130. public static void AuditValue(AuditValueEventArgs e, TimeSpan timeOffset, IUser user)
  131. {
  132. //数据库时间
  133. if ((e.Column.CsType == typeof(DateTime) || e.Column.CsType == typeof(DateTime?))
  134. && e.Property.GetCustomAttribute<ServerTimeAttribute>(false) != null
  135. && (e.Value == null || (DateTime)e.Value == default || (DateTime?)e.Value == default))
  136. {
  137. e.Value = DateTime.Now.Subtract(timeOffset);
  138. }
  139. //雪花Id
  140. if (e.Column.CsType == typeof(long)
  141. && e.Property.GetCustomAttribute<SnowflakeAttribute>(false) is SnowflakeAttribute snowflakeAttribute
  142. && snowflakeAttribute.Enable && (e.Value == null || (long)e.Value == default || (long?)e.Value == default))
  143. {
  144. e.Value = YitIdHelper.NextId();
  145. }
  146. //有序Guid
  147. if (e.Column.CsType == typeof(Guid)
  148. && e.Property.GetCustomAttribute<OrderGuidAttribute>(false) is OrderGuidAttribute orderGuidAttribute
  149. && orderGuidAttribute.Enable && (e.Value == null || (Guid)e.Value == default || (Guid?)e.Value == default))
  150. {
  151. e.Value = FreeUtil.NewMongodbId();
  152. }
  153. if (user == null || user.Id <= 0)
  154. {
  155. return;
  156. }
  157. if (e.AuditValueType == AuditValueType.Insert)
  158. {
  159. switch (e.Property.Name)
  160. {
  161. case "CreatedUserId":
  162. case "OwnerId":
  163. case "MemberId":
  164. if (e.Value == null || (long)e.Value == default || (long?)e.Value == default)
  165. {
  166. e.Value = user.Id;
  167. }
  168. break;
  169. case "CreatedUserName":
  170. if (e.Value == null || ((string)e.Value).IsNull())
  171. {
  172. e.Value = user.UserName;
  173. }
  174. break;
  175. case "OwnerOrgId":
  176. if (e.Value == null || (long)e.Value == default || (long?)e.Value == default)
  177. {
  178. e.Value = user.DataPermission?.OrgId;
  179. }
  180. break;
  181. case "TenantId":
  182. if (e.Value == null || (long)e.Value == default || (long?)e.Value == default)
  183. {
  184. e.Value = user.TenantId;
  185. }
  186. break;
  187. }
  188. }
  189. else if (e.AuditValueType == AuditValueType.Update)
  190. {
  191. switch (e.Property.Name)
  192. {
  193. case "ModifiedUserId":
  194. e.Value = user.Id;
  195. break;
  196. case "ModifiedUserName":
  197. e.Value = user.UserName;
  198. break;
  199. }
  200. }
  201. }
  202. /// <summary>
  203. /// 同步结构
  204. /// </summary>
  205. public static void SyncStructure(IFreeSql db, string msg = null, DbConfig dbConfig = null, AppConfig appConfig = null)
  206. {
  207. //打印结构比对脚本
  208. //var dDL = db.CodeFirst.GetComparisonDDLStatements<PermissionEntity>();
  209. //Console.WriteLine($"{Environment.NewLine} " + dDL);
  210. //打印结构同步脚本
  211. //db.Aop.SyncStructureAfter += (s, e) =>
  212. //{
  213. // if (e.Sql.NotNull())
  214. // {
  215. // Console.WriteLine(" sync structure sql:\n" + e.Sql);
  216. // }
  217. //};
  218. // 同步结构
  219. var dbType = dbConfig.Type.ToString();
  220. Console.WriteLine($"{Environment.NewLine} {(msg.NotNull() ? msg : $"sync {dbType} structure")} started");
  221. if (dbConfig.Type == DataType.Oracle)
  222. {
  223. db.CodeFirst.IsSyncStructureToUpper = true;
  224. }
  225. //获得指定程序集表实体
  226. var entityTypes = GetEntityTypes(dbConfig.AssemblyNames);
  227. db.CodeFirst.SyncStructure(entityTypes);
  228. Console.WriteLine($" {(msg.NotNull() ? msg : $"sync {dbType} structure")} succeed");
  229. }
  230. /// <summary>
  231. /// 同步数据审计方法
  232. /// </summary>
  233. /// <param name="s"></param>
  234. /// <param name="e"></param>
  235. private static void SyncDataAuditValue(object s, AuditValueEventArgs e)
  236. {
  237. var user = new { Id = 161223411986501, Name = "admin", TenantId = 161223412138053 };
  238. if (e.Property.GetCustomAttribute<ServerTimeAttribute>(false) != null
  239. && (e.Column.CsType == typeof(DateTime) || e.Column.CsType == typeof(DateTime?))
  240. && (e.Value == null || (DateTime)e.Value == default || (DateTime?)e.Value == default))
  241. {
  242. e.Value = DateTime.Now.Subtract(TimeOffset);
  243. }
  244. if (e.Column.CsType == typeof(long)
  245. && e.Property.GetCustomAttribute<SnowflakeAttribute>(false) != null
  246. && (e.Value == null || (long)e.Value == default || (long?)e.Value == default))
  247. {
  248. e.Value = YitIdHelper.NextId();
  249. }
  250. if (user == null || user.Id <= 0)
  251. {
  252. return;
  253. }
  254. if (e.AuditValueType == AuditValueType.Insert)
  255. {
  256. switch (e.Property.Name)
  257. {
  258. case "CreatedUserId":
  259. if (e.Value == null || (long)e.Value == default || (long?)e.Value == default)
  260. {
  261. e.Value = user.Id;
  262. }
  263. break;
  264. case "CreatedUserName":
  265. if (e.Value == null || ((string)e.Value).IsNull())
  266. {
  267. e.Value = user.Name;
  268. }
  269. break;
  270. case "TenantId":
  271. if (e.Value == null || (long)e.Value == default || (long?)e.Value == default)
  272. {
  273. e.Value = user.TenantId;
  274. }
  275. break;
  276. }
  277. }
  278. else if (e.AuditValueType == AuditValueType.Update)
  279. {
  280. switch (e.Property.Name)
  281. {
  282. case "ModifiedUserId":
  283. e.Value = user.Id;
  284. break;
  285. case "ModifiedUserName":
  286. e.Value = user.Name;
  287. break;
  288. }
  289. }
  290. }
  291. /// <summary>
  292. /// 同步数据
  293. /// </summary>
  294. /// <param name="db"></param>
  295. /// <param name="dbConfig"></param>
  296. /// <param name="appConfig"></param>
  297. /// <returns></returns>
  298. /// <exception cref="Exception"></exception>
  299. public static async Task SyncDataAsync(
  300. IFreeSql db,
  301. DbConfig dbConfig = null,
  302. AppConfig appConfig = null
  303. )
  304. {
  305. try
  306. {
  307. Console.WriteLine($"{Environment.NewLine} sync data started");
  308. if (dbConfig.AssemblyNames?.Length > 0)
  309. {
  310. db.Aop.AuditValue += SyncDataAuditValue;
  311. Assembly[] assemblies = DependencyContext.Default.RuntimeLibraries
  312. .Where(a => dbConfig.AssemblyNames.Contains(a.Name))
  313. .Select(o => Assembly.Load(new AssemblyName(o.Name))).ToArray();
  314. List<ISyncData> syncDatas = assemblies.Select(assembly => assembly.GetTypes()
  315. .Where(x => typeof(ISyncData).GetTypeInfo().IsAssignableFrom(x.GetTypeInfo()) && x.GetTypeInfo().IsClass && !x.GetTypeInfo().IsAbstract))
  316. .SelectMany(registerTypes => registerTypes.Select(registerType => (ISyncData)Activator.CreateInstance(registerType))).ToList();
  317. foreach (ISyncData syncData in syncDatas)
  318. {
  319. await syncData.SyncDataAsync(db, dbConfig, appConfig);
  320. }
  321. db.Aop.AuditValue -= SyncDataAuditValue;
  322. }
  323. Console.WriteLine($" sync data succeed{Environment.NewLine}");
  324. }
  325. catch (Exception ex)
  326. {
  327. throw new Exception($" sync data failed.\n{ex.Message}");
  328. }
  329. }
  330. /// <summary>
  331. /// 生成数据
  332. /// </summary>
  333. /// <param name="db"></param>
  334. /// <param name="appConfig"></param>
  335. /// <param name="dbConfig"></param>
  336. /// <returns></returns>
  337. /// <exception cref="Exception"></exception>
  338. public static async Task GenerateDataAsync(IFreeSql db, AppConfig appConfig = null, DbConfig dbConfig = null)
  339. {
  340. try
  341. {
  342. Console.WriteLine($"{Environment.NewLine} generate data started");
  343. if (dbConfig.AssemblyNames?.Length > 0)
  344. {
  345. Assembly[] assemblies = DependencyContext.Default.RuntimeLibraries
  346. .Where(a => dbConfig.AssemblyNames.Contains(a.Name))
  347. .Select(o => Assembly.Load(new AssemblyName(o.Name))).ToArray();
  348. List<IGenerateData> generateDatas = assemblies.Select(assembly => assembly.GetTypes()
  349. .Where(x => typeof(IGenerateData).GetTypeInfo().IsAssignableFrom(x.GetTypeInfo()) && x.GetTypeInfo().IsClass && !x.GetTypeInfo().IsAbstract))
  350. .SelectMany(registerTypes => registerTypes.Select(registerType => (IGenerateData)Activator.CreateInstance(registerType))).ToList();
  351. foreach (IGenerateData generateData in generateDatas)
  352. {
  353. await generateData.GenerateDataAsync(db, appConfig);
  354. }
  355. }
  356. Console.WriteLine($" generate data succeed{Environment.NewLine}");
  357. }
  358. catch (Exception ex)
  359. {
  360. throw new Exception($" generate data failed。\n{ex.Message}{Environment.NewLine}");
  361. }
  362. }
  363. /// <summary>
  364. /// 注册数据库
  365. /// </summary>
  366. /// <param name="freeSqlCloud"></param>
  367. /// <param name="user"></param>
  368. /// <param name="dbConfig"></param>
  369. /// <param name="appConfig"></param>
  370. /// <param name="hostAppOptions"></param>
  371. public static void RegisterDb(
  372. FreeSqlCloud freeSqlCloud,
  373. IUser user,
  374. DbConfig dbConfig,
  375. AppConfig appConfig,
  376. HostAppOptions hostAppOptions
  377. )
  378. {
  379. //注册数据库
  380. freeSqlCloud.Register(dbConfig.Key, () =>
  381. {
  382. //创建数据库
  383. if (dbConfig.CreateDb)
  384. {
  385. CreateDatabaseAsync(dbConfig).Wait();
  386. }
  387. var providerType = dbConfig.ProviderType.NotNull() ? Type.GetType(dbConfig.ProviderType) : null;
  388. var freeSqlBuilder = new FreeSqlBuilder()
  389. .UseConnectionString(dbConfig.Type, dbConfig.ConnectionString, providerType)
  390. .UseAutoSyncStructure(false)
  391. .UseLazyLoading(false)
  392. .UseNoneCommandParameter(true);
  393. if (dbConfig.SlaveList?.Length > 0)
  394. {
  395. var slaveList = dbConfig.SlaveList.Select(a => a.ConnectionString).ToArray();
  396. var slaveWeightList = dbConfig.SlaveList.Select(a => a.Weight).ToArray();
  397. freeSqlBuilder.UseSlave(slaveList).UseSlaveWeight(slaveWeightList);
  398. }
  399. hostAppOptions?.ConfigureFreeSqlBuilder?.Invoke(freeSqlBuilder);
  400. #region 监听所有命令
  401. if (dbConfig.MonitorCommand)
  402. {
  403. freeSqlBuilder.UseMonitorCommand(cmd => { }, (cmd, traceLog) =>
  404. {
  405. //Console.WriteLine($"{cmd.CommandText}\n{traceLog}{Environment.NewLine}");
  406. Console.WriteLine($"{cmd.CommandText}{Environment.NewLine}");
  407. });
  408. }
  409. #endregion 监听所有命令
  410. var fsql = freeSqlBuilder.Build();
  411. //生成数据
  412. if (dbConfig.GenerateData && !dbConfig.CreateDb && !dbConfig.SyncData)
  413. {
  414. GenerateDataAsync(fsql, appConfig, dbConfig).Wait();
  415. }
  416. //软删除过滤器
  417. fsql.GlobalFilter.ApplyOnly<IDelete>(FilterNames.Delete, a => a.IsDeleted == false);
  418. //租户过滤器
  419. if (appConfig.Tenant)
  420. {
  421. fsql.GlobalFilter.ApplyOnly<ITenant>(FilterNames.Tenant, a => a.TenantId == user.TenantId);
  422. }
  423. //会员过滤器
  424. fsql.GlobalFilter.ApplyOnly<IMember>(FilterNames.Member, a => a.MemberId == user.Id);
  425. //数据权限过滤器
  426. fsql.GlobalFilter.ApplyOnlyIf<IData>(FilterNames.Self,
  427. () =>
  428. {
  429. if (!(user?.Id > 0))
  430. return false;
  431. var dataPermission = user.DataPermission;
  432. if (user.Type == UserType.DefaultUser && dataPermission != null)
  433. return dataPermission.DataScope != DataScope.All && dataPermission.OrgIds.Count == 0;
  434. return false;
  435. },
  436. a => a.OwnerId == user.Id
  437. );
  438. fsql.GlobalFilter.ApplyOnlyIf<IData>(FilterNames.Data,
  439. () =>
  440. {
  441. if (!(user?.Id > 0))
  442. return false;
  443. var dataPermission = user.DataPermission;
  444. if (user.Type == UserType.DefaultUser && dataPermission != null)
  445. return dataPermission.DataScope != DataScope.All && dataPermission.OrgIds.Count > 0;
  446. return false;
  447. },
  448. a => a.OwnerId == user.Id || user.DataPermission.OrgIds.Contains(a.OwnerOrgId.Value)
  449. );
  450. //配置实体
  451. ConfigEntity(fsql, appConfig, dbConfig);
  452. hostAppOptions?.ConfigureFreeSql?.Invoke(fsql);
  453. #region 初始化数据库
  454. //同步结构
  455. if (dbConfig.SyncStructure)
  456. {
  457. SyncStructure(fsql, dbConfig: dbConfig, appConfig: appConfig);
  458. }
  459. #region 审计数据
  460. //计算服务器时间
  461. var serverTime = fsql.Ado.QuerySingle(() => DateTime.UtcNow);
  462. var timeOffset = DateTime.UtcNow.Subtract(serverTime);
  463. TimeOffset = timeOffset;
  464. fsql.Aop.AuditValue += (s, e) =>
  465. {
  466. AuditValue(e, timeOffset, user);
  467. };
  468. #endregion 审计数据
  469. //同步数据
  470. if (dbConfig.SyncData)
  471. {
  472. SyncDataAsync(fsql, dbConfig, appConfig).Wait();
  473. }
  474. #endregion 初始化数据库
  475. #region 监听Curd操作
  476. if (dbConfig.Curd)
  477. {
  478. fsql.Aop.CurdBefore += (s, e) =>
  479. {
  480. if (appConfig.MiniProfiler)
  481. {
  482. MiniProfiler.Current.CustomTiming("CurdBefore", e.Sql);
  483. }
  484. Console.WriteLine($"{e.Sql}{Environment.NewLine}");
  485. };
  486. fsql.Aop.CurdAfter += (s, e) =>
  487. {
  488. if (appConfig.MiniProfiler)
  489. {
  490. MiniProfiler.Current.CustomTiming("CurdAfter", $"{e.ElapsedMilliseconds}");
  491. }
  492. };
  493. }
  494. #endregion 监听Curd操作
  495. return fsql;
  496. });
  497. //执行注册数据库
  498. var fsql = freeSqlCloud.Use(dbConfig.Key);
  499. if (dbConfig.SyncStructure)
  500. {
  501. var _ = fsql.CodeFirst;
  502. }
  503. }
  504. }