SqlSugarSetup.cs 19 KB

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