DbHelper.cs 21 KB

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