SqlSugarSetup.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. // Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
  2. //
  3. // 本项目主要遵循 MIT 许可证和 Apache 许可证(版本 2.0)进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
  4. //
  5. // 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动!任何基于本项目二次开发而产生的一切法律纠纷和责任,我们不承担任何责任!
  6. namespace Admin.NET.Core;
  7. public static class SqlSugarSetup
  8. {
  9. // 多租户实例
  10. public static ITenant ITenant { get; set; }
  11. // 是否正在处理种子数据
  12. private static bool _isHandlingSeedData = false;
  13. /// <summary>
  14. /// SqlSugar 上下文初始化
  15. /// </summary>
  16. /// <param name="services"></param>
  17. public static void AddSqlSugar(this IServiceCollection services)
  18. {
  19. // 注册雪花Id
  20. var snowIdOpt = App.GetConfig<SnowIdOptions>("SnowId", true);
  21. YitIdHelper.SetIdGenerator(snowIdOpt);
  22. // 自定义 SqlSugar 雪花ID算法
  23. SnowFlakeSingle.WorkId = snowIdOpt.WorkerId;
  24. StaticConfig.CustomSnowFlakeFunc = () =>
  25. {
  26. return YitIdHelper.NextId();
  27. };
  28. var dbOptions = App.GetConfig<DbConnectionOptions>("DbConnection", true);
  29. dbOptions.ConnectionConfigs.ForEach(SetDbConfig);
  30. SqlSugarScope sqlSugar = new(dbOptions.ConnectionConfigs.Adapt<List<ConnectionConfig>>(), db =>
  31. {
  32. dbOptions.ConnectionConfigs.ForEach(config =>
  33. {
  34. var dbProvider = db.GetConnectionScope(config.ConfigId);
  35. SetDbAop(dbProvider, dbOptions.EnableConsoleSql);
  36. SetDbDiffLog(dbProvider, config);
  37. });
  38. });
  39. ITenant = sqlSugar;
  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, // 启用自动删除缓存,所有增删改会自动调用.RemoveDataCache()
  84. IsAutoDeleteQueryFilter = true, // 启用删除查询过滤器
  85. IsAutoUpdateQueryFilter = true, // 启用更新查询过滤器
  86. SqlServerCodeFirstNvarchar = true // 采用Nvarchar
  87. };
  88. // 若库类型是人大金仓则默认设置PG模式
  89. if (config.DbType == SqlSugar.DbType.Kdbndp)
  90. config.MoreSettings.DatabaseModel = SqlSugar.DbType.PostgreSQL; // 配置PG模式主要是兼容系统表差异
  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. Log.Error(log, ex);
  130. App.PrintToMiniProfiler("SqlSugar", "Error", log);
  131. };
  132. db.Aop.OnLogExecuted = (sql, pars) =>
  133. {
  134. //// 若参数值超过100个字符则进行截取
  135. //foreach (var par in pars)
  136. //{
  137. // if (par.DbType != System.Data.DbType.String || par.Value == null) continue;
  138. // if (par.Value.ToString().Length > 100)
  139. // par.Value = string.Concat(par.Value.ToString()[..100], "......");
  140. //}
  141. // 执行时间超过5秒时
  142. if (db.Ado.SqlExecutionTime.TotalSeconds > 5)
  143. {
  144. var fileName = db.Ado.SqlStackTrace.FirstFileName; // 文件名
  145. var fileLine = db.Ado.SqlStackTrace.FirstLine; // 行号
  146. var firstMethodName = db.Ado.SqlStackTrace.FirstMethodName; // 方法名
  147. var log = $"【{DateTime.Now}——超时SQL】\r\n【所在文件名】:{fileName}\r\n【代码行数】:{fileLine}\r\n【方法名】:{firstMethodName}\r\n" + $"【SQL语句】:{UtilMethods.GetNativeSql(sql, pars)}";
  148. Log.Warning(log);
  149. App.PrintToMiniProfiler("SqlSugar", "Slow", log);
  150. }
  151. };
  152. }
  153. // 数据审计
  154. db.Aop.DataExecuting = (oldValue, entityInfo) =>
  155. {
  156. // 若正在处理种子数据则直接返回
  157. if (_isHandlingSeedData) return;
  158. // 新增/插入
  159. if (entityInfo.OperationType == DataFilterType.InsertByObject)
  160. {
  161. // 若主键是长整型且空则赋值雪花Id
  162. if (entityInfo.EntityColumnInfo.IsPrimarykey && !entityInfo.EntityColumnInfo.IsIdentity && 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. // 若创建时间为空则赋值当前时间
  169. else if (entityInfo.PropertyName == nameof(EntityBase.CreateTime))
  170. {
  171. var createTime = entityInfo.EntityColumnInfo.PropertyInfo.GetValue(entityInfo.EntityValue)!;
  172. if (createTime == null || createTime.Equals(DateTime.MinValue))
  173. entityInfo.SetValue(DateTime.Now);
  174. }
  175. // 若当前用户非空(web线程时)
  176. if (App.User != null)
  177. {
  178. dynamic entityValue = entityInfo.EntityValue;
  179. if (entityInfo.PropertyName == nameof(EntityTenantId.TenantId))
  180. {
  181. var tenantId = entityValue.TenantId;
  182. if (tenantId == null || tenantId == 0)
  183. entityInfo.SetValue(App.User.FindFirst(ClaimConst.TenantId)?.Value);
  184. }
  185. else if (entityInfo.PropertyName == nameof(EntityBase.CreateUserId))
  186. {
  187. var createUserId = entityValue.CreateUserId;
  188. if (createUserId == 0 || createUserId == null)
  189. entityInfo.SetValue(App.User.FindFirst(ClaimConst.UserId)?.Value);
  190. }
  191. else if (entityInfo.PropertyName == nameof(EntityBase.CreateUserName))
  192. {
  193. var createUserName = entityValue.CreateUserName;
  194. if (string.IsNullOrEmpty(createUserName))
  195. entityInfo.SetValue(App.User.FindFirst(ClaimConst.RealName)?.Value);
  196. }
  197. else if (entityInfo.PropertyName == nameof(EntityBaseData.CreateOrgId))
  198. {
  199. var createOrgId = entityValue.CreateOrgId;
  200. if (createOrgId == 0 || createOrgId == null)
  201. entityInfo.SetValue(App.User.FindFirst(ClaimConst.OrgId)?.Value);
  202. }
  203. else if (entityInfo.PropertyName == nameof(EntityBaseData.CreateOrgName))
  204. {
  205. var createOrgName = entityValue.CreateOrgName;
  206. if (string.IsNullOrEmpty(createOrgName))
  207. entityInfo.SetValue(App.User.FindFirst(ClaimConst.OrgName)?.Value);
  208. }
  209. }
  210. }
  211. // 编辑/更新
  212. else if (entityInfo.OperationType == DataFilterType.UpdateByObject)
  213. {
  214. if (entityInfo.PropertyName == nameof(EntityBase.UpdateTime))
  215. entityInfo.SetValue(DateTime.Now);
  216. else if (entityInfo.PropertyName == nameof(EntityBase.UpdateUserId))
  217. entityInfo.SetValue(App.User?.FindFirst(ClaimConst.UserId)?.Value);
  218. else if (entityInfo.PropertyName == nameof(EntityBase.UpdateUserName))
  219. entityInfo.SetValue(App.User?.FindFirst(ClaimConst.RealName)?.Value);
  220. }
  221. };
  222. // 超管排除其他过滤器
  223. if (App.User?.FindFirst(ClaimConst.AccountType)?.Value == ((int)AccountTypeEnum.SuperAdmin).ToString())
  224. return;
  225. // 配置假删除过滤器
  226. db.QueryFilter.AddTableFilter<IDeletedFilter>(u => u.IsDelete == false);
  227. // 配置租户过滤器
  228. var tenantId = App.User?.FindFirst(ClaimConst.TenantId)?.Value;
  229. if (!string.IsNullOrWhiteSpace(tenantId))
  230. db.QueryFilter.AddTableFilter<ITenantIdFilter>(u => u.TenantId == long.Parse(tenantId));
  231. // 配置用户机构(数据范围)过滤器
  232. SqlSugarFilter.SetOrgEntityFilter(db);
  233. // 配置自定义过滤器
  234. SqlSugarFilter.SetCustomEntityFilter(db);
  235. }
  236. /// <summary>
  237. /// 开启库表差异化日志
  238. /// </summary>
  239. /// <param name="db"></param>
  240. /// <param name="config"></param>
  241. private static void SetDbDiffLog(SqlSugarScopeProvider db, DbConnectionConfig config)
  242. {
  243. if (!config.DbSettings.EnableDiffLog) return;
  244. db.Aop.OnDiffLogEvent = async u =>
  245. {
  246. var logDiff = new SysLogDiff
  247. {
  248. // 操作后记录(字段描述、列名、值、表名、表描述)
  249. AfterData = JSON.Serialize(u.AfterData),
  250. // 操作前记录(字段描述、列名、值、表名、表描述)
  251. BeforeData = JSON.Serialize(u.BeforeData),
  252. // 传进来的对象(如果对象为空,则使用首个数据的表名作为业务对象)
  253. BusinessData = u.BusinessData == null ? u.AfterData.FirstOrDefault()?.TableName : JSON.Serialize(u.BusinessData),
  254. // 枚举(insert、update、delete)
  255. DiffType = u.DiffType.ToString(),
  256. Sql = UtilMethods.GetNativeSql(u.Sql, u.Parameters),
  257. Parameters = JSON.Serialize(u.Parameters),
  258. Elapsed = u.Time == null ? 0 : (long)u.Time.Value.TotalMilliseconds
  259. };
  260. var logDb = ITenant.IsAnyConnection(SqlSugarConst.LogConfigId) ? ITenant.GetConnectionScope(SqlSugarConst.LogConfigId) : db;
  261. await logDb.CopyNew().Insertable(logDiff).ExecuteCommandAsync();
  262. Console.ForegroundColor = ConsoleColor.Red;
  263. Console.WriteLine(DateTime.Now + $"\r\n*****开始差异日志*****\r\n{Environment.NewLine}{JSON.Serialize(logDiff)}{Environment.NewLine}*****结束差异日志*****\r\n");
  264. };
  265. }
  266. /// <summary>
  267. /// 初始化数据库
  268. /// </summary>
  269. /// <param name="db"></param>
  270. /// <param name="config"></param>
  271. private static void InitDatabase(SqlSugarScope db, DbConnectionConfig config)
  272. {
  273. SqlSugarScopeProvider dbProvider = db.GetConnectionScope(config.ConfigId);
  274. // 初始化/创建数据库
  275. if (config.DbSettings.EnableInitDb)
  276. {
  277. Log.Information($"初始化数据库 {config.DbType} - {config.ConfigId} - {config.ConnectionString}");
  278. if (config.DbType != SqlSugar.DbType.Oracle)
  279. dbProvider.DbMaintenance.CreateDatabase();
  280. }
  281. // 初始化表结构
  282. if (config.TableSettings.EnableInitTable)
  283. {
  284. Log.Information($"初始化表结构 {config.DbType} - {config.ConfigId}");
  285. var entityTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass && u.IsDefined(typeof(SugarTable), false))
  286. .Where(u => !u.GetCustomAttributes<IgnoreTableAttribute>().Any())
  287. .WhereIF(config.TableSettings.EnableIncreTable, u => u.IsDefined(typeof(IncreTableAttribute), false)).ToList();
  288. if (config.ConfigId.ToString() == SqlSugarConst.MainConfigId) // 默认库(有系统表特性、没有日志表和租户表特性)
  289. entityTypes = entityTypes.Where(u => u.GetCustomAttributes<SysTableAttribute>().Any() || (!u.GetCustomAttributes<LogTableAttribute>().Any() && !u.GetCustomAttributes<TenantAttribute>().Any())).ToList();
  290. else if (config.ConfigId.ToString() == SqlSugarConst.LogConfigId) // 日志库
  291. entityTypes = entityTypes.Where(u => u.GetCustomAttributes<LogTableAttribute>().Any()).ToList();
  292. else
  293. entityTypes = entityTypes.Where(u => u.GetCustomAttribute<TenantAttribute>()?.configId.ToString() == config.ConfigId.ToString()).ToList(); // 自定义的库
  294. int count = 0, sum = entityTypes.Count;
  295. foreach (var entityType in entityTypes)
  296. {
  297. Console.WriteLine($"创建表 {entityType} ({config.ConfigId} - {++count}/{sum})");
  298. if (entityType.GetCustomAttribute<SplitTableAttribute>() == null)
  299. dbProvider.CodeFirst.InitTables(entityType);
  300. else
  301. dbProvider.CodeFirst.SplitTables().InitTables(entityType);
  302. }
  303. }
  304. // 初始化种子数据
  305. if (config.SeedSettings.EnableInitSeed)
  306. {
  307. _isHandlingSeedData = true;
  308. Log.Information($"初始化种子数据 {config.DbType} - {config.ConfigId}");
  309. var seedDataTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass && u.GetInterfaces().Any(i => i.HasImplementedRawGeneric(typeof(ISqlSugarEntitySeedData<>))))
  310. .WhereIF(config.SeedSettings.EnableIncreSeed, u => u.IsDefined(typeof(IncreSeedAttribute), false))
  311. .OrderBy(u => u.GetCustomAttributes(typeof(SeedDataAttribute), false).Length > 0 ? ((SeedDataAttribute)u.GetCustomAttributes(typeof(SeedDataAttribute), false)[0]).Order : 0).ToList();
  312. int count = 0, sum = seedDataTypes.Count;
  313. foreach (var seedType in seedDataTypes)
  314. {
  315. var entityType = seedType.GetInterfaces().First().GetGenericArguments().First();
  316. if (config.ConfigId.ToString() == SqlSugarConst.MainConfigId) // 默认库(有系统表特性、没有日志表和租户表特性)
  317. {
  318. if (entityType.GetCustomAttribute<SysTableAttribute>() == null && (entityType.GetCustomAttribute<LogTableAttribute>() != null || entityType.GetCustomAttribute<TenantAttribute>() != null))
  319. continue;
  320. }
  321. else if (config.ConfigId.ToString() == SqlSugarConst.LogConfigId) // 日志库
  322. {
  323. if (entityType.GetCustomAttribute<LogTableAttribute>() == null)
  324. continue;
  325. }
  326. else
  327. {
  328. var att = entityType.GetCustomAttribute<TenantAttribute>(); // 自定义的库
  329. if (att == null || att.configId.ToString() != config.ConfigId.ToString()) continue;
  330. }
  331. var instance = Activator.CreateInstance(seedType);
  332. var hasDataMethod = seedType.GetMethod("HasData");
  333. var seedData = ((IEnumerable)hasDataMethod?.Invoke(instance, null))?.Cast<object>();
  334. if (seedData == null) continue;
  335. var entityInfo = dbProvider.EntityMaintenance.GetEntityInfo(entityType);
  336. Console.WriteLine($"添加数据 {entityInfo.DbTableName} ({config.ConfigId} - {++count}/{sum},数据量:{seedData.Count()})");
  337. if (entityType.GetCustomAttribute<SplitTableAttribute>(true) != null)
  338. {
  339. //拆分表的操作需要实体类型,而通过反射很难实现
  340. //所以,这里将Init方法写在“种子数据类”内部,再传入 db 反射调用
  341. var hasInitMethod = seedType.GetMethod("Init");
  342. var parameters = new object[] { db };
  343. hasInitMethod?.Invoke(instance, parameters);
  344. }
  345. else
  346. {
  347. if (entityInfo.Columns.Any(u => u.IsPrimarykey))
  348. {
  349. // 按主键进行批量增加和更新
  350. var storage = dbProvider.StorageableByObject(seedData.ToList()).ToStorage();
  351. // 先修改再插入,否则会更新修改时间字段
  352. if (seedType.GetCustomAttribute<IgnoreUpdateSeedAttribute>() == null) // 有忽略更新种子特性时则不更新
  353. {
  354. int updateCount = storage.AsUpdateable.IgnoreColumns(entityInfo.Columns.Where(u => u.PropertyInfo.GetCustomAttribute<IgnoreUpdateSeedColumnAttribute>() != null).Select(u => u.PropertyName).ToArray()).ExecuteCommand();
  355. Console.WriteLine($" 修改 {updateCount}/{seedData.Count()} 条记录");
  356. }
  357. int insertCount = storage.AsInsertable.ExecuteCommand();
  358. Console.WriteLine($" 插入 {insertCount}/{seedData.Count()} 条记录");
  359. }
  360. else
  361. {
  362. // 无主键则只进行插入
  363. if (!dbProvider.Queryable(entityInfo.DbTableName, entityInfo.DbTableName).Any())
  364. dbProvider.InsertableByObject(seedData.ToList()).ExecuteCommand();
  365. }
  366. }
  367. }
  368. _isHandlingSeedData = false;
  369. }
  370. }
  371. /// <summary>
  372. /// 初始化租户业务数据库
  373. /// </summary>
  374. /// <param name="iTenant"></param>
  375. /// <param name="config"></param>
  376. public static void InitTenantDatabase(ITenant iTenant, DbConnectionConfig config)
  377. {
  378. SetDbConfig(config);
  379. if (!iTenant.IsAnyConnection(config.ConfigId.ToString()))
  380. iTenant.AddConnection(config);
  381. var db = iTenant.GetConnectionScope(config.ConfigId.ToString());
  382. db.DbMaintenance.CreateDatabase();
  383. // 获取所有业务表-初始化租户库表结构(排除系统表、日志表、特定库表)
  384. var entityTypes = App.EffectiveTypes
  385. .Where(u => !u.GetCustomAttributes<IgnoreTableAttribute>().Any())
  386. .Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass && u.IsDefined(typeof(SugarTable), false) &&
  387. !u.IsDefined(typeof(SysTableAttribute), false) && !u.IsDefined(typeof(LogTableAttribute), false) && !u.IsDefined(typeof(TenantAttribute), false)).ToList();
  388. if (entityTypes.Count == 0) return;
  389. foreach (var entityType in entityTypes)
  390. {
  391. var splitTable = entityType.GetCustomAttribute<SplitTableAttribute>();
  392. if (splitTable == null)
  393. db.CodeFirst.InitTables(entityType);
  394. else
  395. db.CodeFirst.SplitTables().InitTables(entityType);
  396. }
  397. }
  398. }