DbHelper.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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.Aop;
  9. using FreeSql.DataAnnotations;
  10. using Admin.Core.Common.Configs;
  11. using Admin.Core.Common.Helpers;
  12. using Admin.Core.Model.Admin;
  13. using System.Collections.Generic;
  14. using System.Reflection;
  15. using Admin.Core.Common.BaseModel;
  16. namespace Admin.Core.Db
  17. {
  18. public class DbHelper
  19. {
  20. /// <summary>
  21. /// 创建数据库
  22. /// </summary>
  23. /// <param name="dbConfig"></param>
  24. /// <returns></returns>
  25. public async static Task CreateDatabaseAsync(DbConfig dbConfig)
  26. {
  27. if (!dbConfig.CreateDb || dbConfig.Type == DataType.Sqlite)
  28. {
  29. return;
  30. }
  31. var db = new FreeSqlBuilder()
  32. .UseConnectionString(dbConfig.Type, dbConfig.CreateDbConnectionString)
  33. .Build();
  34. try
  35. {
  36. Console.WriteLine("\r\n create database started");
  37. await db.Ado.ExecuteNonQueryAsync(dbConfig.CreateDbSql);
  38. Console.WriteLine(" create database succeed");
  39. }
  40. catch (Exception e)
  41. {
  42. Console.WriteLine($" create database failed.\n {e.Message}");
  43. }
  44. }
  45. /// <summary>
  46. /// 获得指定程序集表实体
  47. /// </summary>
  48. /// <returns></returns>
  49. public static Type[] GetEntityTypes()
  50. {
  51. List<string> assemblyNames = new List<string>()
  52. {
  53. "Admin.Core.Model"
  54. };
  55. List<Type> entityTypes = new List<Type>();
  56. foreach (var assemblyName in assemblyNames)
  57. {
  58. foreach (Type type in Assembly.Load(assemblyName).GetExportedTypes())
  59. {
  60. foreach (Attribute attribute in type.GetCustomAttributes())
  61. {
  62. if (attribute is TableAttribute tableAttribute)
  63. {
  64. if (tableAttribute.DisableSyncStructure == false)
  65. {
  66. entityTypes.Add(type);
  67. }
  68. }
  69. }
  70. }
  71. }
  72. return entityTypes.ToArray();
  73. }
  74. /// <summary>
  75. /// 同步结构
  76. /// </summary>
  77. public static void SyncStructure(IFreeSql db, string msg = null, DbConfig dbConfig = null, AppConfig appConfig = null)
  78. {
  79. //打印结构比对脚本
  80. //var dDL = db.CodeFirst.GetComparisonDDLStatements<PermissionEntity>();
  81. //Console.WriteLine("\r\n " + dDL);
  82. //打印结构同步脚本
  83. //db.Aop.SyncStructureAfter += (s, e) =>
  84. //{
  85. // if (e.Sql.NotNull())
  86. // {
  87. // Console.WriteLine(" sync structure sql:\n" + e.Sql);
  88. // }
  89. //};
  90. // 同步结构
  91. var dbType = dbConfig.Type.ToString();
  92. Console.WriteLine($"\r\n {(msg.NotNull() ? msg : $"sync {dbType} structure")} started");
  93. if(dbConfig.Type == DataType.Oracle)
  94. {
  95. db.CodeFirst.IsSyncStructureToUpper = true;
  96. }
  97. //获得指定程序集表实体
  98. var entityTypes = GetEntityTypes();
  99. //非共享数据库实体配置,不生成租户Id
  100. if(appConfig.TenantType != TenantType.Share)
  101. {
  102. var iTenant = nameof(ITenant);
  103. var tenantId = nameof(ITenant.TenantId);
  104. foreach (var entityType in entityTypes)
  105. {
  106. if(entityType.GetInterfaces().Any(a=> a.Name == iTenant))
  107. {
  108. db.CodeFirst.Entity(entityType, a =>
  109. {
  110. a.Ignore(tenantId);
  111. });
  112. }
  113. }
  114. }
  115. db.CodeFirst.SyncStructure(entityTypes);
  116. Console.WriteLine($" {(msg.NotNull() ? msg : $"sync {dbType} structure")} succeed");
  117. }
  118. /// <summary>
  119. /// 检查实体属性是否为自增长
  120. /// </summary>
  121. /// <typeparam name="T"></typeparam>
  122. /// <returns></returns>
  123. private static bool CheckIdentity<T>() where T : class
  124. {
  125. var isIdentity = false;
  126. var properties = typeof(T).GetProperties();
  127. foreach (var property in properties)
  128. {
  129. if (property.GetCustomAttributes(typeof(ColumnAttribute), false).FirstOrDefault() is ColumnAttribute columnAttribute && columnAttribute.IsIdentity)
  130. {
  131. isIdentity = true;
  132. break;
  133. }
  134. }
  135. return isIdentity;
  136. }
  137. /// <summary>
  138. /// 初始化数据表数据
  139. /// </summary>
  140. /// <typeparam name="T"></typeparam>
  141. /// <param name="db"></param>
  142. /// <param name="data"></param>
  143. /// <param name="tran"></param>
  144. /// <param name="dbConfig"></param>
  145. /// <returns></returns>
  146. private static async Task InitDtDataAsync<T>(
  147. IFreeSql db,
  148. T[] data,
  149. System.Data.Common.DbTransaction tran,
  150. DbConfig dbConfig = null
  151. ) where T : class
  152. {
  153. var table = typeof(T).GetCustomAttributes(typeof(TableAttribute),false).FirstOrDefault() as TableAttribute;
  154. var tableName = table.Name;
  155. try
  156. {
  157. if (!await db.Queryable<T>().AnyAsync())
  158. {
  159. if (data?.Length > 0)
  160. {
  161. var insert = db.Insert<T>();
  162. if(tran != null)
  163. {
  164. insert = insert.WithTransaction(tran);
  165. }
  166. var isIdentity = CheckIdentity<T>();
  167. if (isIdentity)
  168. {
  169. if (dbConfig.Type == DataType.SqlServer)
  170. {
  171. var insrtSql = insert.AppendData(data).InsertIdentity().ToSql();
  172. await db.Ado.ExecuteNonQueryAsync($"SET IDENTITY_INSERT {tableName} ON\n {insrtSql} \nSET IDENTITY_INSERT {tableName} OFF");
  173. }
  174. else
  175. {
  176. await insert.AppendData(data).InsertIdentity().ExecuteAffrowsAsync();
  177. }
  178. }
  179. else
  180. {
  181. await insert.AppendData(data).ExecuteAffrowsAsync();
  182. }
  183. Console.WriteLine($" table: {tableName} sync data succeed");
  184. }
  185. else
  186. {
  187. Console.WriteLine($" table: {tableName} import data []");
  188. }
  189. }
  190. else
  191. {
  192. Console.WriteLine($" table: {tableName} record already exists");
  193. }
  194. }
  195. catch (Exception ex)
  196. {
  197. Console.WriteLine($" table: {tableName} sync data failed.\n{ex.Message}");
  198. }
  199. }
  200. /// <summary>
  201. /// 同步数据审计方法
  202. /// </summary>
  203. /// <param name="s"></param>
  204. /// <param name="e"></param>
  205. private static void SyncDataAuditValue(object s, AuditValueEventArgs e)
  206. {
  207. if (e.AuditValueType == AuditValueType.Insert)
  208. {
  209. switch (e.Property.Name)
  210. {
  211. case "CreatedUserId":
  212. e.Value = 2;
  213. break;
  214. case "CreatedUserName":
  215. e.Value = "admin";
  216. break;
  217. }
  218. }
  219. else if (e.AuditValueType == AuditValueType.Update)
  220. {
  221. switch (e.Property.Name)
  222. {
  223. case "ModifiedUserId":
  224. e.Value = 2;
  225. break;
  226. case "ModifiedUserName":
  227. e.Value = "admin";
  228. break;
  229. }
  230. }
  231. }
  232. /// <summary>
  233. /// 同步数据
  234. /// </summary>
  235. /// <returns></returns>
  236. public static async Task SyncDataAsync(IFreeSql db, DbConfig dbConfig = null)
  237. {
  238. try
  239. {
  240. //db.Aop.CurdBefore += (s, e) =>
  241. //{
  242. // Console.WriteLine($"{e.Sql}\r\n");
  243. //};
  244. Console.WriteLine("\r\n sync data started");
  245. db.Aop.AuditValue += SyncDataAuditValue;
  246. var filePath = Path.Combine(AppContext.BaseDirectory, "Db/Data/data.json").ToPath();
  247. var jsonData = FileHelper.ReadFile(filePath);
  248. var data = JsonConvert.DeserializeObject<Data>(jsonData);
  249. using (var uow = db.CreateUnitOfWork())
  250. using (var tran = uow.GetOrBeginTransaction())
  251. {
  252. await InitDtDataAsync(db, data.Dictionaries, tran, dbConfig);
  253. await InitDtDataAsync(db, data.Apis, tran, dbConfig);
  254. await InitDtDataAsync(db, data.Views, tran, dbConfig);
  255. await InitDtDataAsync(db, data.Permissions, tran, dbConfig);
  256. await InitDtDataAsync(db, data.Users, tran, dbConfig);
  257. await InitDtDataAsync(db, data.Roles, tran, dbConfig);
  258. await InitDtDataAsync(db, data.UserRoles, tran, dbConfig);
  259. await InitDtDataAsync(db, data.RolePermissions, tran, dbConfig);
  260. await InitDtDataAsync(db, data.Tenants, tran, dbConfig);
  261. uow.Commit();
  262. }
  263. db.Aop.AuditValue -= SyncDataAuditValue;
  264. Console.WriteLine(" sync data succeed");
  265. }
  266. catch (Exception ex)
  267. {
  268. throw new Exception($" sync data failed.\n{ex.Message}");
  269. }
  270. }
  271. /// <summary>
  272. /// 生成极简数据
  273. /// </summary>
  274. /// <param name="db"></param>
  275. /// <returns></returns>
  276. public static async Task GenerateSimpleJsonDataAsync(IFreeSql db)
  277. {
  278. try
  279. {
  280. Console.WriteLine("\r\n generate data started");
  281. #region 数据表
  282. #region 数据字典
  283. var dictionaries = await db.Queryable<DictionaryEntity>().ToListAsync(a => new
  284. {
  285. a.Id,
  286. a.ParentId,
  287. a.Name,
  288. a.Code,
  289. a.Value,
  290. a.Description,
  291. a.Sort
  292. });
  293. #endregion
  294. #region 接口
  295. var apis = await db.Queryable<ApiEntity>().ToListAsync(a => new
  296. {
  297. a.Id,
  298. a.ParentId,
  299. a.Name,
  300. a.Label,
  301. a.Path,
  302. a.HttpMethods,
  303. a.Description,
  304. a.Sort
  305. });
  306. #endregion
  307. #region 视图
  308. var views = await db.Queryable<ViewEntity>().ToListAsync(a => new
  309. {
  310. a.Id,
  311. a.ParentId,
  312. a.Name,
  313. a.Label,
  314. a.Path,
  315. a.Description,
  316. a.Sort
  317. });
  318. #endregion
  319. #region 权限
  320. var permissions = await db.Queryable<PermissionEntity>().ToListAsync(a => new
  321. {
  322. a.Id,
  323. a.ParentId,
  324. a.Label,
  325. a.Code,
  326. a.Type,
  327. a.ViewId,
  328. a.ApiId,
  329. a.Path,
  330. a.Icon,
  331. a.Closable,
  332. a.Opened,
  333. a.NewWindow,
  334. a.External,
  335. a.Sort,
  336. a.Description
  337. });
  338. #endregion
  339. #region 用户
  340. var users = await db.Queryable<UserEntity>().ToListAsync(a => new
  341. {
  342. a.Id,
  343. a.UserName,
  344. a.Password,
  345. a.NickName,
  346. a.Avatar,
  347. a.Status,
  348. a.Remark
  349. });
  350. #endregion
  351. #region 角色
  352. var roles = await db.Queryable<RoleEntity>().ToListAsync(a => new
  353. {
  354. a.Id,
  355. a.Name,
  356. a.Sort,
  357. a.Description
  358. });
  359. #endregion
  360. #region 用户角色
  361. var userRoles = await db.Queryable<UserRoleEntity>().ToListAsync(a => new
  362. {
  363. a.Id,
  364. a.UserId,
  365. a.RoleId
  366. });
  367. #endregion
  368. #region 角色权限
  369. var rolePermissions = await db.Queryable<RolePermissionEntity>().ToListAsync(a => new
  370. {
  371. a.Id,
  372. a.RoleId,
  373. a.PermissionId
  374. });
  375. #endregion
  376. #region 租户
  377. var tenants = await db.Queryable<TenantEntity>().ToListAsync(a => new
  378. {
  379. a.Id,
  380. a.Name,
  381. a.Code,
  382. a.DbType,
  383. a.ConnectionString,
  384. a.IdleTime,
  385. a.Description
  386. });
  387. #endregion
  388. #endregion
  389. if (!(users?.Count > 0))
  390. {
  391. return;
  392. }
  393. #region 生成数据
  394. var settings = new JsonSerializerSettings();
  395. settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
  396. settings.NullValueHandling = NullValueHandling.Ignore;
  397. settings.DefaultValueHandling = DefaultValueHandling.Ignore;
  398. var jsonData = JsonConvert.SerializeObject(new
  399. {
  400. dictionaries,
  401. apis,
  402. views,
  403. permissions,
  404. users,
  405. roles,
  406. userRoles,
  407. rolePermissions,
  408. tenants
  409. },
  410. //Formatting.Indented,
  411. settings
  412. );
  413. var filePath = Path.Combine(Directory.GetCurrentDirectory(), "Db/Data/data.json").ToPath();
  414. FileHelper.WriteFile(filePath, jsonData);
  415. #endregion
  416. Console.WriteLine(" generate data succeed\r\n");
  417. }
  418. catch (Exception ex)
  419. {
  420. throw new Exception($" generate data failed。\n{ex.Message}\r\n");
  421. }
  422. }
  423. }
  424. }