SqlSugarSetup.cs 21 KB

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