SqlSugarSetup.cs 15 KB

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