SqlSugarSetup.cs 19 KB

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