0
0

DbHelper.cs 23 KB

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