SqlSugarSetup.cs 21 KB

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