SqlSugarSetup.cs 19 KB

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