SqlSugarSetup.cs 14 KB

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