SqlSugarSetup.cs 18 KB

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