DbHelper.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  1. using System;
  2. using System.IO;
  3. using System.Linq;
  4. using System.Threading.Tasks;
  5. using Newtonsoft.Json;
  6. using Newtonsoft.Json.Serialization;
  7. using FreeSql;
  8. using FreeSql.DataAnnotations;
  9. using Admin.Core.Common.Configs;
  10. using Admin.Core.Common.Helpers;
  11. using Admin.Core.Model.Admin;
  12. using System.Collections.Generic;
  13. using System.Reflection;
  14. using Admin.Core.Common.BaseModel;
  15. using Admin.Core.Service.Admin.Api.Output;
  16. using Admin.Core.Service.Admin.View.Output;
  17. using Admin.Core.Service.Admin.Permission.Output;
  18. using FreeSql.Aop;
  19. using Admin.Core.Common.Attributes;
  20. using Admin.Core.Common.Auth;
  21. using Yitter.IdGenerator;
  22. using Admin.Core.Common.Extensions;
  23. namespace Admin.Core.Db
  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 == FreeSql.Aop.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. if (data?.Length > 0)
  242. {
  243. var repo = db.GetRepository<T>();
  244. var insert = db.Insert<T>();
  245. if (unitOfWork != null)
  246. {
  247. repo.UnitOfWork = unitOfWork;
  248. insert = insert.WithTransaction(tran);
  249. }
  250. var isIdentity = CheckIdentity<T>();
  251. if (isIdentity)
  252. {
  253. if (dbConfig.Type == DataType.SqlServer)
  254. {
  255. var insrtSql = insert.AppendData(data).InsertIdentity().ToSql();
  256. await repo.Orm.Ado.ExecuteNonQueryAsync($"SET IDENTITY_INSERT {tableName} ON\n {insrtSql} \nSET IDENTITY_INSERT {tableName} OFF");
  257. }
  258. else
  259. {
  260. await insert.AppendData(data).InsertIdentity().ExecuteAffrowsAsync();
  261. }
  262. }
  263. else
  264. {
  265. repo.DbContextOptions.EnableAddOrUpdateNavigateList = true;
  266. await repo.InsertAsync(data);
  267. }
  268. Console.WriteLine($" table: {tableName} sync data succeed");
  269. }
  270. else
  271. {
  272. Console.WriteLine($" table: {tableName} import data []");
  273. }
  274. }
  275. else
  276. {
  277. Console.WriteLine($" table: {tableName} record already exists");
  278. }
  279. }
  280. catch (Exception ex)
  281. {
  282. Console.WriteLine($" table: {tableName} sync data failed.\n{ex.Message}");
  283. }
  284. }
  285. /// <summary>
  286. /// 同步数据审计方法
  287. /// </summary>
  288. /// <param name="s"></param>
  289. /// <param name="e"></param>
  290. private static void SyncDataAuditValue(object s, AuditValueEventArgs e)
  291. {
  292. var user = new { Id = 161223411986501, Name = "admin", TenantId = 161223412138053 };
  293. if (e.Property.GetCustomAttribute<ServerTimeAttribute>(false) != null
  294. && (e.Column.CsType == typeof(DateTime) || e.Column.CsType == typeof(DateTime?))
  295. && (e.Value == null || (DateTime)e.Value == default || (DateTime?)e.Value == default))
  296. {
  297. e.Value = DateTime.Now.Subtract(TimeOffset);
  298. }
  299. if (e.Column.CsType == typeof(long)
  300. && e.Property.GetCustomAttribute<SnowflakeAttribute>(false) != null
  301. && (e.Value == null || (long)e.Value == default || (long?)e.Value == default))
  302. {
  303. e.Value = YitIdHelper.NextId();
  304. }
  305. if (user == null || user.Id <= 0)
  306. {
  307. return;
  308. }
  309. if (e.AuditValueType == AuditValueType.Insert)
  310. {
  311. switch (e.Property.Name)
  312. {
  313. case "CreatedUserId":
  314. if (e.Value == null || (long)e.Value == default || (long?)e.Value == default)
  315. {
  316. e.Value = user.Id;
  317. }
  318. break;
  319. case "CreatedUserName":
  320. if (e.Value == null || ((string)e.Value).IsNull())
  321. {
  322. e.Value = user.Name;
  323. }
  324. break;
  325. case "TenantId":
  326. if (e.Value == null || (long)e.Value == default || (long?)e.Value == default)
  327. {
  328. e.Value = user.TenantId;
  329. }
  330. break;
  331. }
  332. }
  333. else if (e.AuditValueType == AuditValueType.Update)
  334. {
  335. switch (e.Property.Name)
  336. {
  337. case "ModifiedUserId":
  338. e.Value = user.Id;
  339. break;
  340. case "ModifiedUserName":
  341. e.Value = user.Name;
  342. break;
  343. }
  344. }
  345. }
  346. /// <summary>
  347. /// 同步数据
  348. /// </summary>
  349. /// <returns></returns>
  350. public static async Task SyncDataAsync(IFreeSql db, DbConfig dbConfig = null, AppConfig appConfig = null)
  351. {
  352. try
  353. {
  354. //db.Aop.CurdBefore += (s, e) =>
  355. //{
  356. // Console.WriteLine($"{e.Sql}\r\n");
  357. //};
  358. Console.WriteLine("\r\n sync data started");
  359. db.Aop.AuditValue += SyncDataAuditValue;
  360. var fileName = appConfig.Tenant ? "data-share.json" : "data.json";
  361. var filePath = Path.Combine(AppContext.BaseDirectory, $"Db/Data/{fileName}").ToPath();
  362. var jsonData = FileHelper.ReadFile(filePath);
  363. var data = JsonConvert.DeserializeObject<Data>(jsonData);
  364. using (var uow = db.CreateUnitOfWork())
  365. using (var tran = uow.GetOrBeginTransaction())
  366. {
  367. var dualRepo = db.GetRepository<DualEntity>();
  368. dualRepo.UnitOfWork = uow;
  369. if (!await dualRepo.Select.AnyAsync())
  370. {
  371. await dualRepo.InsertAsync(new DualEntity { });
  372. }
  373. //await InitDtDataAsync(db, uow, tran, data.Dictionaries, dbConfig);
  374. await InitDtDataAsync(db, uow, tran, data.ApiTree, dbConfig);
  375. await InitDtDataAsync(db, uow, tran, data.ViewTree, dbConfig);
  376. await InitDtDataAsync(db, uow, tran, data.PermissionTree, dbConfig);
  377. await InitDtDataAsync(db, uow, tran, data.Users, dbConfig);
  378. await InitDtDataAsync(db, uow, tran, data.Roles, dbConfig);
  379. await InitDtDataAsync(db, uow, tran, data.UserRoles, dbConfig);
  380. await InitDtDataAsync(db, uow, tran, data.RolePermissions, dbConfig);
  381. await InitDtDataAsync(db, uow, tran, data.Tenants, dbConfig);
  382. uow.Commit();
  383. }
  384. db.Aop.AuditValue -= SyncDataAuditValue;
  385. Console.WriteLine(" sync data succeed\r\n");
  386. }
  387. catch (Exception ex)
  388. {
  389. throw new Exception($" sync data failed.\n{ex.Message}");
  390. }
  391. }
  392. /// <summary>
  393. /// 生成极简数据
  394. /// </summary>
  395. /// <param name="db"></param>
  396. /// <returns></returns>
  397. public static async Task GenerateSimpleJsonDataAsync(IFreeSql db)
  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 users = await db.Queryable<UserEntity>().ToListAsync(a => new
  466. {
  467. a.TenantId,
  468. a.Id,
  469. a.UserName,
  470. a.Password,
  471. a.NickName,
  472. a.Avatar,
  473. a.Status,
  474. a.Remark
  475. });
  476. #endregion
  477. #region 角色
  478. var roles = await db.Queryable<RoleEntity>().ToListAsync(a => new
  479. {
  480. a.TenantId,
  481. a.Id,
  482. a.Name,
  483. a.Code,
  484. a.Sort,
  485. a.Description
  486. });
  487. #endregion
  488. #region 用户角色
  489. var userRoles = await db.Queryable<UserRoleEntity>().ToListAsync(a => new
  490. {
  491. a.Id,
  492. a.UserId,
  493. a.RoleId
  494. });
  495. #endregion
  496. #region 角色权限
  497. var rolePermissions = await db.Queryable<RolePermissionEntity>().ToListAsync(a => new
  498. {
  499. a.Id,
  500. a.RoleId,
  501. a.PermissionId
  502. });
  503. #endregion
  504. #region 租户
  505. var tenants = await db.Queryable<TenantEntity>().ToListAsync(a => new
  506. {
  507. a.TenantId,
  508. a.Id,
  509. a.UserId,
  510. a.RoleId,
  511. a.Name,
  512. a.Code,
  513. a.RealName,
  514. a.Phone,
  515. a.Email,
  516. a.TenantType,
  517. a.DbType,
  518. a.ConnectionString,
  519. a.IdleTime,
  520. a.Description
  521. });
  522. #endregion
  523. #endregion
  524. if (!(users?.Count > 0))
  525. {
  526. return;
  527. }
  528. #region 生成数据
  529. var settings = new JsonSerializerSettings();
  530. settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
  531. settings.NullValueHandling = NullValueHandling.Ignore;
  532. settings.DefaultValueHandling = DefaultValueHandling.Ignore;
  533. var jsonData = JsonConvert.SerializeObject(new
  534. {
  535. //dictionaries,
  536. apis,
  537. apiTree,
  538. viewTree,
  539. permissionTree,
  540. users,
  541. roles,
  542. userRoles,
  543. rolePermissions,
  544. tenants
  545. },
  546. //Formatting.Indented,
  547. settings
  548. );
  549. var filePath = Path.Combine(Directory.GetCurrentDirectory(), "Db/Data/data.json").ToPath();
  550. FileHelper.WriteFile(filePath, jsonData);
  551. #endregion
  552. Console.WriteLine(" generate data succeed\r\n");
  553. }
  554. catch (Exception ex)
  555. {
  556. throw new Exception($" generate data failed。\n{ex.Message}\r\n");
  557. }
  558. }
  559. }
  560. }