SqlSugarSetup.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. using Masuit.Tools;
  2. namespace Admin.NET.Core;
  3. public static class SqlSugarSetup
  4. {
  5. /// <summary>
  6. /// Sqlsugar 上下文初始化
  7. /// </summary>
  8. /// <param name="services"></param>
  9. public static void AddSqlSugar(this IServiceCollection services)
  10. {
  11. var dbOptions = App.GetOptions<DbConnectionOptions>();
  12. var configureExternalServices = new ConfigureExternalServices
  13. {
  14. EntityService = (type, column) => // 修改列可空-1、带?问号 2、String类型若没有Required
  15. {
  16. if ((type.PropertyType.IsGenericType && type.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
  17. || (type.PropertyType == typeof(string) && type.GetCustomAttribute<RequiredAttribute>() == null))
  18. column.IsNullable = true;
  19. },
  20. DataInfoCacheService = new SqlSugarCache(),
  21. };
  22. dbOptions.ConnectionConfigs.ForEach(config =>
  23. {
  24. config.ConfigureExternalServices = configureExternalServices;
  25. config.InitKeyType = InitKeyType.Attribute;
  26. config.IsAutoCloseConnection = true;
  27. config.MoreSettings = new ConnMoreSettings
  28. {
  29. IsAutoRemoveDataCache = true
  30. };
  31. });
  32. SqlSugarScope sqlSugar = new(dbOptions.ConnectionConfigs.Adapt<List<ConnectionConfig>>(), client =>
  33. {
  34. dbOptions.ConnectionConfigs.ForEach(config =>
  35. {
  36. var db = client.GetConnectionScope((string)config.ConfigId);
  37. // 设置超时时间
  38. db.Ado.CommandTimeOut = 30;
  39. // 打印SQL语句
  40. db.Aop.OnLogExecuting = (sql, pars) =>
  41. {
  42. if (sql.StartsWith("SELECT", StringComparison.OrdinalIgnoreCase))
  43. Console.ForegroundColor = ConsoleColor.Green;
  44. if (sql.StartsWith("UPDATE", StringComparison.OrdinalIgnoreCase) || sql.StartsWith("INSERT", StringComparison.OrdinalIgnoreCase))
  45. Console.ForegroundColor = ConsoleColor.White;
  46. if (sql.StartsWith("DELETE", StringComparison.OrdinalIgnoreCase))
  47. Console.ForegroundColor = ConsoleColor.Blue;
  48. Console.WriteLine("【" + DateTime.Now + "——执行SQL】\r\n" + UtilMethods.GetSqlString(config.DbType, sql, pars) + "\r\n");
  49. App.PrintToMiniProfiler("SqlSugar", "Info", sql + "\r\n" + db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
  50. };
  51. db.Aop.OnError = (ex) =>
  52. {
  53. Console.ForegroundColor = ConsoleColor.Red;
  54. var pars = db.Utilities.SerializeObject(((SugarParameter[])ex.Parametres).ToDictionary(it => it.ParameterName, it => it.Value));
  55. Console.WriteLine("【" + DateTime.Now + "——错误SQL】\r\n" + UtilMethods.GetSqlString(config.DbType, ex.Sql, (SugarParameter[])ex.Parametres) + "\r\n");
  56. App.PrintToMiniProfiler("SqlSugar", "Error", $"{ex.Message}{Environment.NewLine}{ex.Sql}{pars}{Environment.NewLine}");
  57. };
  58. // 数据审计
  59. db.Aop.DataExecuting = (oldValue, entityInfo) =>
  60. {
  61. // 新增操作
  62. if (entityInfo.OperationType == DataFilterType.InsertByObject)
  63. {
  64. // 主键(long类型)且没有值的---赋值雪花Id
  65. if (entityInfo.EntityColumnInfo.IsPrimarykey && entityInfo.EntityColumnInfo.PropertyInfo.PropertyType == typeof(long))
  66. {
  67. var id = entityInfo.EntityColumnInfo.PropertyInfo.GetValue(entityInfo.EntityValue);
  68. if (id == null || (long)id == 0)
  69. entityInfo.SetValue(Yitter.IdGenerator.YitIdHelper.NextId());
  70. }
  71. if (entityInfo.PropertyName == "CreateTime")
  72. entityInfo.SetValue(DateTime.Now);
  73. if (App.User != null)
  74. {
  75. if (entityInfo.PropertyName == "TenantId")
  76. {
  77. var tenantId = ((dynamic)entityInfo.EntityValue).TenantId;
  78. if (tenantId == null || tenantId == 0)
  79. entityInfo.SetValue(App.User.FindFirst(ClaimConst.TenantId)?.Value);
  80. }
  81. if (entityInfo.PropertyName == "CreateUserId")
  82. entityInfo.SetValue(App.User.FindFirst(ClaimConst.UserId)?.Value);
  83. if (entityInfo.PropertyName == "CreateOrgId")
  84. entityInfo.SetValue(App.User.FindFirst(ClaimConst.OrgId)?.Value);
  85. }
  86. }
  87. // 更新操作
  88. if (entityInfo.OperationType == DataFilterType.UpdateByObject)
  89. {
  90. if (entityInfo.PropertyName == "UpdateTime")
  91. entityInfo.SetValue(DateTime.Now);
  92. if (entityInfo.PropertyName == "UpdateUserId")
  93. entityInfo.SetValue(App.User?.FindFirst(ClaimConst.UserId)?.Value);
  94. }
  95. };
  96. // 差异日志
  97. db.Aop.OnDiffLogEvent = async u =>
  98. {
  99. if (!config.EnableDiffLog) return;
  100. var LogDiff = new SysLogDiff
  101. {
  102. // 操作后记录(字段描述、列名、值、表名、表描述)
  103. AfterData = JsonConvert.SerializeObject(u.AfterData),
  104. // 操作前记录(字段描述、列名、值、表名、表描述)
  105. BeforeData = JsonConvert.SerializeObject(u.BeforeData),
  106. // 传进来的对象
  107. BusinessData = JsonConvert.SerializeObject(u.BusinessData),
  108. // 枚举(insert、update、delete)
  109. DiffType = u.DiffType.ToString(),
  110. Sql = UtilMethods.GetSqlString(config.DbType, u.Sql, u.Parameters),
  111. Parameters = JsonConvert.SerializeObject(u.Parameters),
  112. Duration = u.Time == null ? 0 : (long)u.Time.Value.TotalMilliseconds
  113. };
  114. await client.GetConnectionScope(SqlSugarConst.ConfigId).Insertable(LogDiff).ExecuteCommandAsync();
  115. Console.ForegroundColor = ConsoleColor.Red;
  116. Console.WriteLine(DateTime.Now + $"\r\n**********差异日志开始**********\r\n{Environment.NewLine}{JsonConvert.SerializeObject(LogDiff)}{Environment.NewLine}**********差异日志结束**********\r\n");
  117. };
  118. // 配置实体假删除过滤器
  119. SetDeletedEntityFilter(db);
  120. // 配置租户过滤器
  121. SetTenantEntityFilter(db);
  122. // 配置用户机构范围过滤器
  123. SetOrgEntityFilter(db);
  124. // 配置自定义过滤器
  125. SetCustomEntityFilter(db);
  126. });
  127. });
  128. // 初始化数据库表结构及种子数据
  129. InitDataBase(sqlSugar, dbOptions);
  130. services.AddSingleton<ISqlSugarClient>(sqlSugar); // 单例注册
  131. services.AddScoped(typeof(SqlSugarRepository<>)); // 注册仓储
  132. services.AddUnitOfWork<SqlSugarUnitOfWork>(); // 注册事务与工作单元
  133. }
  134. /// <summary>
  135. /// 初始化数据库结构
  136. /// </summary>
  137. private static void InitDataBase(SqlSugarScope db, DbConnectionOptions dbOptions)
  138. {
  139. // 创建数据库
  140. dbOptions.ConnectionConfigs.ForEach(config =>
  141. {
  142. if (!config.EnableInitDb || config.DbType == SqlSugar.DbType.Oracle) return;
  143. db.GetConnectionScope(config.ConfigId).DbMaintenance.CreateDatabase();
  144. });
  145. // 获取所有实体表-初始化表结构
  146. var entityTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
  147. && u.IsDefined(typeof(SugarTable), false) && !u.IsDefined(typeof(NotTableAttribute), false));
  148. if (!entityTypes.Any()) return;
  149. foreach (var entityType in entityTypes)
  150. {
  151. var tAtt = entityType.GetCustomAttribute<TenantAttribute>(); // 多数据库
  152. var configId = tAtt == null ? SqlSugarConst.ConfigId : tAtt.configId.ToString();
  153. if (!dbOptions.ConnectionConfigs.FirstOrDefault(u => u.ConfigId == configId).EnableInitDb)
  154. continue;
  155. var db2 = db.GetConnectionScope(configId);
  156. var splitTable = entityType.GetCustomAttribute<SplitTableAttribute>(); // 分表
  157. if (splitTable == null)
  158. db2.CodeFirst.InitTables(entityType);
  159. else
  160. db2.CodeFirst.SplitTables().InitTables(entityType);
  161. }
  162. // 获取所有种子配置-初始化数据
  163. var seedDataTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
  164. && u.GetInterfaces().Any(i => i.HasImplementedRawGeneric(typeof(ISqlSugarEntitySeedData<>))));
  165. if (!seedDataTypes.Any()) return;
  166. foreach (var seedType in seedDataTypes)
  167. {
  168. var instance = Activator.CreateInstance(seedType);
  169. var hasDataMethod = seedType.GetMethod("HasData");
  170. var seedData = ((IEnumerable)hasDataMethod?.Invoke(instance, null))?.Cast<object>();
  171. if (seedData == null) continue;
  172. var entityType = seedType.GetInterfaces().First().GetGenericArguments().First();
  173. var tAtt = entityType.GetCustomAttribute<TenantAttribute>();
  174. var configId = tAtt == null ? SqlSugarConst.ConfigId : tAtt.configId.ToString();
  175. if (!dbOptions.ConnectionConfigs.FirstOrDefault(u => u.ConfigId == configId).EnableInitDb)
  176. continue;
  177. var db2 = db.GetConnectionScope(configId);
  178. var seedDataTable = seedData.ToList().ToDataTable();
  179. seedDataTable.TableName = db.EntityMaintenance.GetEntityInfo(entityType).DbTableName;
  180. if (seedDataTable.Columns.Contains(SqlSugarConst.PrimaryKey))
  181. {
  182. var storage = db2.Storageable(seedDataTable).WhereColumns(SqlSugarConst.PrimaryKey).ToStorage();
  183. storage.AsInsertable.ExecuteCommand();
  184. storage.AsUpdateable.ExecuteCommand();
  185. }
  186. else // 没有主键或者不是预定义的主键(没主键有重复的可能)
  187. {
  188. var storage = db2.Storageable(seedDataTable).ToStorage();
  189. storage.AsInsertable.ExecuteCommand();
  190. }
  191. }
  192. }
  193. /// <summary>
  194. /// 配置实体假删除过滤器
  195. /// </summary>
  196. private static void SetDeletedEntityFilter(SqlSugarScopeProvider db)
  197. {
  198. // 配置实体假删除缓存
  199. var cacheKey = $"db:{db.CurrentConnectionConfig.ConfigId}:IsDelete";
  200. var tableFilterItemList = db.DataCache.Get<List<TableFilterItem<object>>>(cacheKey);
  201. if (tableFilterItemList == null)
  202. {
  203. // 获取基类实体数据表
  204. var entityTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
  205. && (u.BaseType == typeof(EntityBase) || u.BaseType == typeof(EntityTenant) || u.BaseType == typeof(DataEntityBase)));
  206. if (!entityTypes.Any()) return;
  207. var tableFilterItems = new List<TableFilterItem<object>>();
  208. foreach (var entityType in entityTypes)
  209. {
  210. // 排除非当前数据库实体
  211. var tAtt = entityType.GetCustomAttribute<TenantAttribute>();
  212. if ((tAtt != null && (string)db.CurrentConnectionConfig.ConfigId != tAtt.configId.ToString()) ||
  213. (tAtt == null && (string)db.CurrentConnectionConfig.ConfigId != SqlSugarConst.ConfigId))
  214. continue;
  215. Expression<Func<DataEntityBase, bool>> dynamicExpression = u => u.IsDelete == false;
  216. var tableFilterItem = new TableFilterItem<object>(entityType, dynamicExpression);
  217. tableFilterItems.Add(tableFilterItem);
  218. db.QueryFilter.Add(tableFilterItem);
  219. }
  220. db.DataCache.Add(cacheKey, tableFilterItems);
  221. }
  222. else
  223. {
  224. tableFilterItemList.ForEach(u =>
  225. {
  226. db.QueryFilter.Add(u);
  227. });
  228. }
  229. }
  230. /// <summary>
  231. /// 配置租户过滤器
  232. /// </summary>
  233. private static void SetTenantEntityFilter(SqlSugarScopeProvider db)
  234. {
  235. var tenantId = App.User?.FindFirst(ClaimConst.TenantId)?.Value;
  236. if (string.IsNullOrWhiteSpace(tenantId)) return;
  237. // 配置租户缓存
  238. var cacheKey = $"db:{db.CurrentConnectionConfig.ConfigId}:TenantId:{tenantId}";
  239. var tableFilterItemList = db.DataCache.Get<List<TableFilterItem<object>>>(cacheKey);
  240. if (tableFilterItemList == null)
  241. {
  242. // 获取租户实体数据表
  243. var entityTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
  244. && u.BaseType == typeof(EntityTenant));
  245. if (!entityTypes.Any()) return;
  246. var tableFilterItems = new List<TableFilterItem<object>>();
  247. foreach (var entityType in entityTypes)
  248. {
  249. // 排除非当前数据库实体
  250. var tAtt = entityType.GetCustomAttribute<TenantAttribute>();
  251. if ((tAtt != null && (string)db.CurrentConnectionConfig.ConfigId != tAtt.configId.ToString()) ||
  252. (tAtt == null && (string)db.CurrentConnectionConfig.ConfigId != SqlSugarConst.ConfigId))
  253. continue;
  254. Expression<Func<EntityTenant, bool>> dynamicExpression = u => u.TenantId == long.Parse(tenantId);
  255. var tableFilterItem = new TableFilterItem<object>(entityType, dynamicExpression);
  256. tableFilterItems.Add(tableFilterItem);
  257. db.QueryFilter.Add(tableFilterItem);
  258. }
  259. db.DataCache.Add(cacheKey, tableFilterItems);
  260. }
  261. else
  262. {
  263. tableFilterItemList.ForEach(u =>
  264. {
  265. db.QueryFilter.Add(u);
  266. });
  267. }
  268. }
  269. /// <summary>
  270. /// 配置用户机构范围过滤器
  271. /// </summary>
  272. private static void SetOrgEntityFilter(SqlSugarScopeProvider db)
  273. {
  274. var userId = App.User?.FindFirst(ClaimConst.UserId)?.Value;
  275. if (string.IsNullOrWhiteSpace(userId)) return;
  276. // 配置用户机构范围缓存
  277. var cacheKey = $"db:{db.CurrentConnectionConfig.ConfigId}:UserId:{userId}";
  278. var tableFilterItemList = db.DataCache.Get<List<TableFilterItem<object>>>(cacheKey);
  279. if (tableFilterItemList == null)
  280. {
  281. // 获取用户所属机构
  282. var orgIds = App.GetService<SysCacheService>().GetOrgIdList(long.Parse(userId));
  283. if (orgIds == null || orgIds.Count == 0) return;
  284. // 获取业务实体数据表
  285. var entityTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
  286. && u.BaseType == typeof(DataEntityBase));
  287. if (!entityTypes.Any()) return;
  288. var tableFilterItems = new List<TableFilterItem<object>>();
  289. foreach (var entityType in entityTypes)
  290. {
  291. // 排除非当前数据库实体
  292. var tAtt = entityType.GetCustomAttribute<TenantAttribute>();
  293. if ((tAtt != null && (string)db.CurrentConnectionConfig.ConfigId != tAtt.configId.ToString()) ||
  294. (tAtt == null && (string)db.CurrentConnectionConfig.ConfigId != SqlSugarConst.ConfigId))
  295. continue;
  296. Expression<Func<DataEntityBase, bool>> dynamicExpression = u => orgIds.Contains((long)u.CreateOrgId);
  297. var tableFilterItem = new TableFilterItem<object>(entityType, dynamicExpression);
  298. tableFilterItems.Add(tableFilterItem);
  299. db.QueryFilter.Add(tableFilterItem);
  300. }
  301. db.DataCache.Add(cacheKey, tableFilterItems);
  302. }
  303. else
  304. {
  305. tableFilterItemList.ForEach(u =>
  306. {
  307. db.QueryFilter.Add(u);
  308. });
  309. }
  310. }
  311. /// <summary>
  312. /// 配置自定义过滤器
  313. /// </summary>
  314. private static void SetCustomEntityFilter(SqlSugarScopeProvider db)
  315. {
  316. // 排除超管过滤
  317. if (App.User?.FindFirst(ClaimConst.SuperAdmin)?.Value == ((int)UserTypeEnum.SuperAdmin).ToString())
  318. return;
  319. // 配置用户机构范围缓存
  320. var cacheKey = $"db:{db.CurrentConnectionConfig.ConfigId}:Custom";
  321. var tableFilterItemList = db.DataCache.Get<List<TableFilterItem<object>>>(cacheKey);
  322. if (tableFilterItemList == null)
  323. {
  324. // 获取自定义实体过滤器
  325. var entityFilterTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
  326. && u.GetInterfaces().Any(i => i.HasImplementedRawGeneric(typeof(IEntityFilter))));
  327. if (!entityFilterTypes.Any()) return;
  328. var tableFilterItems = new List<TableFilterItem<object>>();
  329. foreach (var entityFilter in entityFilterTypes)
  330. {
  331. var instance = Activator.CreateInstance(entityFilter);
  332. var entityFilterMethod = entityFilter.GetMethod("AddEntityFilter");
  333. var entityFilters = ((IList)entityFilterMethod?.Invoke(instance, null))?.Cast<object>();
  334. if (entityFilters == null) continue;
  335. entityFilters.ForEach(u =>
  336. {
  337. var tableFilterItem = (TableFilterItem<object>)u;
  338. var entityType = tableFilterItem.GetType().GetProperty("type", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(tableFilterItem, null) as Type;
  339. // 排除非当前数据库实体
  340. var tAtt = entityType.GetCustomAttribute<TenantAttribute>();
  341. if ((tAtt != null && (string)db.CurrentConnectionConfig.ConfigId != tAtt.configId.ToString()) ||
  342. (tAtt == null && (string)db.CurrentConnectionConfig.ConfigId != SqlSugarConst.ConfigId))
  343. return;
  344. tableFilterItems.Add(tableFilterItem);
  345. db.QueryFilter.Add(tableFilterItem);
  346. });
  347. }
  348. db.DataCache.Add(cacheKey, tableFilterItems);
  349. }
  350. else
  351. {
  352. tableFilterItemList.ForEach(u =>
  353. {
  354. db.QueryFilter.Add(u);
  355. });
  356. }
  357. }
  358. }