SqlSugarSetup.cs 19 KB

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