DbHelper.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  1. using ZhonTai.Common.Attributes;
  2. using ZhonTai.Common.Auth;
  3. using ZhonTai.Common.Domain.Entities;
  4. using ZhonTai.Common.Configs;
  5. using ZhonTai.Common.Extensions;
  6. using ZhonTai.Common.Helpers;
  7. using FreeSql;
  8. using FreeSql.Aop;
  9. using FreeSql.DataAnnotations;
  10. using Newtonsoft.Json;
  11. using Newtonsoft.Json.Serialization;
  12. using System;
  13. using System.Collections.Generic;
  14. using System.IO;
  15. using System.Linq;
  16. using System.Reflection;
  17. using System.Threading.Tasks;
  18. using Yitter.IdGenerator;
  19. using ZhonTai.Plate.Admin.Domain.DictionaryType;
  20. using ZhonTai.Plate.Admin.Domain.Dictionary;
  21. using ZhonTai.Plate.Admin.Domain.DictionaryType.Dtos;
  22. using ZhonTai.Plate.Admin.Domain.Dictionary.Dtos;
  23. using ZhonTai.Plate.Admin.Domain.Dual;
  24. using ZhonTai.Plate.Admin.Domain.Api;
  25. using ZhonTai.Plate.Admin.Domain.Api.Dtos;
  26. using ZhonTai.Plate.Admin.Domain.View.Dtos;
  27. using ZhonTai.Plate.Admin.Domain.Permission.Dtos;
  28. using ZhonTai.Plate.Admin.Domain.Permission;
  29. using ZhonTai.Plate.Admin.Domain.User;
  30. using ZhonTai.Plate.Admin.Domain.User.Dtos;
  31. using ZhonTai.Plate.Admin.Domain.Role;
  32. using ZhonTai.Plate.Admin.Domain.Role.Dtos;
  33. using ZhonTai.Plate.Admin.Domain.UserRole;
  34. using ZhonTai.Plate.Admin.Domain.RolePermission;
  35. using ZhonTai.Plate.Admin.Domain.Tenant;
  36. using ZhonTai.Plate.Admin.Domain.TenantPermission;
  37. using ZhonTai.Plate.Admin.Domain.PermissionApi;
  38. using ZhonTai.Plate.Admin.Domain.View;
  39. namespace ZhonTai.Plate.Admin.Repository
  40. {
  41. public class DbHelper
  42. {
  43. /// <summary>
  44. /// 偏移时间
  45. /// </summary>
  46. public static TimeSpan TimeOffset;
  47. /// <summary>
  48. /// 创建数据库
  49. /// </summary>
  50. /// <param name="dbConfig"></param>
  51. /// <returns></returns>
  52. public async static Task CreateDatabaseAsync(DbConfig dbConfig)
  53. {
  54. if (!dbConfig.CreateDb || dbConfig.Type == DataType.Sqlite)
  55. {
  56. return;
  57. }
  58. var db = new FreeSqlBuilder()
  59. .UseConnectionString(dbConfig.Type, dbConfig.CreateDbConnectionString)
  60. .Build();
  61. try
  62. {
  63. Console.WriteLine("\r\n create database started");
  64. await db.Ado.ExecuteNonQueryAsync(dbConfig.CreateDbSql);
  65. Console.WriteLine(" create database succeed");
  66. }
  67. catch (Exception e)
  68. {
  69. Console.WriteLine($" create database failed.\n {e.Message}");
  70. }
  71. }
  72. /// <summary>
  73. /// 获得指定程序集表实体
  74. /// </summary>
  75. /// <returns></returns>
  76. public static Type[] GetEntityTypes()
  77. {
  78. List<string> assemblyNames = new List<string>()
  79. {
  80. "ZhonTai.Plate.Admin.Domain"
  81. };
  82. List<Type> entityTypes = new List<Type>();
  83. foreach (var assemblyName in assemblyNames)
  84. {
  85. foreach (Type type in Assembly.Load(assemblyName).GetExportedTypes())
  86. {
  87. foreach (Attribute attribute in type.GetCustomAttributes())
  88. {
  89. if (attribute is TableAttribute tableAttribute)
  90. {
  91. if (tableAttribute.DisableSyncStructure == false)
  92. {
  93. entityTypes.Add(type);
  94. }
  95. }
  96. }
  97. }
  98. }
  99. return entityTypes.ToArray();
  100. }
  101. /// <summary>
  102. /// 配置实体
  103. /// </summary>
  104. public static void ConfigEntity(IFreeSql db, AppConfig appConfig = null)
  105. {
  106. //租户生成和操作租户Id
  107. if (!appConfig.Tenant)
  108. {
  109. var iTenant = nameof(ITenant);
  110. var tenantId = nameof(ITenant.TenantId);
  111. //获得指定程序集表实体
  112. var entityTypes = GetEntityTypes();
  113. foreach (var entityType in entityTypes)
  114. {
  115. if (entityType.GetInterfaces().Any(a => a.Name == iTenant))
  116. {
  117. db.CodeFirst.Entity(entityType, a =>
  118. {
  119. a.Ignore(tenantId);
  120. });
  121. }
  122. }
  123. }
  124. }
  125. /// <summary>
  126. /// 审计数据
  127. /// </summary>
  128. /// <param name="e"></param>
  129. /// <param name="timeOffset"></param>
  130. /// <param name="user"></param>
  131. public static void AuditValue(AuditValueEventArgs e, TimeSpan timeOffset, IUser user)
  132. {
  133. if (e.Property.GetCustomAttribute<ServerTimeAttribute>(false) != null
  134. && (e.Column.CsType == typeof(DateTime) || e.Column.CsType == typeof(DateTime?))
  135. && (e.Value == null || (DateTime)e.Value == default || (DateTime?)e.Value == default))
  136. {
  137. e.Value = DateTime.Now.Subtract(timeOffset);
  138. }
  139. if (e.Column.CsType == typeof(long)
  140. && e.Property.GetCustomAttribute<SnowflakeAttribute>(false) is SnowflakeAttribute snowflakeAttribute
  141. && snowflakeAttribute.Enable && (e.Value == null || (long)e.Value == default || (long?)e.Value == default))
  142. {
  143. e.Value = YitIdHelper.NextId();
  144. }
  145. if (user == null || user.Id <= 0)
  146. {
  147. return;
  148. }
  149. if (e.AuditValueType == AuditValueType.Insert)
  150. {
  151. switch (e.Property.Name)
  152. {
  153. case "CreatedUserId":
  154. if (e.Value == null || (long)e.Value == default || (long?)e.Value == default)
  155. {
  156. e.Value = user.Id;
  157. }
  158. break;
  159. case "CreatedUserName":
  160. if (e.Value == null || ((string)e.Value).IsNull())
  161. {
  162. e.Value = user.Name;
  163. }
  164. break;
  165. case "TenantId":
  166. if (e.Value == null || (long)e.Value == default || (long?)e.Value == default)
  167. {
  168. e.Value = user.TenantId;
  169. }
  170. break;
  171. }
  172. }
  173. else if (e.AuditValueType == AuditValueType.Update)
  174. {
  175. switch (e.Property.Name)
  176. {
  177. case "ModifiedUserId":
  178. e.Value = user.Id;
  179. break;
  180. case "ModifiedUserName":
  181. e.Value = user.Name;
  182. break;
  183. }
  184. }
  185. }
  186. /// <summary>
  187. /// 同步结构
  188. /// </summary>
  189. public static void SyncStructure(IFreeSql db, string msg = null, DbConfig dbConfig = null, AppConfig appConfig = null)
  190. {
  191. //打印结构比对脚本
  192. //var dDL = db.CodeFirst.GetComparisonDDLStatements<PermissionEntity>();
  193. //Console.WriteLine("\r\n " + dDL);
  194. //打印结构同步脚本
  195. //db.Aop.SyncStructureAfter += (s, e) =>
  196. //{
  197. // if (e.Sql.NotNull())
  198. // {
  199. // Console.WriteLine(" sync structure sql:\n" + e.Sql);
  200. // }
  201. //};
  202. // 同步结构
  203. var dbType = dbConfig.Type.ToString();
  204. Console.WriteLine($"\r\n {(msg.NotNull() ? msg : $"sync {dbType} structure")} started");
  205. if (dbConfig.Type == DataType.Oracle)
  206. {
  207. db.CodeFirst.IsSyncStructureToUpper = true;
  208. }
  209. //获得指定程序集表实体
  210. var entityTypes = GetEntityTypes();
  211. db.CodeFirst.SyncStructure(entityTypes);
  212. Console.WriteLine($" {(msg.NotNull() ? msg : $"sync {dbType} structure")} succeed");
  213. }
  214. /// <summary>
  215. /// 检查实体属性是否为自增长
  216. /// </summary>
  217. /// <typeparam name="T"></typeparam>
  218. /// <returns></returns>
  219. private static bool CheckIdentity<T>() where T : class
  220. {
  221. var isIdentity = false;
  222. var properties = typeof(T).GetProperties();
  223. foreach (var property in properties)
  224. {
  225. if (property.GetCustomAttributes(typeof(ColumnAttribute), false).FirstOrDefault() is ColumnAttribute columnAttribute && columnAttribute.IsIdentity)
  226. {
  227. isIdentity = true;
  228. break;
  229. }
  230. }
  231. return isIdentity;
  232. }
  233. /// <summary>
  234. /// 初始化数据表数据
  235. /// </summary>
  236. /// <typeparam name="T"></typeparam>
  237. /// <param name="db"></param>
  238. /// <param name="unitOfWork"></param>
  239. /// <param name="tran"></param>
  240. /// <param name="data"></param>
  241. /// <param name="dbConfig"></param>
  242. /// <returns></returns>
  243. private static async Task InitDtDataAsync<T>(
  244. IFreeSql db,
  245. IUnitOfWork unitOfWork,
  246. System.Data.Common.DbTransaction tran,
  247. T[] data,
  248. DbConfig dbConfig = null
  249. ) where T : class, new()
  250. {
  251. var table = typeof(T).GetCustomAttributes(typeof(TableAttribute), false).FirstOrDefault() as TableAttribute;
  252. var tableName = table.Name;
  253. try
  254. {
  255. if (await db.Queryable<T>().AnyAsync())
  256. {
  257. Console.WriteLine($" table: {tableName} record already exists");
  258. return;
  259. }
  260. if (!(data?.Length > 0))
  261. {
  262. Console.WriteLine($" table: {tableName} import data []");
  263. return;
  264. }
  265. var repo = db.GetRepositoryBase<T>();
  266. var insert = db.Insert<T>();
  267. if (unitOfWork != null)
  268. {
  269. repo.UnitOfWork = unitOfWork;
  270. insert = insert.WithTransaction(tran);
  271. }
  272. var isIdentity = CheckIdentity<T>();
  273. if (isIdentity)
  274. {
  275. if (dbConfig.Type == DataType.SqlServer)
  276. {
  277. var insrtSql = insert.AppendData(data).InsertIdentity().ToSql();
  278. await repo.Orm.Ado.ExecuteNonQueryAsync($"SET IDENTITY_INSERT {tableName} ON\n {insrtSql} \nSET IDENTITY_INSERT {tableName} OFF");
  279. }
  280. else
  281. {
  282. await insert.AppendData(data).InsertIdentity().ExecuteAffrowsAsync();
  283. }
  284. }
  285. else
  286. {
  287. repo.DbContextOptions.EnableAddOrUpdateNavigateList = true;
  288. await repo.InsertAsync(data);
  289. }
  290. Console.WriteLine($" table: {tableName} sync data succeed");
  291. }
  292. catch (Exception ex)
  293. {
  294. Console.WriteLine($" table: {tableName} sync data failed.\n{ex.Message}");
  295. }
  296. }
  297. /// <summary>
  298. /// 同步数据审计方法
  299. /// </summary>
  300. /// <param name="s"></param>
  301. /// <param name="e"></param>
  302. private static void SyncDataAuditValue(object s, AuditValueEventArgs e)
  303. {
  304. var user = new { Id = 161223411986501, Name = "admin", TenantId = 161223412138053 };
  305. if (e.Property.GetCustomAttribute<ServerTimeAttribute>(false) != null
  306. && (e.Column.CsType == typeof(DateTime) || e.Column.CsType == typeof(DateTime?))
  307. && (e.Value == null || (DateTime)e.Value == default || (DateTime?)e.Value == default))
  308. {
  309. e.Value = DateTime.Now.Subtract(TimeOffset);
  310. }
  311. if (e.Column.CsType == typeof(long)
  312. && e.Property.GetCustomAttribute<SnowflakeAttribute>(false) != null
  313. && (e.Value == null || (long)e.Value == default || (long?)e.Value == default))
  314. {
  315. e.Value = YitIdHelper.NextId();
  316. }
  317. if (user == null || user.Id <= 0)
  318. {
  319. return;
  320. }
  321. if (e.AuditValueType == AuditValueType.Insert)
  322. {
  323. switch (e.Property.Name)
  324. {
  325. case "CreatedUserId":
  326. if (e.Value == null || (long)e.Value == default || (long?)e.Value == default)
  327. {
  328. e.Value = user.Id;
  329. }
  330. break;
  331. case "CreatedUserName":
  332. if (e.Value == null || ((string)e.Value).IsNull())
  333. {
  334. e.Value = user.Name;
  335. }
  336. break;
  337. case "TenantId":
  338. if (e.Value == null || (long)e.Value == default || (long?)e.Value == default)
  339. {
  340. e.Value = user.TenantId;
  341. }
  342. break;
  343. }
  344. }
  345. else if (e.AuditValueType == AuditValueType.Update)
  346. {
  347. switch (e.Property.Name)
  348. {
  349. case "ModifiedUserId":
  350. e.Value = user.Id;
  351. break;
  352. case "ModifiedUserName":
  353. e.Value = user.Name;
  354. break;
  355. }
  356. }
  357. }
  358. /// <summary>
  359. /// 同步数据
  360. /// </summary>
  361. /// <returns></returns>
  362. public static async Task SyncDataAsync(IFreeSql db, DbConfig dbConfig = null, AppConfig appConfig = null)
  363. {
  364. try
  365. {
  366. //db.Aop.CurdBefore += (s, e) =>
  367. //{
  368. // Console.WriteLine($"{e.Sql}\r\n");
  369. //};
  370. Console.WriteLine("\r\n sync data started");
  371. db.Aop.AuditValue += SyncDataAuditValue;
  372. var fileName = appConfig.Tenant ? "data-share.json" : "data.json";
  373. var filePath = Path.Combine(AppContext.BaseDirectory, $"Db/Data/{fileName}").ToPath();
  374. var jsonData = FileHelper.ReadFile(filePath);
  375. var data = JsonConvert.DeserializeObject<Data>(jsonData);
  376. using (var uow = db.CreateUnitOfWork())
  377. using (var tran = uow.GetOrBeginTransaction())
  378. {
  379. var dualRepo = db.GetRepositoryBase<DualEntity>();
  380. dualRepo.UnitOfWork = uow;
  381. if (!await dualRepo.Select.AnyAsync())
  382. {
  383. await dualRepo.InsertAsync(new DualEntity { });
  384. }
  385. //admin
  386. await InitDtDataAsync(db, uow, tran, data.DictionaryTypes, dbConfig);
  387. await InitDtDataAsync(db, uow, tran, data.Dictionaries, dbConfig);
  388. await InitDtDataAsync(db, uow, tran, data.ApiTree, dbConfig);
  389. await InitDtDataAsync(db, uow, tran, data.ViewTree, dbConfig);
  390. await InitDtDataAsync(db, uow, tran, data.PermissionTree, dbConfig);
  391. await InitDtDataAsync(db, uow, tran, data.Users, dbConfig);
  392. await InitDtDataAsync(db, uow, tran, data.Roles, dbConfig);
  393. await InitDtDataAsync(db, uow, tran, data.UserRoles, dbConfig);
  394. await InitDtDataAsync(db, uow, tran, data.RolePermissions, dbConfig);
  395. await InitDtDataAsync(db, uow, tran, data.Tenants, dbConfig);
  396. await InitDtDataAsync(db, uow, tran, data.TenantPermissions, dbConfig);
  397. await InitDtDataAsync(db, uow, tran, data.PermissionApis, dbConfig);
  398. uow.Commit();
  399. }
  400. db.Aop.AuditValue -= SyncDataAuditValue;
  401. Console.WriteLine(" sync data succeed\r\n");
  402. }
  403. catch (Exception ex)
  404. {
  405. throw new Exception($" sync data failed.\n{ex.Message}");
  406. }
  407. }
  408. /// <summary>
  409. /// 生成极简数据
  410. /// </summary>
  411. /// <param name="db"></param>
  412. /// <param name="appConfig"></param>
  413. /// <returns></returns>
  414. public static async Task GenerateSimpleJsonDataAsync(IFreeSql db, AppConfig appConfig = null)
  415. {
  416. try
  417. {
  418. Console.WriteLine("\r\n generate data started");
  419. #region 数据表
  420. //admin
  421. #region 数据字典
  422. var dictionaryTypes = await db.Queryable<DictionaryTypeEntity>().ToListAsync<DictionaryTypeDataOutput>();
  423. var dictionaries = await db.Queryable<DictionaryEntity>().ToListAsync<DictionaryDataOutput>();
  424. #endregion
  425. #region 接口
  426. var apis = await db.Queryable<ApiEntity>().ToListAsync<ApiDataOutput>();
  427. var apiTree = apis.ToTree((r, c) =>
  428. {
  429. return c.ParentId == 0;
  430. },
  431. (r, c) =>
  432. {
  433. return r.Id == c.ParentId;
  434. },
  435. (r, datalist) =>
  436. {
  437. r.Childs ??= new List<ApiDataOutput>();
  438. r.Childs.AddRange(datalist);
  439. });
  440. #endregion
  441. #region 视图
  442. var views = await db.Queryable<ViewEntity>().ToListAsync<ViewDataOutput>();
  443. var viewTree = views.ToTree((r, c) =>
  444. {
  445. return c.ParentId == 0;
  446. },
  447. (r, c) =>
  448. {
  449. return r.Id == c.ParentId;
  450. },
  451. (r, datalist) =>
  452. {
  453. r.Childs ??= new List<ViewDataOutput>();
  454. r.Childs.AddRange(datalist);
  455. });
  456. #endregion
  457. #region 权限
  458. var permissions = await db.Queryable<PermissionEntity>().ToListAsync<PermissionDataOutput>();
  459. var permissionTree = permissions.ToTree((r, c) =>
  460. {
  461. return c.ParentId == 0;
  462. },
  463. (r, c) =>
  464. {
  465. return r.Id == c.ParentId;
  466. },
  467. (r, datalist) =>
  468. {
  469. r.Childs ??= new List<PermissionDataOutput>();
  470. r.Childs.AddRange(datalist);
  471. });
  472. #endregion
  473. #region 用户
  474. var users = await db.Queryable<UserEntity>().ToListAsync<UserDataOutput>();
  475. #endregion
  476. #region 角色
  477. var roles = await db.Queryable<RoleEntity>().ToListAsync<RoleDataOutput>();
  478. #endregion
  479. #region 用户角色
  480. var userRoles = await db.Queryable<UserRoleEntity>().ToListAsync(a => new
  481. {
  482. a.Id,
  483. a.UserId,
  484. a.RoleId
  485. });
  486. #endregion
  487. #region 角色权限
  488. var rolePermissions = await db.Queryable<RolePermissionEntity>().ToListAsync(a => new
  489. {
  490. a.Id,
  491. a.RoleId,
  492. a.PermissionId
  493. });
  494. #endregion
  495. #region 租户
  496. var tenants = await db.Queryable<TenantEntity>().ToListAsync(a => new
  497. {
  498. a.Id,
  499. a.UserId,
  500. a.RoleId,
  501. a.Name,
  502. a.Code,
  503. a.RealName,
  504. a.Phone,
  505. a.Email,
  506. a.TenantType,
  507. a.DataIsolationType,
  508. a.DbType,
  509. a.ConnectionString,
  510. a.IdleTime,
  511. a.Description
  512. });
  513. #endregion
  514. #region 租户权限
  515. var tenantPermissions = await db.Queryable<TenantPermissionEntity>().ToListAsync(a => new
  516. {
  517. a.Id,
  518. a.TenantId,
  519. a.PermissionId
  520. });
  521. #endregion
  522. #region 权限接口
  523. var permissionApis = await db.Queryable<PermissionApiEntity>().ToListAsync(a => new
  524. {
  525. a.Id,
  526. a.PermissionId,
  527. a.ApiId
  528. });
  529. #endregion
  530. #endregion
  531. if (!(users?.Count > 0))
  532. {
  533. return;
  534. }
  535. #region 生成数据
  536. var settings = new JsonSerializerSettings();
  537. settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
  538. settings.NullValueHandling = NullValueHandling.Ignore;
  539. settings.DefaultValueHandling = DefaultValueHandling.Ignore;
  540. var jsonData = JsonConvert.SerializeObject(new
  541. {
  542. dictionaries,
  543. dictionaryTypes,
  544. apis,
  545. apiTree,
  546. viewTree,
  547. permissionTree,
  548. users,
  549. roles,
  550. userRoles,
  551. rolePermissions,
  552. tenants,
  553. tenantPermissions,
  554. permissionApis
  555. },
  556. //Formatting.Indented,
  557. settings
  558. );
  559. var isTenant = appConfig.Tenant;
  560. var fileName = isTenant ? "data-share.json" : "data.json";
  561. var filePath = Path.Combine(Directory.GetCurrentDirectory(), $"Db/Data/{fileName}").ToPath();
  562. FileHelper.WriteFile(filePath, jsonData);
  563. if (isTenant)
  564. {
  565. var tenantId = tenants.Where(a => a.Code.ToLower() == "zhontai").FirstOrDefault().Id;
  566. jsonData = JsonConvert.SerializeObject(new
  567. {
  568. dictionaries = dictionaries.Where(a=>a.TenantId == tenantId),
  569. dictionaryTypes = dictionaryTypes.Where(a => a.TenantId == tenantId),
  570. apis,
  571. apiTree,
  572. viewTree,
  573. permissionTree,
  574. users = users.Where(a => a.TenantId == tenantId),
  575. roles = roles.Where(a => a.TenantId == tenantId),
  576. userRoles,
  577. rolePermissions,
  578. tenants,
  579. tenantPermissions,
  580. permissionApis
  581. },
  582. settings
  583. );
  584. filePath = Path.Combine(Directory.GetCurrentDirectory(), "Db/Data/data.json").ToPath();
  585. FileHelper.WriteFile(filePath, jsonData);
  586. }
  587. #endregion
  588. Console.WriteLine(" generate data succeed\r\n");
  589. }
  590. catch (Exception ex)
  591. {
  592. throw new Exception($" generate data failed。\n{ex.Message}\r\n");
  593. }
  594. }
  595. }
  596. }