SqlSugarSetup.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  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. var storage = db2.Storageable(seedDataTable).WhereColumns(SqlSugarConst.PrimaryKey).ToStorage();
  206. storage.AsInsertable.ExecuteCommand();
  207. storage.AsUpdateable.ExecuteCommand();
  208. }
  209. else // 没有主键或者不是预定义的主键(有重复的可能)
  210. {
  211. var storage = db2.Storageable(seedDataTable).ToStorage();
  212. storage.AsInsertable.ExecuteCommand();
  213. }
  214. }
  215. }
  216. /// <summary>
  217. /// 增加租户库连接
  218. /// </summary>
  219. /// <param name="iTenant"></param>
  220. /// <param name="tenantId"></param>
  221. public static SqlSugarScopeProvider InitTenantDb(ITenant iTenant, long tenantId)
  222. {
  223. var tenant = App.GetRequiredService<SysCacheService>().Get<List<SysTenant>>(CacheConst.KeyTenant).FirstOrDefault(u => u.Id == tenantId);
  224. if (!iTenant.IsAnyConnection(tenantId.ToString()))
  225. {
  226. iTenant.AddConnection(new ConnectionConfig()
  227. {
  228. ConfigId = tenantId.ToString(),
  229. ConnectionString = tenant.Connection,
  230. DbType = tenant.DbType,
  231. IsAutoCloseConnection = true
  232. });
  233. SetDbAop(iTenant.GetConnectionScope(tenantId.ToString()));
  234. }
  235. return iTenant.GetConnectionScope(tenantId.ToString());
  236. }
  237. /// <summary>
  238. /// 配置实体假删除过滤器
  239. /// </summary>
  240. private static void SetDeletedEntityFilter(SqlSugarScopeProvider db)
  241. {
  242. // 配置实体假删除缓存
  243. var cacheKey = $"db:{db.CurrentConnectionConfig.ConfigId}:IsDelete";
  244. var tableFilterItemList = db.DataCache.Get<List<TableFilterItem<object>>>(cacheKey);
  245. if (tableFilterItemList == null)
  246. {
  247. // 获取基类实体数据表
  248. var entityTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
  249. && (u.BaseType == typeof(EntityBase) || u.BaseType == typeof(EntityTenant) || u.BaseType == typeof(DataEntityBase)));
  250. if (!entityTypes.Any()) return;
  251. var tableFilterItems = new List<TableFilterItem<object>>();
  252. foreach (var entityType in entityTypes)
  253. {
  254. // 排除非当前数据库实体
  255. var tAtt = entityType.GetCustomAttribute<TenantAttribute>();
  256. if ((tAtt != null && (string)db.CurrentConnectionConfig.ConfigId != tAtt.configId.ToString()) ||
  257. (tAtt == null && (string)db.CurrentConnectionConfig.ConfigId != SqlSugarConst.ConfigId))
  258. continue;
  259. Expression<Func<DataEntityBase, bool>> dynamicExpression = u => u.IsDelete == false;
  260. var tableFilterItem = new TableFilterItem<object>(entityType, dynamicExpression);
  261. tableFilterItems.Add(tableFilterItem);
  262. db.QueryFilter.Add(tableFilterItem);
  263. }
  264. db.DataCache.Add(cacheKey, tableFilterItems);
  265. }
  266. else
  267. {
  268. tableFilterItemList.ForEach(u =>
  269. {
  270. db.QueryFilter.Add(u);
  271. });
  272. }
  273. }
  274. /// <summary>
  275. /// 配置租户过滤器
  276. /// </summary>
  277. private static void SetTenantEntityFilter(SqlSugarScopeProvider db)
  278. {
  279. var tenantId = App.User?.FindFirst(ClaimConst.TenantId)?.Value;
  280. if (string.IsNullOrWhiteSpace(tenantId)) return;
  281. // 配置租户缓存
  282. var cacheKey = $"db:{db.CurrentConnectionConfig.ConfigId}:TenantId:{tenantId}";
  283. var tableFilterItemList = db.DataCache.Get<List<TableFilterItem<object>>>(cacheKey);
  284. if (tableFilterItemList == null)
  285. {
  286. // 获取租户实体数据表
  287. var entityTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
  288. && u.BaseType == typeof(EntityTenant));
  289. if (!entityTypes.Any()) return;
  290. var tableFilterItems = new List<TableFilterItem<object>>();
  291. foreach (var entityType in entityTypes)
  292. {
  293. // 排除非当前数据库实体
  294. var tAtt = entityType.GetCustomAttribute<TenantAttribute>();
  295. if ((tAtt != null && (string)db.CurrentConnectionConfig.ConfigId != tAtt.configId.ToString()) ||
  296. (tAtt == null && (string)db.CurrentConnectionConfig.ConfigId != SqlSugarConst.ConfigId))
  297. continue;
  298. Expression<Func<EntityTenant, bool>> dynamicExpression = u => u.TenantId == long.Parse(tenantId);
  299. var tableFilterItem = new TableFilterItem<object>(entityType, dynamicExpression);
  300. tableFilterItems.Add(tableFilterItem);
  301. db.QueryFilter.Add(tableFilterItem);
  302. }
  303. db.DataCache.Add(cacheKey, tableFilterItems);
  304. }
  305. else
  306. {
  307. tableFilterItemList.ForEach(u =>
  308. {
  309. db.QueryFilter.Add(u);
  310. });
  311. }
  312. }
  313. /// <summary>
  314. /// 配置用户机构范围过滤器
  315. /// </summary>
  316. private static void SetOrgEntityFilter(SqlSugarScopeProvider db)
  317. {
  318. var userId = App.User?.FindFirst(ClaimConst.UserId)?.Value;
  319. if (string.IsNullOrWhiteSpace(userId)) return;
  320. // 配置用户机构范围缓存
  321. var cacheKey = $"db:{db.CurrentConnectionConfig.ConfigId}:UserId:{userId}";
  322. var tableFilterItemList = db.DataCache.Get<List<TableFilterItem<object>>>(cacheKey);
  323. if (tableFilterItemList == null)
  324. {
  325. // 获取用户所属机构
  326. var orgIds = App.GetService<SysCacheService>().Get<List<long>>(CacheConst.KeyOrgIdList + userId);
  327. if (orgIds == null || orgIds.Count == 0) return;
  328. // 获取业务实体数据表
  329. var entityTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
  330. && u.BaseType == typeof(DataEntityBase));
  331. if (!entityTypes.Any()) return;
  332. var tableFilterItems = new List<TableFilterItem<object>>();
  333. foreach (var entityType in entityTypes)
  334. {
  335. // 排除非当前数据库实体
  336. var tAtt = entityType.GetCustomAttribute<TenantAttribute>();
  337. if ((tAtt != null && (string)db.CurrentConnectionConfig.ConfigId != tAtt.configId.ToString()) ||
  338. (tAtt == null && (string)db.CurrentConnectionConfig.ConfigId != SqlSugarConst.ConfigId))
  339. continue;
  340. Expression<Func<DataEntityBase, bool>> dynamicExpression = u => orgIds.Contains((long)u.CreateOrgId);
  341. var tableFilterItem = new TableFilterItem<object>(entityType, dynamicExpression);
  342. tableFilterItems.Add(tableFilterItem);
  343. db.QueryFilter.Add(tableFilterItem);
  344. }
  345. db.DataCache.Add(cacheKey, tableFilterItems);
  346. }
  347. else
  348. {
  349. tableFilterItemList.ForEach(u =>
  350. {
  351. db.QueryFilter.Add(u);
  352. });
  353. }
  354. }
  355. /// <summary>
  356. /// 配置自定义过滤器
  357. /// </summary>
  358. private static void SetCustomEntityFilter(SqlSugarScopeProvider db)
  359. {
  360. // 排除超管过滤
  361. if (App.User?.FindFirst(ClaimConst.AccountType)?.Value == ((int)AccountTypeEnum.SuperAdmin).ToString())
  362. return;
  363. // 配置用户机构范围缓存
  364. var cacheKey = $"db:{db.CurrentConnectionConfig.ConfigId}:Custom";
  365. var tableFilterItemList = db.DataCache.Get<List<TableFilterItem<object>>>(cacheKey);
  366. if (tableFilterItemList == null)
  367. {
  368. // 获取自定义实体过滤器
  369. var entityFilterTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
  370. && u.GetInterfaces().Any(i => i.HasImplementedRawGeneric(typeof(IEntityFilter))));
  371. if (!entityFilterTypes.Any()) return;
  372. var tableFilterItems = new List<TableFilterItem<object>>();
  373. foreach (var entityFilter in entityFilterTypes)
  374. {
  375. var instance = Activator.CreateInstance(entityFilter);
  376. var entityFilterMethod = entityFilter.GetMethod("AddEntityFilter");
  377. var entityFilters = ((IList)entityFilterMethod?.Invoke(instance, null))?.Cast<object>();
  378. if (entityFilters == null) continue;
  379. foreach (var u in entityFilters)
  380. {
  381. var tableFilterItem = (TableFilterItem<object>)u;
  382. var entityType = tableFilterItem.GetType().GetProperty("type", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(tableFilterItem, null) as Type;
  383. // 排除非当前数据库实体
  384. var tAtt = entityType.GetCustomAttribute<TenantAttribute>();
  385. if ((tAtt != null && (string)db.CurrentConnectionConfig.ConfigId != tAtt.configId.ToString()) ||
  386. (tAtt == null && (string)db.CurrentConnectionConfig.ConfigId != SqlSugarConst.ConfigId))
  387. return;
  388. tableFilterItems.Add(tableFilterItem);
  389. db.QueryFilter.Add(tableFilterItem);
  390. }
  391. }
  392. db.DataCache.Add(cacheKey, tableFilterItems);
  393. }
  394. else
  395. {
  396. tableFilterItemList.ForEach(u =>
  397. {
  398. db.QueryFilter.Add(u);
  399. });
  400. }
  401. }
  402. }