SqlSugarSetup.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  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.DbType == SqlSugar.DbType.Oracle || !config.EnableInitDb) 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. //添加分表特性后,初始化数据库时自动分表
  157. var splitTable = entityType.GetCustomAttribute<SplitTableAttribute>();
  158. if (splitTable == null)
  159. {
  160. db2.CodeFirst.InitTables(entityType);
  161. }
  162. else
  163. {
  164. db2.CodeFirst.SplitTables().InitTables(entityType);
  165. }
  166. }
  167. // 获取所有种子配置-初始化数据
  168. var seedDataTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
  169. && u.GetInterfaces().Any(i => i.HasImplementedRawGeneric(typeof(ISqlSugarEntitySeedData<>))));
  170. if (!seedDataTypes.Any()) return;
  171. foreach (var seedType in seedDataTypes)
  172. {
  173. var instance = Activator.CreateInstance(seedType);
  174. var hasDataMethod = seedType.GetMethod("HasData");
  175. var seedData = ((IEnumerable)hasDataMethod?.Invoke(instance, null))?.Cast<object>();
  176. if (seedData == null) continue;
  177. var entityType = seedType.GetInterfaces().First().GetGenericArguments().First();
  178. var tAtt = entityType.GetCustomAttribute<TenantAttribute>();
  179. var configId = tAtt == null ? SqlSugarConst.ConfigId : tAtt.configId.ToString();
  180. if (!dbOptions.ConnectionConfigs.FirstOrDefault(u => u.ConfigId == configId).EnableInitDb)
  181. continue;
  182. var db2 = db.GetConnectionScope(configId);
  183. var seedDataTable = seedData.ToList().ToDataTable();
  184. seedDataTable.TableName = db.EntityMaintenance.GetEntityInfo(entityType).DbTableName;
  185. if (seedDataTable.Columns.Contains(SqlSugarConst.PrimaryKey))
  186. {
  187. var storage = db2.Storageable(seedDataTable).WhereColumns(SqlSugarConst.PrimaryKey).ToStorage();
  188. storage.AsInsertable.ExecuteCommand();
  189. storage.AsUpdateable.ExecuteCommand();
  190. }
  191. else // 没有主键或者不是预定义的主键(没主键有重复的可能)
  192. {
  193. var storage = db2.Storageable(seedDataTable).ToStorage();
  194. storage.AsInsertable.ExecuteCommand();
  195. }
  196. }
  197. }
  198. /// <summary>
  199. /// 配置实体假删除过滤器
  200. /// </summary>
  201. private static void SetDeletedEntityFilter(SqlSugarScopeProvider db)
  202. {
  203. // 配置实体假删除缓存
  204. var cacheKey = $"DB:{db.CurrentConnectionConfig.ConfigId}:FAKEDELETE";
  205. var tableFilterItemList = db.DataCache.Get<List<TableFilterItem<object>>>(cacheKey);
  206. if (tableFilterItemList == null)
  207. {
  208. // 获取基类实体数据表
  209. var entityTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
  210. && (u.BaseType == typeof(EntityBase) || u.BaseType == typeof(EntityTenant) || u.BaseType == typeof(DataEntityBase)));
  211. if (!entityTypes.Any()) return;
  212. var tableFilterItems = new List<TableFilterItem<object>>();
  213. foreach (var entityType in entityTypes)
  214. {
  215. // 排除非当前数据库实体
  216. var tAtt = entityType.GetCustomAttribute<TenantAttribute>();
  217. if ((tAtt != null && (string)db.CurrentConnectionConfig.ConfigId != tAtt.configId.ToString()) ||
  218. (tAtt == null && (string)db.CurrentConnectionConfig.ConfigId != SqlSugarConst.ConfigId))
  219. continue;
  220. Expression<Func<DataEntityBase, bool>> dynamicExpression = u => u.IsDelete == false;
  221. var tableFilterItem = new TableFilterItem<object>(entityType, dynamicExpression);
  222. tableFilterItems.Add(tableFilterItem);
  223. db.QueryFilter.Add(tableFilterItem);
  224. }
  225. db.DataCache.Add(cacheKey, tableFilterItems);
  226. }
  227. else
  228. {
  229. tableFilterItemList.ForEach(u =>
  230. {
  231. db.QueryFilter.Add(u);
  232. });
  233. }
  234. }
  235. /// <summary>
  236. /// 配置租户过滤器
  237. /// </summary>
  238. private static void SetTenantEntityFilter(SqlSugarScopeProvider db)
  239. {
  240. var tenantId = App.User?.FindFirst(ClaimConst.TenantId)?.Value;
  241. if (string.IsNullOrWhiteSpace(tenantId)) return;
  242. // 配置租户缓存
  243. var cacheKey = $"DB:{db.CurrentConnectionConfig.ConfigId}:TENANTID:{tenantId}";
  244. var tableFilterItemList = db.DataCache.Get<List<TableFilterItem<object>>>(cacheKey);
  245. if (tableFilterItemList == null)
  246. {
  247. // 获取租户实体数据表
  248. var entityTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
  249. && u.BaseType == typeof(EntityTenant));
  250. if (!entityTypes.Any()) return;
  251. var tableFilterItems = new List<TableFilterItem<object>>();
  252. foreach (var entityType in entityTypes)
  253. {
  254. // 排除非当前数据库实体
  255. var tAtt = entityType.GetCustomAttribute<TenantAttribute>();
  256. if ((tAtt != null && (string)db.CurrentConnectionConfig.ConfigId != tAtt.configId.ToString()) ||
  257. (tAtt == null && (string)db.CurrentConnectionConfig.ConfigId != SqlSugarConst.ConfigId))
  258. continue;
  259. Expression<Func<EntityTenant, bool>> dynamicExpression = u => u.TenantId == long.Parse(tenantId);
  260. var tableFilterItem = new TableFilterItem<object>(entityType, dynamicExpression);
  261. tableFilterItems.Add(tableFilterItem);
  262. db.QueryFilter.Add(tableFilterItem);
  263. }
  264. db.DataCache.Add(cacheKey, tableFilterItems);
  265. }
  266. else
  267. {
  268. tableFilterItemList.ForEach(u =>
  269. {
  270. db.QueryFilter.Add(u);
  271. });
  272. }
  273. }
  274. /// <summary>
  275. /// 配置用户机构范围过滤器
  276. /// </summary>
  277. private static void SetOrgEntityFilter(SqlSugarScopeProvider db)
  278. {
  279. var userId = App.User?.FindFirst(ClaimConst.UserId)?.Value;
  280. if (string.IsNullOrWhiteSpace(userId)) return;
  281. // 配置用户机构范围缓存
  282. var cacheKey = $"DB:{db.CurrentConnectionConfig.ConfigId}:USERID:{userId}";
  283. var tableFilterItemList = db.DataCache.Get<List<TableFilterItem<object>>>(cacheKey);
  284. if (tableFilterItemList == null)
  285. {
  286. // 获取用户所属机构
  287. var orgIds = App.GetService<SysCacheService>().GetOrgIdList(long.Parse(userId));
  288. if (orgIds == null || orgIds.Count == 0) return;
  289. // 获取业务实体数据表
  290. var entityTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
  291. && u.BaseType == typeof(DataEntityBase));
  292. if (!entityTypes.Any()) return;
  293. var tableFilterItems = new List<TableFilterItem<object>>();
  294. foreach (var entityType in entityTypes)
  295. {
  296. // 排除非当前数据库实体
  297. var tAtt = entityType.GetCustomAttribute<TenantAttribute>();
  298. if ((tAtt != null && (string)db.CurrentConnectionConfig.ConfigId != tAtt.configId.ToString()) ||
  299. (tAtt == null && (string)db.CurrentConnectionConfig.ConfigId != SqlSugarConst.ConfigId))
  300. continue;
  301. Expression<Func<DataEntityBase, bool>> dynamicExpression = u => orgIds.Contains((long)u.CreateOrgId);
  302. var tableFilterItem = new TableFilterItem<object>(entityType, dynamicExpression);
  303. tableFilterItems.Add(tableFilterItem);
  304. db.QueryFilter.Add(tableFilterItem);
  305. }
  306. db.DataCache.Add(cacheKey, tableFilterItems);
  307. }
  308. else
  309. {
  310. tableFilterItemList.ForEach(u =>
  311. {
  312. db.QueryFilter.Add(u);
  313. });
  314. }
  315. }
  316. /// <summary>
  317. /// 配置自定义过滤器
  318. /// </summary>
  319. private static void SetCustomEntityFilter(SqlSugarScopeProvider db)
  320. {
  321. // 排除超管过滤
  322. if (App.User?.FindFirst(ClaimConst.SuperAdmin)?.Value == ((int)UserTypeEnum.SuperAdmin).ToString())
  323. return;
  324. // 配置用户机构范围缓存
  325. var cacheKey = $"DB:{db.CurrentConnectionConfig.ConfigId}:CUSTOM";
  326. var tableFilterItemList = db.DataCache.Get<List<TableFilterItem<object>>>(cacheKey);
  327. if (tableFilterItemList == null)
  328. {
  329. // 获取自定义实体过滤器
  330. var entityFilterTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
  331. && u.GetInterfaces().Any(i => i.HasImplementedRawGeneric(typeof(IEntityFilter))));
  332. if (!entityFilterTypes.Any()) return;
  333. var tableFilterItems = new List<TableFilterItem<object>>();
  334. foreach (var entityFilter in entityFilterTypes)
  335. {
  336. var instance = Activator.CreateInstance(entityFilter);
  337. var entityFilterMethod = entityFilter.GetMethod("AddEntityFilter");
  338. var entityFilters = ((IList)entityFilterMethod?.Invoke(instance, null))?.Cast<object>();
  339. if (entityFilters == null) continue;
  340. entityFilters.ForEach(u =>
  341. {
  342. var tableFilterItem = (TableFilterItem<object>)u;
  343. var entityType = tableFilterItem.GetType().GetProperty("type", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(tableFilterItem, null) as Type;
  344. // 排除非当前数据库实体
  345. var tAtt = entityType.GetCustomAttribute<TenantAttribute>();
  346. if ((tAtt != null && (string)db.CurrentConnectionConfig.ConfigId != tAtt.configId.ToString()) ||
  347. (tAtt == null && (string)db.CurrentConnectionConfig.ConfigId != SqlSugarConst.ConfigId))
  348. return;
  349. tableFilterItems.Add(tableFilterItem);
  350. db.QueryFilter.Add(tableFilterItem);
  351. });
  352. }
  353. db.DataCache.Add(cacheKey, tableFilterItems);
  354. }
  355. else
  356. {
  357. tableFilterItemList.ForEach(u =>
  358. {
  359. db.QueryFilter.Add(u);
  360. });
  361. }
  362. }
  363. }