SqlSugarSetup.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. // 麻省理工学院许可证
  2. //
  3. // 版权所有 (c) 2021-2023 zuohuaijun,大名科技(天津)有限公司 联系电话/微信:18020030720 QQ:515096995
  4. //
  5. // 特此免费授予获得本软件的任何人以处理本软件的权利,但须遵守以下条件:在所有副本或重要部分的软件中必须包括上述版权声明和本许可声明。
  6. //
  7. // 软件按“原样”提供,不提供任何形式的明示或暗示的保证,包括但不限于对适销性、适用性和非侵权的保证。
  8. // 在任何情况下,作者或版权持有人均不对任何索赔、损害或其他责任负责,无论是因合同、侵权或其他方式引起的,与软件或其使用或其他交易有关。
  9. namespace Admin.NET.Core;
  10. public static class SqlSugarSetup
  11. {
  12. /// <summary>
  13. /// SqlSugar 上下文初始化
  14. /// </summary>
  15. /// <param name="services"></param>
  16. public static void AddSqlSugar(this IServiceCollection services)
  17. {
  18. //// 注册雪花Id
  19. //var snowIdOpt = App.GetConfig<SnowIdOptions>("SnowId", true);
  20. //YitIdHelper.SetIdGenerator(snowIdOpt);
  21. // 注册雪花Id-支持分布式
  22. var snowIdOpt = App.GetConfig<SnowIdOptions>("SnowId", true);
  23. services.AddYitIdHelper(snowIdOpt);
  24. // 自定义 SqlSugar 雪花ID算法
  25. SnowFlakeSingle.WorkId = snowIdOpt.WorkerId;
  26. StaticConfig.CustomSnowFlakeFunc = () =>
  27. {
  28. return YitIdHelper.NextId();
  29. };
  30. var dbOptions = App.GetConfig<DbConnectionOptions>("DbConnection", true);
  31. dbOptions.ConnectionConfigs.ForEach(SetDbConfig);
  32. SqlSugarScope sqlSugar = new(dbOptions.ConnectionConfigs.Adapt<List<ConnectionConfig>>(), db =>
  33. {
  34. dbOptions.ConnectionConfigs.ForEach(config =>
  35. {
  36. var dbProvider = db.GetConnectionScope(config.ConfigId);
  37. SetDbAop(dbProvider, dbOptions.EnableConsoleSql);
  38. SetDbDiffLog(dbProvider, config);
  39. });
  40. });
  41. services.AddSingleton<ISqlSugarClient>(sqlSugar); // 单例注册
  42. services.AddScoped(typeof(SqlSugarRepository<>)); // 仓储注册
  43. services.AddUnitOfWork<SqlSugarUnitOfWork>(); // 事务与工作单元注册
  44. // 初始化数据库表结构及种子数据
  45. dbOptions.ConnectionConfigs.ForEach(config =>
  46. {
  47. InitDatabase(sqlSugar, config);
  48. });
  49. }
  50. /// <summary>
  51. /// 配置连接属性
  52. /// </summary>
  53. /// <param name="config"></param>
  54. public static void SetDbConfig(DbConnectionConfig config)
  55. {
  56. var configureExternalServices = new ConfigureExternalServices
  57. {
  58. EntityNameService = (type, entity) => // 处理表
  59. {
  60. entity.IsDisabledDelete = true; // 禁止删除非 sqlsugar 创建的列
  61. // 只处理贴了特性[SugarTable]表
  62. if (!type.GetCustomAttributes<SugarTable>().Any())
  63. return;
  64. if (config.DbSettings.EnableUnderLine && !entity.DbTableName.Contains('_'))
  65. entity.DbTableName = UtilMethods.ToUnderLine(entity.DbTableName); // 驼峰转下划线
  66. },
  67. EntityService = (type, column) => // 处理列
  68. {
  69. // 只处理贴了特性[SugarColumn]列
  70. if (!type.GetCustomAttributes<SugarColumn>().Any())
  71. return;
  72. if (new NullabilityInfoContext().Create(type).WriteState is NullabilityState.Nullable)
  73. column.IsNullable = true;
  74. if (config.DbSettings.EnableUnderLine && !column.IsIgnore && !column.DbColumnName.Contains('_'))
  75. column.DbColumnName = UtilMethods.ToUnderLine(column.DbColumnName); // 驼峰转下划线
  76. },
  77. DataInfoCacheService = new SqlSugarCache(),
  78. };
  79. config.ConfigureExternalServices = configureExternalServices;
  80. config.InitKeyType = InitKeyType.Attribute;
  81. config.IsAutoCloseConnection = true;
  82. config.MoreSettings = new ConnMoreSettings
  83. {
  84. IsAutoRemoveDataCache = true, // 启用自动删除缓存,所有增删改会自动调用.RemoveDataCache()
  85. IsAutoDeleteQueryFilter = true, // 启用删除查询过滤器
  86. IsAutoUpdateQueryFilter = true, // 启用更新查询过滤器
  87. SqlServerCodeFirstNvarchar = true // 采用Nvarchar
  88. };
  89. }
  90. /// <summary>
  91. /// 配置Aop
  92. /// </summary>
  93. /// <param name="db"></param>
  94. /// <param name="enableConsoleSql"></param>
  95. public static void SetDbAop(SqlSugarScopeProvider db, bool enableConsoleSql)
  96. {
  97. var config = db.CurrentConnectionConfig;
  98. // 设置超时时间
  99. db.Ado.CommandTimeOut = 30;
  100. // 打印SQL语句
  101. if (enableConsoleSql)
  102. {
  103. db.Aop.OnLogExecuting = (sql, pars) =>
  104. {
  105. var log = $"【{DateTime.Now}——执行SQL】\r\n{UtilMethods.GetSqlString(config.DbType, sql, pars)}\r\n";
  106. var originColor = Console.ForegroundColor;
  107. if (sql.StartsWith("SELECT", StringComparison.OrdinalIgnoreCase))
  108. Console.ForegroundColor = ConsoleColor.Green;
  109. if (sql.StartsWith("UPDATE", StringComparison.OrdinalIgnoreCase) || sql.StartsWith("INSERT", StringComparison.OrdinalIgnoreCase))
  110. Console.ForegroundColor = ConsoleColor.Yellow;
  111. if (sql.StartsWith("DELETE", StringComparison.OrdinalIgnoreCase))
  112. Console.ForegroundColor = ConsoleColor.Red;
  113. Console.WriteLine(log);
  114. Console.ForegroundColor = originColor;
  115. App.PrintToMiniProfiler("SqlSugar", "Info", log);
  116. };
  117. db.Aop.OnError = ex =>
  118. {
  119. if (ex.Parametres == null) return;
  120. var log = $"【{DateTime.Now}——错误SQL】\r\n{UtilMethods.GetSqlString(config.DbType, ex.Sql, (SugarParameter[])ex.Parametres)}\r\n";
  121. var originColor = Console.ForegroundColor;
  122. Console.ForegroundColor = ConsoleColor.DarkRed;
  123. Console.WriteLine(log);
  124. Console.ForegroundColor = originColor;
  125. App.PrintToMiniProfiler("SqlSugar", "Error", log);
  126. };
  127. db.Aop.OnLogExecuted = (sql, pars) =>
  128. {
  129. // 执行时间超过5秒
  130. if (db.Ado.SqlExecutionTime.TotalSeconds > 5)
  131. {
  132. var fileName = db.Ado.SqlStackTrace.FirstFileName; // 文件名
  133. var fileLine = db.Ado.SqlStackTrace.FirstLine; // 行号
  134. var firstMethodName = db.Ado.SqlStackTrace.FirstMethodName; // 方法名
  135. var log = $"【{DateTime.Now}——超时SQL】\r\n【所在文件名】:{fileName}\r\n【代码行数】:{fileLine}\r\n【方法名】:{firstMethodName}\r\n" + $"【SQL语句】:{UtilMethods.GetSqlString(config.DbType, sql, pars)}";
  136. var originColor = Console.ForegroundColor;
  137. Console.ForegroundColor = ConsoleColor.DarkYellow;
  138. Console.WriteLine(log);
  139. Console.ForegroundColor = originColor;
  140. App.PrintToMiniProfiler("SqlSugar", "Slow", log);
  141. }
  142. };
  143. }
  144. // 数据审计
  145. db.Aop.DataExecuting = (oldValue, entityInfo) =>
  146. {
  147. //// 演示环境判断
  148. //if (entityInfo.EntityColumnInfo.IsPrimarykey)
  149. //{
  150. // if (entityInfo.EntityName != nameof(SysJobDetail) && entityInfo.EntityName != nameof(SysJobTrigger) &&
  151. // entityInfo.EntityName != nameof(SysLogOp) && entityInfo.EntityName != nameof(SysLogVis) &&
  152. // entityInfo.EntityName != nameof(SysOnlineUser))
  153. // {
  154. // var isDemoEnv = App.GetService<SysConfigService>().GetConfigValue<bool>(CommonConst.SysDemoEnv).GetAwaiter().GetResult();
  155. // if (isDemoEnv)
  156. // throw Oops.Oh(ErrorCodeEnum.D1200);
  157. // }
  158. //}
  159. if (entityInfo.OperationType == DataFilterType.InsertByObject)
  160. {
  161. // 主键(long类型)且没有值的---赋值雪花Id
  162. if (entityInfo.EntityColumnInfo.IsPrimarykey && entityInfo.EntityColumnInfo.PropertyInfo.PropertyType == typeof(long))
  163. {
  164. var id = entityInfo.EntityColumnInfo.PropertyInfo.GetValue(entityInfo.EntityValue);
  165. if (id == null || (long)id == 0)
  166. entityInfo.SetValue(YitIdHelper.NextId());
  167. }
  168. if (entityInfo.PropertyName == nameof(EntityBase.CreateTime))
  169. entityInfo.SetValue(DateTime.Now);
  170. if (App.User != null)
  171. {
  172. if (entityInfo.PropertyName == nameof(EntityTenantId.TenantId))
  173. {
  174. var tenantId = ((dynamic)entityInfo.EntityValue).TenantId;
  175. if (tenantId == null || tenantId == 0)
  176. entityInfo.SetValue(App.User.FindFirst(ClaimConst.TenantId)?.Value);
  177. }
  178. else if (entityInfo.PropertyName == nameof(EntityBase.CreateUserId))
  179. {
  180. var createUserId = ((dynamic)entityInfo.EntityValue).CreateUserId;
  181. if (createUserId == 0 || createUserId == null)
  182. entityInfo.SetValue(App.User.FindFirst(ClaimConst.UserId)?.Value);
  183. }
  184. else if (entityInfo.PropertyName == nameof(EntityBase.CreateUserName))
  185. {
  186. var createUserName = ((dynamic)entityInfo.EntityValue).CreateUserName;
  187. if (string.IsNullOrEmpty(createUserName))
  188. entityInfo.SetValue(App.User.FindFirst(ClaimConst.RealName)?.Value);
  189. }
  190. else if (entityInfo.PropertyName == nameof(EntityBaseData.CreateOrgId))
  191. {
  192. var createOrgId = ((dynamic)entityInfo.EntityValue).CreateOrgId;
  193. if (createOrgId == 0 || createOrgId == null)
  194. entityInfo.SetValue(App.User.FindFirst(ClaimConst.OrgId)?.Value);
  195. }
  196. else if (entityInfo.PropertyName == nameof(EntityBaseData.CreateOrgName))
  197. {
  198. var createOrgName = ((dynamic)entityInfo.EntityValue).CreateOrgName;
  199. if (string.IsNullOrEmpty(createOrgName))
  200. entityInfo.SetValue(App.User.FindFirst(ClaimConst.OrgName)?.Value);
  201. }
  202. }
  203. }
  204. if (entityInfo.OperationType == DataFilterType.UpdateByObject)
  205. {
  206. if (entityInfo.PropertyName == nameof(EntityBase.UpdateTime))
  207. entityInfo.SetValue(DateTime.Now);
  208. else if (entityInfo.PropertyName == nameof(EntityBase.UpdateUserId))
  209. entityInfo.SetValue(App.User?.FindFirst(ClaimConst.UserId)?.Value);
  210. else if (entityInfo.PropertyName == nameof(EntityBase.UpdateUserName))
  211. entityInfo.SetValue(App.User?.FindFirst(ClaimConst.RealName)?.Value);
  212. }
  213. };
  214. // 超管排除其他过滤器
  215. if (App.User?.FindFirst(ClaimConst.AccountType)?.Value == ((int)AccountTypeEnum.SuperAdmin).ToString())
  216. return;
  217. // 配置假删除过滤器
  218. db.QueryFilter.AddTableFilter<IDeletedFilter>(u => u.IsDelete == false);
  219. // 配置租户过滤器
  220. var tenantId = App.User?.FindFirst(ClaimConst.TenantId)?.Value;
  221. if (!string.IsNullOrWhiteSpace(tenantId))
  222. db.QueryFilter.AddTableFilter<ITenantIdFilter>(u => u.TenantId == long.Parse(tenantId));
  223. // 配置用户机构(数据范围)过滤器
  224. SqlSugarFilter.SetOrgEntityFilter(db);
  225. // 配置自定义过滤器
  226. SqlSugarFilter.SetCustomEntityFilter(db);
  227. }
  228. /// <summary>
  229. /// 开启库表差异化日志
  230. /// </summary>
  231. /// <param name="db"></param>
  232. /// <param name="config"></param>
  233. private static void SetDbDiffLog(SqlSugarScopeProvider db, DbConnectionConfig config)
  234. {
  235. if (!config.DbSettings.EnableDiffLog) return;
  236. db.Aop.OnDiffLogEvent = async u =>
  237. {
  238. var logDiff = new SysLogDiff
  239. {
  240. // 操作后记录(字段描述、列名、值、表名、表描述)
  241. AfterData = JSON.Serialize(u.AfterData),
  242. // 操作前记录(字段描述、列名、值、表名、表描述)
  243. BeforeData = JSON.Serialize(u.BeforeData),
  244. // 传进来的对象
  245. BusinessData = JSON.Serialize(u.BusinessData),
  246. // 枚举(insert、update、delete)
  247. DiffType = u.DiffType.ToString(),
  248. Sql = UtilMethods.GetSqlString(config.DbType, u.Sql, u.Parameters),
  249. Parameters = JSON.Serialize(u.Parameters),
  250. Elapsed = u.Time == null ? 0 : (long)u.Time.Value.TotalMilliseconds
  251. };
  252. await db.Insertable(logDiff).ExecuteCommandAsync();
  253. Console.ForegroundColor = ConsoleColor.Red;
  254. Console.WriteLine(DateTime.Now + $"\r\n*****差异日志开始*****\r\n{Environment.NewLine}{JSON.Serialize(logDiff)}{Environment.NewLine}*****差异日志结束*****\r\n");
  255. };
  256. }
  257. /// <summary>
  258. /// 初始化数据库
  259. /// </summary>
  260. /// <param name="db"></param>
  261. /// <param name="config"></param>
  262. private static void InitDatabase(SqlSugarScope db, DbConnectionConfig config)
  263. {
  264. SqlSugarScopeProvider dbProvider = db.GetConnectionScope(config.ConfigId);
  265. // 初始化/创建数据库
  266. if (config.DbSettings.EnableInitDb)
  267. {
  268. if (config.DbType != SqlSugar.DbType.Oracle)
  269. dbProvider.DbMaintenance.CreateDatabase();
  270. }
  271. // 初始化表结构
  272. if (config.TableSettings.EnableInitTable)
  273. {
  274. var entityTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass && u.IsDefined(typeof(SugarTable), false))
  275. .WhereIF(config.TableSettings.EnableIncreTable, u => u.IsDefined(typeof(IncreTableAttribute), false)).ToList();
  276. if (config.ConfigId.ToString() == SqlSugarConst.MainConfigId) // 默认库(有系统表特性、没有日志表和租户表特性)
  277. entityTypes = entityTypes.Where(u => u.GetCustomAttributes<SysTableAttribute>().Any() || (!u.GetCustomAttributes<LogTableAttribute>().Any() && !u.GetCustomAttributes<TenantAttribute>().Any())).ToList();
  278. else if (config.ConfigId.ToString() == SqlSugarConst.LogConfigId) // 日志库
  279. entityTypes = entityTypes.Where(u => u.GetCustomAttributes<LogTableAttribute>().Any()).ToList();
  280. else
  281. entityTypes = entityTypes.Where(u => u.GetCustomAttribute<TenantAttribute>()?.configId.ToString() == config.ConfigId.ToString()).ToList(); // 自定义的库
  282. foreach (var entityType in entityTypes)
  283. {
  284. if (entityType.GetCustomAttribute<SplitTableAttribute>() == null)
  285. dbProvider.CodeFirst.InitTables(entityType);
  286. else
  287. dbProvider.CodeFirst.SplitTables().InitTables(entityType);
  288. }
  289. }
  290. // 初始化种子数据
  291. if (config.SeedSettings.EnableInitSeed)
  292. {
  293. var seedDataTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass && u.GetInterfaces().Any(i => i.HasImplementedRawGeneric(typeof(ISqlSugarEntitySeedData<>))))
  294. .WhereIF(config.SeedSettings.EnableIncreSeed, u => u.IsDefined(typeof(IncreSeedAttribute), false)).ToList();
  295. foreach (var seedType in seedDataTypes)
  296. {
  297. var entityType = seedType.GetInterfaces().First().GetGenericArguments().First();
  298. if (config.ConfigId.ToString() == SqlSugarConst.MainConfigId) // 默认库(有系统表特性、没有日志表和租户表特性)
  299. {
  300. if (entityType.GetCustomAttribute<SysTableAttribute>() == null && (entityType.GetCustomAttribute<LogTableAttribute>() != null || entityType.GetCustomAttribute<TenantAttribute>() != null))
  301. continue;
  302. }
  303. else if (config.ConfigId.ToString() == SqlSugarConst.LogConfigId) // 日志库
  304. {
  305. if (entityType.GetCustomAttribute<LogTableAttribute>() == null)
  306. continue;
  307. }
  308. else
  309. {
  310. var att = entityType.GetCustomAttribute<TenantAttribute>(); // 自定义的库
  311. if (att == null || att.configId.ToString() != config.ConfigId.ToString()) continue;
  312. }
  313. var instance = Activator.CreateInstance(seedType);
  314. var hasDataMethod = seedType.GetMethod("HasData");
  315. var seedData = ((IEnumerable)hasDataMethod?.Invoke(instance, null))?.Cast<object>();
  316. if (seedData == null) continue;
  317. var entityInfo = dbProvider.EntityMaintenance.GetEntityInfo(entityType);
  318. if (entityInfo.Columns.Any(u => u.IsPrimarykey))
  319. {
  320. // 按主键进行批量增加和更新
  321. var storage = dbProvider.StorageableByObject(seedData.ToList()).ToStorage();
  322. storage.AsInsertable.ExecuteCommand();
  323. storage.AsUpdateable.ExecuteCommand();
  324. }
  325. else
  326. {
  327. // 无主键则只进行插入
  328. if (!dbProvider.Queryable(entityInfo.DbTableName, entityInfo.DbTableName).Any())
  329. dbProvider.InsertableByObject(seedData.ToList()).ExecuteCommand();
  330. }
  331. }
  332. }
  333. }
  334. /// <summary>
  335. /// 初始化租户业务数据库
  336. /// </summary>
  337. /// <param name="iTenant"></param>
  338. /// <param name="config"></param>
  339. public static void InitTenantDatabase(ITenant iTenant, DbConnectionConfig config)
  340. {
  341. SetDbConfig(config);
  342. if (!iTenant.IsAnyConnection(config.ConfigId.ToString()))
  343. iTenant.AddConnection(config);
  344. var db = iTenant.GetConnectionScope(config.ConfigId.ToString());
  345. db.DbMaintenance.CreateDatabase();
  346. // 获取所有业务表-初始化租户库表结构(排除系统表、日志表、特定库表)
  347. var entityTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass && u.IsDefined(typeof(SugarTable), false) &&
  348. !u.IsDefined(typeof(SysTableAttribute), false) && !u.IsDefined(typeof(LogTableAttribute), false) && !u.IsDefined(typeof(TenantAttribute), false)).ToList();
  349. if (!entityTypes.Any()) return;
  350. foreach (var entityType in entityTypes)
  351. {
  352. var splitTable = entityType.GetCustomAttribute<SplitTableAttribute>();
  353. if (splitTable == null)
  354. db.CodeFirst.InitTables(entityType);
  355. else
  356. db.CodeFirst.SplitTables().InitTables(entityType);
  357. }
  358. }
  359. }