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