SqlSugarSetup.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. namespace Admin.NET.Core;
  2. public static class SqlSugarSetup
  3. {
  4. /// <summary>
  5. /// Sqlsugar 上下文初始化
  6. /// </summary>
  7. /// <param name="services"></param>
  8. public static void AddSqlSugar(this IServiceCollection services)
  9. {
  10. var dbOptions = App.GetOptions<DbConnectionOptions>();
  11. dbOptions.ConnectionConfigs.ForEach(config =>
  12. {
  13. SetDbConfig(config);
  14. });
  15. SqlSugarScope sqlSugar = new(dbOptions.ConnectionConfigs.Adapt<List<ConnectionConfig>>(), db =>
  16. {
  17. dbOptions.ConnectionConfigs.ForEach(config =>
  18. {
  19. SetDbAop(db.GetConnectionScope(config.ConfigId));
  20. });
  21. });
  22. // 初始化数据库表结构及种子数据
  23. dbOptions.ConnectionConfigs.ForEach(config =>
  24. {
  25. if (config.EnableInitDb && config.DbType != SqlSugar.DbType.Oracle)
  26. {
  27. sqlSugar.DbMaintenance.CreateDatabase();
  28. InitDatabase(sqlSugar.AsTenant(), config);
  29. }
  30. });
  31. services.AddSingleton<ISqlSugarClient>(sqlSugar); // 单例注册
  32. services.AddScoped(typeof(SqlSugarRepository<>)); // 仓储注册
  33. services.AddUnitOfWork<SqlSugarUnitOfWork>(); // 事务与工作单元注册
  34. }
  35. /// <summary>
  36. /// 配置连接属性
  37. /// </summary>
  38. /// <param name="config"></param>
  39. public static void SetDbConfig(DbConnectionConfig config)
  40. {
  41. var configureExternalServices = new ConfigureExternalServices
  42. {
  43. EntityService = (type, column) => // 修改列可空-1、带?问号 2、String类型若没有Required
  44. {
  45. if ((type.PropertyType.IsGenericType && type.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
  46. || (type.PropertyType == typeof(string) && type.GetCustomAttribute<RequiredAttribute>() == null))
  47. column.IsNullable = true;
  48. },
  49. DataInfoCacheService = new SqlSugarCache(),
  50. };
  51. config.ConfigureExternalServices = configureExternalServices;
  52. config.InitKeyType = InitKeyType.Attribute;
  53. config.IsAutoCloseConnection = true;
  54. config.MoreSettings = new ConnMoreSettings
  55. {
  56. IsAutoRemoveDataCache = true
  57. };
  58. }
  59. /// <summary>
  60. /// 配置Aop
  61. /// </summary>
  62. /// <param name="db"></param>
  63. public static void SetDbAop(SqlSugarScopeProvider db)
  64. {
  65. var config = db.CurrentConnectionConfig;
  66. // 设置超时时间
  67. db.Ado.CommandTimeOut = 30;
  68. // 打印SQL语句
  69. db.Aop.OnLogExecuting = (sql, pars) =>
  70. {
  71. if (sql.StartsWith("SELECT", StringComparison.OrdinalIgnoreCase))
  72. Console.ForegroundColor = ConsoleColor.Green;
  73. if (sql.StartsWith("UPDATE", StringComparison.OrdinalIgnoreCase) || sql.StartsWith("INSERT", StringComparison.OrdinalIgnoreCase))
  74. Console.ForegroundColor = ConsoleColor.White;
  75. if (sql.StartsWith("DELETE", StringComparison.OrdinalIgnoreCase))
  76. Console.ForegroundColor = ConsoleColor.Blue;
  77. Console.WriteLine("【" + DateTime.Now + "——执行SQL】\r\n" + UtilMethods.GetSqlString(config.DbType, sql, pars) + "\r\n");
  78. App.PrintToMiniProfiler("SqlSugar", "Info", sql + "\r\n" + db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
  79. };
  80. db.Aop.OnError = (ex) =>
  81. {
  82. if (ex.Parametres == null) return;
  83. Console.ForegroundColor = ConsoleColor.Red;
  84. var pars = db.Utilities.SerializeObject(((SugarParameter[])ex.Parametres).ToDictionary(it => it.ParameterName, it => it.Value));
  85. Console.WriteLine("【" + DateTime.Now + "——错误SQL】\r\n" + UtilMethods.GetSqlString(config.DbType, ex.Sql, (SugarParameter[])ex.Parametres) + "\r\n");
  86. App.PrintToMiniProfiler("SqlSugar", "Error", $"{ex.Message}{Environment.NewLine}{ex.Sql}{pars}{Environment.NewLine}");
  87. };
  88. // 数据审计
  89. db.Aop.DataExecuting = (oldValue, entityInfo) =>
  90. {
  91. // 新增操作
  92. if (entityInfo.OperationType == DataFilterType.InsertByObject)
  93. {
  94. // 主键(long类型)且没有值的---赋值雪花Id
  95. if (entityInfo.EntityColumnInfo.IsPrimarykey && entityInfo.EntityColumnInfo.PropertyInfo.PropertyType == typeof(long))
  96. {
  97. var id = entityInfo.EntityColumnInfo.PropertyInfo.GetValue(entityInfo.EntityValue);
  98. if (id == null || (long)id == 0)
  99. entityInfo.SetValue(Yitter.IdGenerator.YitIdHelper.NextId());
  100. }
  101. if (entityInfo.PropertyName == "CreateTime")
  102. entityInfo.SetValue(DateTime.Now);
  103. if (App.User != null)
  104. {
  105. if (entityInfo.PropertyName == "TenantId")
  106. {
  107. var tenantId = ((dynamic)entityInfo.EntityValue).TenantId;
  108. if (tenantId == null || tenantId == 0)
  109. entityInfo.SetValue(App.User.FindFirst(ClaimConst.TenantId)?.Value);
  110. }
  111. if (entityInfo.PropertyName == "CreateUserId")
  112. entityInfo.SetValue(App.User.FindFirst(ClaimConst.UserId)?.Value);
  113. if (entityInfo.PropertyName == "CreateOrgId")
  114. entityInfo.SetValue(App.User.FindFirst(ClaimConst.OrgId)?.Value);
  115. }
  116. }
  117. // 更新操作
  118. if (entityInfo.OperationType == DataFilterType.UpdateByObject)
  119. {
  120. if (entityInfo.PropertyName == "UpdateTime")
  121. entityInfo.SetValue(DateTime.Now);
  122. if (entityInfo.PropertyName == "UpdateUserId")
  123. entityInfo.SetValue(App.User?.FindFirst(ClaimConst.UserId)?.Value);
  124. }
  125. };
  126. //// 差异日志
  127. //db.Aop.OnDiffLogEvent = async u =>
  128. //{
  129. // if (!config.EnableDiffLog) return;
  130. // var LogDiff = new SysLogDiff
  131. // {
  132. // // 操作后记录(字段描述、列名、值、表名、表描述)
  133. // AfterData = JsonConvert.SerializeObject(u.AfterData),
  134. // // 操作前记录(字段描述、列名、值、表名、表描述)
  135. // BeforeData = JsonConvert.SerializeObject(u.BeforeData),
  136. // // 传进来的对象
  137. // BusinessData = JsonConvert.SerializeObject(u.BusinessData),
  138. // // 枚举(insert、update、delete)
  139. // DiffType = u.DiffType.ToString(),
  140. // Sql = UtilMethods.GetSqlString(config.DbType, u.Sql, u.Parameters),
  141. // Parameters = JsonConvert.SerializeObject(u.Parameters),
  142. // Duration = u.Time == null ? 0 : (long)u.Time.Value.TotalMilliseconds
  143. // };
  144. // await client.GetConnectionScope(SqlSugarConst.ConfigId).Insertable(LogDiff).ExecuteCommandAsync();
  145. // Console.ForegroundColor = ConsoleColor.Red;
  146. // Console.WriteLine(DateTime.Now + $"\r\n**********差异日志开始**********\r\n{Environment.NewLine}{JsonConvert.SerializeObject(LogDiff)}{Environment.NewLine}**********差异日志结束**********\r\n");
  147. //};
  148. // 配置实体假删除过滤器
  149. SetDeletedEntityFilter(db);
  150. // 配置租户过滤器
  151. SetTenantEntityFilter(db);
  152. // 配置用户机构范围过滤器
  153. SetOrgEntityFilter(db);
  154. // 配置自定义过滤器
  155. SetCustomEntityFilter(db);
  156. }
  157. /// <summary>
  158. /// 初始化数据库结构
  159. /// </summary>
  160. /// <param name="db"></param>
  161. /// <param name="config"></param>
  162. /// <param name="tenantId"></param>
  163. public static void InitDatabase(ITenant db, DbConnectionConfig config, long tenantId = 0)
  164. {
  165. // 获取所有实体表-初始化表结构
  166. var entityTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
  167. && u.IsDefined(typeof(SugarTable), false) && !u.IsDefined(typeof(NotTableAttribute), false));
  168. if (!entityTypes.Any()) return;
  169. var db2 = db.GetConnectionScope(config.ConfigId);
  170. foreach (var entityType in entityTypes)
  171. {
  172. var tAtt = entityType.GetCustomAttribute<TenantAttribute>();
  173. if (tAtt != null && tAtt.configId.ToString() != config.ConfigId) continue;
  174. if (tAtt == null && config.ConfigId != SqlSugarConst.ConfigId && tenantId < 1) continue;
  175. var splitTable = entityType.GetCustomAttribute<SplitTableAttribute>();
  176. if (splitTable == null)
  177. db2.CodeFirst.InitTables(entityType);
  178. else
  179. db2.CodeFirst.SplitTables().InitTables(entityType);
  180. }
  181. // 获取所有种子配置-初始化数据
  182. var seedDataTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
  183. && u.GetInterfaces().Any(i => i.HasImplementedRawGeneric(typeof(ISqlSugarEntitySeedData<>))));
  184. if (!seedDataTypes.Any()) return;
  185. foreach (var seedType in seedDataTypes)
  186. {
  187. var instance = Activator.CreateInstance(seedType);
  188. var hasDataMethod = seedType.GetMethod("HasData");
  189. var seedData = ((IEnumerable)hasDataMethod?.Invoke(instance, null))?.Cast<object>();
  190. if (seedData == null) continue;
  191. var entityType = seedType.GetInterfaces().First().GetGenericArguments().First();
  192. var tAtt = entityType.GetCustomAttribute<TenantAttribute>();
  193. if (tAtt != null && tAtt.configId.ToString() != config.ConfigId) continue;
  194. if (tAtt == null && config.ConfigId != SqlSugarConst.ConfigId && tenantId < 1) continue;
  195. var seedDataTable = seedData.ToList().ToDataTable();
  196. seedDataTable.TableName = db2.EntityMaintenance.GetEntityInfo(entityType).DbTableName;
  197. // 创建租户库时修改租户Id
  198. if (tenantId > 1 && seedDataTable.Columns.Contains(SqlSugarConst.TenantId))
  199. {
  200. foreach (DataRow dr in seedDataTable.Rows)
  201. dr[SqlSugarConst.TenantId] = tenantId;
  202. }
  203. if (seedDataTable.Columns.Contains(SqlSugarConst.PrimaryKey))
  204. {
  205. //解决pgsql中,业务添加框架的种子数据时候,类映射了多个类型的问题bug(本bug是sqlsugar作者提供的解决方案)
  206. var storage = db2.CopyNew().Storageable(seedDataTable).WhereColumns(SqlSugarConst.PrimaryKey).ToStorage();
  207. storage.AsInsertable.ExecuteCommand();
  208. storage.AsUpdateable.ExecuteCommand();
  209. }
  210. else // 没有主键或者不是预定义的主键(有重复的可能)
  211. {
  212. var storage = db2.CopyNew().Storageable(seedDataTable).ToStorage();
  213. storage.AsInsertable.ExecuteCommand();
  214. }
  215. }
  216. }
  217. /// <summary>
  218. /// 增加租户库连接
  219. /// </summary>
  220. /// <param name="iTenant"></param>
  221. /// <param name="tenantId"></param>
  222. public static SqlSugarScopeProvider InitTenantDb(ITenant iTenant, long tenantId)
  223. {
  224. var tenant = App.GetRequiredService<SysCacheService>().Get<List<SysTenant>>(CacheConst.KeyTenant).FirstOrDefault(u => u.Id == tenantId);
  225. if (!iTenant.IsAnyConnection(tenantId.ToString()))
  226. {
  227. iTenant.AddConnection(new ConnectionConfig()
  228. {
  229. ConfigId = tenantId.ToString(),
  230. ConnectionString = tenant.Connection,
  231. DbType = tenant.DbType,
  232. IsAutoCloseConnection = true
  233. });
  234. SetDbAop(iTenant.GetConnectionScope(tenantId.ToString()));
  235. }
  236. return iTenant.GetConnectionScope(tenantId.ToString());
  237. }
  238. /// <summary>
  239. /// 配置实体假删除过滤器
  240. /// </summary>
  241. private static void SetDeletedEntityFilter(SqlSugarScopeProvider db)
  242. {
  243. // 配置实体假删除缓存
  244. var cacheKey = $"db:{db.CurrentConnectionConfig.ConfigId}:IsDelete";
  245. var tableFilterItemList = db.DataCache.Get<List<TableFilterItem<object>>>(cacheKey);
  246. if (tableFilterItemList == null)
  247. {
  248. // 获取基类实体数据表
  249. var entityTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
  250. && (u.BaseType == typeof(EntityBase) || u.BaseType == typeof(EntityTenant) || u.BaseType == typeof(DataEntityBase)));
  251. if (!entityTypes.Any()) return;
  252. var tableFilterItems = new List<TableFilterItem<object>>();
  253. foreach (var entityType in entityTypes)
  254. {
  255. // 排除非当前数据库实体
  256. var tAtt = entityType.GetCustomAttribute<TenantAttribute>();
  257. if ((tAtt != null && (string)db.CurrentConnectionConfig.ConfigId != tAtt.configId.ToString()) ||
  258. (tAtt == null && (string)db.CurrentConnectionConfig.ConfigId != SqlSugarConst.ConfigId))
  259. continue;
  260. Expression<Func<DataEntityBase, bool>> dynamicExpression = u => u.IsDelete == false;
  261. var tableFilterItem = new TableFilterItem<object>(entityType, dynamicExpression);
  262. tableFilterItems.Add(tableFilterItem);
  263. db.QueryFilter.Add(tableFilterItem);
  264. }
  265. db.DataCache.Add(cacheKey, tableFilterItems);
  266. }
  267. else
  268. {
  269. tableFilterItemList.ForEach(u =>
  270. {
  271. db.QueryFilter.Add(u);
  272. });
  273. }
  274. }
  275. /// <summary>
  276. /// 配置租户过滤器
  277. /// </summary>
  278. private static void SetTenantEntityFilter(SqlSugarScopeProvider db)
  279. {
  280. var tenantId = App.User?.FindFirst(ClaimConst.TenantId)?.Value;
  281. if (string.IsNullOrWhiteSpace(tenantId)) return;
  282. // 配置租户缓存
  283. var cacheKey = $"db:{db.CurrentConnectionConfig.ConfigId}:TenantId:{tenantId}";
  284. var tableFilterItemList = db.DataCache.Get<List<TableFilterItem<object>>>(cacheKey);
  285. if (tableFilterItemList == null)
  286. {
  287. // 获取租户实体数据表
  288. var entityTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
  289. && u.BaseType == typeof(EntityTenant));
  290. if (!entityTypes.Any()) return;
  291. var tableFilterItems = new List<TableFilterItem<object>>();
  292. foreach (var entityType in entityTypes)
  293. {
  294. // 排除非当前数据库实体
  295. var tAtt = entityType.GetCustomAttribute<TenantAttribute>();
  296. if ((tAtt != null && (string)db.CurrentConnectionConfig.ConfigId != tAtt.configId.ToString()) ||
  297. (tAtt == null && (string)db.CurrentConnectionConfig.ConfigId != SqlSugarConst.ConfigId))
  298. continue;
  299. Expression<Func<EntityTenant, bool>> dynamicExpression = u => u.TenantId == long.Parse(tenantId);
  300. var tableFilterItem = new TableFilterItem<object>(entityType, dynamicExpression);
  301. tableFilterItems.Add(tableFilterItem);
  302. db.QueryFilter.Add(tableFilterItem);
  303. }
  304. db.DataCache.Add(cacheKey, tableFilterItems);
  305. }
  306. else
  307. {
  308. tableFilterItemList.ForEach(u =>
  309. {
  310. db.QueryFilter.Add(u);
  311. });
  312. }
  313. }
  314. /// <summary>
  315. /// 配置用户机构范围过滤器
  316. /// </summary>
  317. private static void SetOrgEntityFilter(SqlSugarScopeProvider db)
  318. {
  319. var userId = App.User?.FindFirst(ClaimConst.UserId)?.Value;
  320. if (string.IsNullOrWhiteSpace(userId)) return;
  321. // 配置用户机构范围缓存
  322. var cacheKey = $"db:{db.CurrentConnectionConfig.ConfigId}:UserId:{userId}";
  323. var tableFilterItemList = db.DataCache.Get<List<TableFilterItem<object>>>(cacheKey);
  324. if (tableFilterItemList == null)
  325. {
  326. // 获取用户所属机构
  327. var orgIds = App.GetService<SysCacheService>().Get<List<long>>(CacheConst.KeyOrgIdList + userId);
  328. if (orgIds == null || orgIds.Count == 0) return;
  329. // 获取业务实体数据表
  330. var entityTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
  331. && u.BaseType == typeof(DataEntityBase));
  332. if (!entityTypes.Any()) return;
  333. var tableFilterItems = new List<TableFilterItem<object>>();
  334. foreach (var entityType in entityTypes)
  335. {
  336. // 排除非当前数据库实体
  337. var tAtt = entityType.GetCustomAttribute<TenantAttribute>();
  338. if ((tAtt != null && (string)db.CurrentConnectionConfig.ConfigId != tAtt.configId.ToString()) ||
  339. (tAtt == null && (string)db.CurrentConnectionConfig.ConfigId != SqlSugarConst.ConfigId))
  340. continue;
  341. Expression<Func<DataEntityBase, bool>> dynamicExpression = u => orgIds.Contains((long)u.CreateOrgId);
  342. var tableFilterItem = new TableFilterItem<object>(entityType, dynamicExpression);
  343. tableFilterItems.Add(tableFilterItem);
  344. db.QueryFilter.Add(tableFilterItem);
  345. }
  346. db.DataCache.Add(cacheKey, tableFilterItems);
  347. }
  348. else
  349. {
  350. tableFilterItemList.ForEach(u =>
  351. {
  352. db.QueryFilter.Add(u);
  353. });
  354. }
  355. }
  356. /// <summary>
  357. /// 配置自定义过滤器
  358. /// </summary>
  359. private static void SetCustomEntityFilter(SqlSugarScopeProvider db)
  360. {
  361. // 排除超管过滤
  362. if (App.User?.FindFirst(ClaimConst.AccountType)?.Value == ((int)AccountTypeEnum.SuperAdmin).ToString())
  363. return;
  364. // 配置用户机构范围缓存
  365. var cacheKey = $"db:{db.CurrentConnectionConfig.ConfigId}:Custom";
  366. var tableFilterItemList = db.DataCache.Get<List<TableFilterItem<object>>>(cacheKey);
  367. if (tableFilterItemList == null)
  368. {
  369. // 获取自定义实体过滤器
  370. var entityFilterTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
  371. && u.GetInterfaces().Any(i => i.HasImplementedRawGeneric(typeof(IEntityFilter))));
  372. if (!entityFilterTypes.Any()) return;
  373. var tableFilterItems = new List<TableFilterItem<object>>();
  374. foreach (var entityFilter in entityFilterTypes)
  375. {
  376. var instance = Activator.CreateInstance(entityFilter);
  377. var entityFilterMethod = entityFilter.GetMethod("AddEntityFilter");
  378. var entityFilters = ((IList)entityFilterMethod?.Invoke(instance, null))?.Cast<object>();
  379. if (entityFilters == null) continue;
  380. foreach (var u in entityFilters)
  381. {
  382. var tableFilterItem = (TableFilterItem<object>)u;
  383. var entityType = tableFilterItem.GetType().GetProperty("type", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(tableFilterItem, null) as Type;
  384. // 排除非当前数据库实体
  385. var tAtt = entityType.GetCustomAttribute<TenantAttribute>();
  386. if ((tAtt != null && (string)db.CurrentConnectionConfig.ConfigId != tAtt.configId.ToString()) ||
  387. (tAtt == null && (string)db.CurrentConnectionConfig.ConfigId != SqlSugarConst.ConfigId))
  388. return;
  389. tableFilterItems.Add(tableFilterItem);
  390. db.QueryFilter.Add(tableFilterItem);
  391. }
  392. }
  393. db.DataCache.Add(cacheKey, tableFilterItems);
  394. }
  395. else
  396. {
  397. tableFilterItemList.ForEach(u =>
  398. {
  399. db.QueryFilter.Add(u);
  400. });
  401. }
  402. }
  403. }