SqlSugarSetup.cs 20 KB

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