SqlSugarSetup.cs 12 KB

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