SqlSugarSetup.cs 21 KB

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