SqlSugarSetup.cs 20 KB

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