SqlSugarSetup.cs 20 KB

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