SqlSugarSetup.cs 19 KB

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