SqlSugarSetup.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. // 麻省理工学院许可证
  2. //
  3. // 版权所有 (c) 2021-2023 zuohuaijun,大名科技(天津)有限公司 联系电话/微信:18020030720 QQ:515096995
  4. //
  5. // 特此免费授予获得本软件的任何人以处理本软件的权利,但须遵守以下条件:在所有副本或重要部分的软件中必须包括上述版权声明和本许可声明。
  6. //
  7. // 软件按“原样”提供,不提供任何形式的明示或暗示的保证,包括但不限于对适销性、适用性和非侵权的保证。
  8. // 在任何情况下,作者或版权持有人均不对任何索赔、损害或其他责任负责,无论是因合同、侵权或其他方式引起的,与软件或其使用或其他交易有关。
  9. namespace Admin.NET.Core;
  10. public static class SqlSugarSetup
  11. {
  12. /// <summary>
  13. /// SqlSugar 上下文初始化
  14. /// </summary>
  15. /// <param name="services"></param>
  16. public static void AddSqlSugar(this IServiceCollection services)
  17. {
  18. // 自定义 SqlSugar 雪花ID算法
  19. SnowFlakeSingle.WorkId = App.GetOptions<SnowIdOptions>().WorkerId;
  20. StaticConfig.CustomSnowFlakeFunc = () =>
  21. {
  22. return YitIdHelper.NextId();
  23. };
  24. var dbOptions = App.GetOptions<DbConnectionOptions>();
  25. dbOptions.ConnectionConfigs.ForEach(SetDbConfig);
  26. SqlSugarScope sqlSugar = new(dbOptions.ConnectionConfigs.Adapt<List<ConnectionConfig>>(), db =>
  27. {
  28. dbOptions.ConnectionConfigs.ForEach(config =>
  29. {
  30. var dbProvider = db.GetConnectionScope(config.ConfigId);
  31. SetDbAop(dbProvider);
  32. SetDbDiffLog(dbProvider, config);
  33. });
  34. });
  35. services.AddSingleton<ISqlSugarClient>(sqlSugar); // 单例注册
  36. services.AddScoped(typeof(SqlSugarRepository<>)); // 仓储注册
  37. services.AddUnitOfWork<SqlSugarUnitOfWork>(); // 事务与工作单元注册
  38. // 初始化数据库表结构及种子数据
  39. dbOptions.ConnectionConfigs.ForEach(config =>
  40. {
  41. InitDatabase(sqlSugar, config);
  42. });
  43. }
  44. /// <summary>
  45. /// 配置连接属性
  46. /// </summary>
  47. /// <param name="config"></param>
  48. public static void SetDbConfig(DbConnectionConfig config)
  49. {
  50. var configureExternalServices = new ConfigureExternalServices
  51. {
  52. EntityNameService = (type, entity) => // 处理表
  53. {
  54. // 只处理贴了特性 SugarTable 表
  55. if (!type.GetCustomAttributes<SugarTable>().Any())
  56. return;
  57. if (config.EnableUnderLine && !entity.DbTableName.Contains('_'))
  58. entity.DbTableName = UtilMethods.ToUnderLine(entity.DbTableName); // 驼峰转下划线
  59. },
  60. EntityService = (type, column) => // 处理列
  61. {
  62. // 只处理贴了特性 SugarColumn 列
  63. if (!type.GetCustomAttributes<SugarColumn>().Any())
  64. return;
  65. if (new NullabilityInfoContext().Create(type).WriteState is NullabilityState.Nullable)
  66. column.IsNullable = true;
  67. if (config.EnableUnderLine && !column.IsIgnore && !column.DbColumnName.Contains('_'))
  68. column.DbColumnName = UtilMethods.ToUnderLine(column.DbColumnName); // 驼峰转下划线
  69. if (config.DbType == SqlSugar.DbType.Oracle)
  70. {
  71. if (type.PropertyType == typeof(long) || type.PropertyType == typeof(long?))
  72. column.DataType = "number(18)";
  73. if (type.PropertyType == typeof(bool) || type.PropertyType == typeof(bool?))
  74. column.DataType = "number(1)";
  75. }
  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,
  85. IsAutoDeleteQueryFilter = true, // 启用删除查询过滤器
  86. IsAutoUpdateQueryFilter = true, // 启用更新查询过滤器
  87. SqlServerCodeFirstNvarchar = true // 采用Nvarchar
  88. };
  89. }
  90. /// <summary>
  91. /// 配置Aop
  92. /// </summary>
  93. /// <param name="db"></param>
  94. public static void SetDbAop(SqlSugarScopeProvider db)
  95. {
  96. var config = db.CurrentConnectionConfig;
  97. // 设置超时时间
  98. db.Ado.CommandTimeOut = 30;
  99. // 打印SQL语句
  100. db.Aop.OnLogExecuting = (sql, pars) =>
  101. {
  102. var originColor = Console.ForegroundColor;
  103. if (sql.StartsWith("SELECT", StringComparison.OrdinalIgnoreCase))
  104. Console.ForegroundColor = ConsoleColor.Green;
  105. if (sql.StartsWith("UPDATE", StringComparison.OrdinalIgnoreCase) || sql.StartsWith("INSERT", StringComparison.OrdinalIgnoreCase))
  106. Console.ForegroundColor = ConsoleColor.Yellow;
  107. if (sql.StartsWith("DELETE", StringComparison.OrdinalIgnoreCase))
  108. Console.ForegroundColor = ConsoleColor.Red;
  109. Console.WriteLine("【" + DateTime.Now + "——执行SQL】\r\n" + UtilMethods.GetSqlString(config.DbType, sql, pars) + "\r\n");
  110. Console.ForegroundColor = originColor;
  111. App.PrintToMiniProfiler("SqlSugar", "Info", sql + "\r\n" + db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
  112. };
  113. db.Aop.OnError = ex =>
  114. {
  115. if (ex.Parametres == null) return;
  116. var originColor = Console.ForegroundColor;
  117. Console.ForegroundColor = ConsoleColor.DarkRed;
  118. var pars = db.Utilities.SerializeObject(((SugarParameter[])ex.Parametres).ToDictionary(it => it.ParameterName, it => it.Value));
  119. Console.WriteLine("【" + DateTime.Now + "——错误SQL】\r\n" + UtilMethods.GetSqlString(config.DbType, ex.Sql, (SugarParameter[])ex.Parametres) + "\r\n");
  120. Console.ForegroundColor = originColor;
  121. App.PrintToMiniProfiler("SqlSugar", "Error", $"{ex.Message}{Environment.NewLine}{ex.Sql}{pars}{Environment.NewLine}");
  122. };
  123. // 数据审计
  124. db.Aop.DataExecuting = (oldValue, entityInfo) =>
  125. {
  126. // 演示环境判断
  127. if (entityInfo.EntityColumnInfo.IsPrimarykey)
  128. {
  129. if (entityInfo.EntityName != nameof(SysJobDetail) && entityInfo.EntityName != nameof(SysJobTrigger) &&
  130. entityInfo.EntityName != nameof(SysLogOp) && entityInfo.EntityName != nameof(SysLogVis) &&
  131. entityInfo.EntityName != nameof(SysOnlineUser))
  132. {
  133. var isDemoEnv = App.GetService<SysConfigService>().GetConfigValue<bool>(CommonConst.SysDemoEnv).GetAwaiter().GetResult();
  134. if (isDemoEnv)
  135. throw Oops.Oh(ErrorCodeEnum.D1200);
  136. }
  137. }
  138. if (entityInfo.OperationType == DataFilterType.InsertByObject)
  139. {
  140. // 主键(long类型)且没有值的---赋值雪花Id
  141. if (entityInfo.EntityColumnInfo.IsPrimarykey && entityInfo.EntityColumnInfo.PropertyInfo.PropertyType == typeof(long))
  142. {
  143. var id = entityInfo.EntityColumnInfo.PropertyInfo.GetValue(entityInfo.EntityValue);
  144. if (id == null || (long)id == 0)
  145. entityInfo.SetValue(YitIdHelper.NextId());
  146. }
  147. if (entityInfo.PropertyName == "CreateTime")
  148. entityInfo.SetValue(DateTime.Now);
  149. if (App.User != null)
  150. {
  151. if (entityInfo.PropertyName == "TenantId")
  152. {
  153. var tenantId = ((dynamic)entityInfo.EntityValue).TenantId;
  154. if (tenantId == null || tenantId == 0)
  155. entityInfo.SetValue(App.User.FindFirst(ClaimConst.TenantId)?.Value);
  156. }
  157. if (entityInfo.PropertyName == "CreateUserId")
  158. {
  159. var createUserId = ((dynamic)entityInfo.EntityValue).CreateUserId;
  160. if (createUserId == 0 || createUserId == null)
  161. entityInfo.SetValue(App.User.FindFirst(ClaimConst.UserId)?.Value);
  162. }
  163. if (entityInfo.PropertyName == "CreateOrgId")
  164. {
  165. var createOrgId = ((dynamic)entityInfo.EntityValue).CreateOrgId;
  166. if (createOrgId == 0 || createOrgId == null)
  167. entityInfo.SetValue(App.User.FindFirst(ClaimConst.OrgId)?.Value);
  168. }
  169. }
  170. }
  171. if (entityInfo.OperationType == DataFilterType.UpdateByObject)
  172. {
  173. if (entityInfo.PropertyName == "UpdateTime")
  174. entityInfo.SetValue(DateTime.Now);
  175. if (entityInfo.PropertyName == "UpdateUserId")
  176. entityInfo.SetValue(App.User?.FindFirst(ClaimConst.UserId)?.Value);
  177. }
  178. };
  179. // 超管时排除各种过滤器
  180. if (App.User?.FindFirst(ClaimConst.AccountType)?.Value == ((int)AccountTypeEnum.SuperAdmin).ToString())
  181. return;
  182. // 配置实体假删除过滤器
  183. db.QueryFilter.AddTableFilter<IDeletedFilter>(u => u.IsDelete == false);
  184. // 配置租户过滤器
  185. var tenantId = App.User?.FindFirst(ClaimConst.TenantId)?.Value;
  186. if (!string.IsNullOrWhiteSpace(tenantId))
  187. db.QueryFilter.AddTableFilter<ITenantIdFilter>(u => u.TenantId == long.Parse(tenantId));
  188. // 配置用户机构(数据范围)过滤器
  189. SqlSugarFilter.SetOrgEntityFilter(db);
  190. // 配置自定义过滤器
  191. SqlSugarFilter.SetCustomEntityFilter(db);
  192. }
  193. /// <summary>
  194. /// 开启库表差异化日志
  195. /// </summary>
  196. /// <param name="db"></param>
  197. /// <param name="config"></param>
  198. private static void SetDbDiffLog(SqlSugarScopeProvider db, DbConnectionConfig config)
  199. {
  200. if (!config.EnableDiffLog) return;
  201. db.Aop.OnDiffLogEvent = async u =>
  202. {
  203. var logDiff = new SysLogDiff
  204. {
  205. // 操作后记录(字段描述、列名、值、表名、表描述)
  206. AfterData = JSON.Serialize(u.AfterData),
  207. // 操作前记录(字段描述、列名、值、表名、表描述)
  208. BeforeData = JSON.Serialize(u.BeforeData),
  209. // 传进来的对象
  210. BusinessData = JSON.Serialize(u.BusinessData),
  211. // 枚举(insert、update、delete)
  212. DiffType = u.DiffType.ToString(),
  213. Sql = UtilMethods.GetSqlString(config.DbType, u.Sql, u.Parameters),
  214. Parameters = JSON.Serialize(u.Parameters),
  215. Elapsed = u.Time == null ? 0 : (long)u.Time.Value.TotalMilliseconds
  216. };
  217. await db.Insertable(logDiff).ExecuteCommandAsync();
  218. Console.ForegroundColor = ConsoleColor.Red;
  219. Console.WriteLine(DateTime.Now + $"\r\n*****差异日志开始*****\r\n{Environment.NewLine}{JSON.Serialize(logDiff)}{Environment.NewLine}*****差异日志结束*****\r\n");
  220. };
  221. }
  222. /// <summary>
  223. /// 初始化数据库
  224. /// </summary>
  225. /// <param name="db"></param>
  226. /// <param name="config"></param>
  227. private static void InitDatabase(SqlSugarScope db, DbConnectionConfig config)
  228. {
  229. if (!config.EnableInitDb) return;
  230. SqlSugarScopeProvider dbProvider = db.GetConnectionScope(config.ConfigId);
  231. // 创建数据库
  232. if (config.DbType != SqlSugar.DbType.Oracle)
  233. dbProvider.DbMaintenance.CreateDatabase();
  234. // 获取所有实体表-初始化表结构
  235. var entityTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass && u.IsDefined(typeof(SugarTable), false)).ToList();
  236. if (!entityTypes.Any()) return;
  237. foreach (var entityType in entityTypes)
  238. {
  239. var tAtt = entityType.GetCustomAttribute<TenantAttribute>();
  240. if (tAtt != null && tAtt.configId.ToString() != config.ConfigId) continue;
  241. if (tAtt == null && config.ConfigId != SqlSugarConst.ConfigId) continue;
  242. var splitTable = entityType.GetCustomAttribute<SplitTableAttribute>();
  243. if (splitTable == null)
  244. dbProvider.CodeFirst.InitTables(entityType);
  245. else
  246. dbProvider.CodeFirst.SplitTables().InitTables(entityType);
  247. }
  248. if (!config.EnableInitSeed) return;
  249. // 获取所有种子配置-初始化数据
  250. var seedDataTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
  251. && u.GetInterfaces().Any(i => i.HasImplementedRawGeneric(typeof(ISqlSugarEntitySeedData<>)))).ToList();
  252. if (!seedDataTypes.Any()) return;
  253. foreach (var seedType in seedDataTypes)
  254. {
  255. var instance = Activator.CreateInstance(seedType);
  256. var hasDataMethod = seedType.GetMethod("HasData");
  257. var seedData = ((IEnumerable)hasDataMethod?.Invoke(instance, null))?.Cast<object>();
  258. if (seedData == null) continue;
  259. var entityType = seedType.GetInterfaces().First().GetGenericArguments().First();
  260. var tAtt = entityType.GetCustomAttribute<TenantAttribute>();
  261. if (tAtt != null && tAtt.configId.ToString() != config.ConfigId) continue;
  262. if (tAtt == null && config.ConfigId != SqlSugarConst.ConfigId) continue;
  263. var entityInfo = dbProvider.EntityMaintenance.GetEntityInfo(entityType);
  264. if (entityInfo.Columns.Any(u => u.IsPrimarykey))
  265. {
  266. // 按主键进行批量增加和更新
  267. var storage = dbProvider.StorageableByObject(seedData.ToList()).ToStorage();
  268. storage.AsInsertable.ExecuteCommand();
  269. var ignoreUpdate = hasDataMethod.GetCustomAttribute<IgnoreUpdateAttribute>();
  270. if (ignoreUpdate == null) storage.AsUpdateable.ExecuteCommand();
  271. }
  272. else
  273. {
  274. // 无主键则只进行插入
  275. if (!dbProvider.Queryable(entityInfo.DbTableName, entityInfo.DbTableName).Any())
  276. dbProvider.InsertableByObject(seedData.ToList()).ExecuteCommand();
  277. }
  278. }
  279. }
  280. /// <summary>
  281. /// 初始化租户业务数据库
  282. /// </summary>
  283. /// <param name="iTenant"></param>
  284. /// <param name="config"></param>
  285. public static void InitTenantDatabase(ITenant iTenant, DbConnectionConfig config)
  286. {
  287. SetDbConfig(config);
  288. iTenant.AddConnection(config);
  289. var db = iTenant.GetConnectionScope(config.ConfigId);
  290. db.DbMaintenance.CreateDatabase();
  291. // 获取所有实体表-初始化租户业务表
  292. var entityTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
  293. && u.IsDefined(typeof(SugarTable), false) && !u.IsDefined(typeof(SystemTableAttribute), false)).ToList();
  294. if (!entityTypes.Any()) return;
  295. foreach (var entityType in entityTypes)
  296. {
  297. var splitTable = entityType.GetCustomAttribute<SplitTableAttribute>();
  298. if (splitTable == null)
  299. db.CodeFirst.InitTables(entityType);
  300. else
  301. db.CodeFirst.SplitTables().InitTables(entityType);
  302. }
  303. }
  304. }