SqlSugarSetup.cs 14 KB

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