SqlSugarSetup.cs 14 KB

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