SqlSugarSetup.cs 15 KB

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