SqlSugarSetup.cs 14 KB

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