SqlSugarSetup.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. using DbType = SqlSugar.DbType;
  2. namespace Admin.NET.Core;
  3. public static class SqlSugarSetup
  4. {
  5. /// <summary>
  6. /// Sqlsugar上下文初始化
  7. /// </summary>
  8. /// <param name="services"></param>
  9. /// <param name="configuration"></param>
  10. public static void AddSqlSugarSetup(this IServiceCollection services, IConfiguration configuration)
  11. {
  12. var dbOptions = App.GetOptions<DbConnectionOptions>();
  13. var configureExternalServices = new ConfigureExternalServices
  14. {
  15. EntityService = (type, column) => // 修改列可空-1、带?问号 2、String类型若没有Required
  16. {
  17. if ((type.PropertyType.IsGenericType && type.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
  18. || (type.PropertyType == typeof(string) && type.GetCustomAttribute<RequiredAttribute>() == null))
  19. column.IsNullable = true;
  20. }
  21. };
  22. dbOptions.ConnectionConfigs.ForEach(config =>
  23. {
  24. config.ConfigureExternalServices = configureExternalServices;
  25. });
  26. SqlSugarScope sqlSugar = new(dbOptions.ConnectionConfigs, db =>
  27. {
  28. dbOptions.ConnectionConfigs.ForEach(config =>
  29. {
  30. var dbProvider = db.GetConnectionScope((string)config.ConfigId);
  31. // 设置超时时间
  32. dbProvider.Ado.CommandTimeOut = 30;
  33. // 打印SQL语句
  34. dbProvider.Aop.OnLogExecuting = (sql, pars) =>
  35. {
  36. if (sql.StartsWith("SELECT", StringComparison.OrdinalIgnoreCase))
  37. Console.ForegroundColor = ConsoleColor.Green;
  38. if (sql.StartsWith("UPDATE", StringComparison.OrdinalIgnoreCase) || sql.StartsWith("INSERT", StringComparison.OrdinalIgnoreCase))
  39. Console.ForegroundColor = ConsoleColor.White;
  40. if (sql.StartsWith("DELETE", StringComparison.OrdinalIgnoreCase))
  41. Console.ForegroundColor = ConsoleColor.Blue;
  42. Console.WriteLine("【" + DateTime.Now + "——执行SQL】\r\n" + UtilMethods.GetSqlString(DbType.MySql, sql, pars) + "\r\n");
  43. App.PrintToMiniProfiler("SqlSugar", "Info", sql + "\r\n" + db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
  44. };
  45. dbProvider.Aop.OnError = (ex) =>
  46. {
  47. Console.ForegroundColor = ConsoleColor.Red;
  48. var pars = db.Utilities.SerializeObject(((SugarParameter[])ex.Parametres).ToDictionary(it => it.ParameterName, it => it.Value));
  49. Console.WriteLine("【" + DateTime.Now + "——错误SQL】\r\n" + UtilMethods.GetSqlString(DbType.MySql, ex.Sql, (SugarParameter[])ex.Parametres) + "\r\n");
  50. App.PrintToMiniProfiler("SqlSugar", "Error", $"{ex.Message}{Environment.NewLine}{ex.Sql}{pars}{Environment.NewLine}");
  51. };
  52. // 数据审计
  53. dbProvider.Aop.DataExecuting = (oldValue, entityInfo) =>
  54. {
  55. // 新增操作
  56. if (entityInfo.OperationType == DataFilterType.InsertByObject)
  57. {
  58. // 主键(long类型)-赋值雪花Id
  59. if (entityInfo.EntityColumnInfo.IsPrimarykey && entityInfo.EntityColumnInfo.PropertyInfo.PropertyType == typeof(long))
  60. {
  61. var keyId = entityInfo.EntityColumnInfo.PropertyInfo.GetValue(entityInfo.EntityValue);
  62. //默认有id,则不用生成,有些业务需要提前设置id
  63. if (keyId == null || (long)keyId == 0)
  64. entityInfo.SetValue(Yitter.IdGenerator.YitIdHelper.NextId());
  65. }
  66. if (entityInfo.PropertyName == "CreateTime")
  67. entityInfo.SetValue(DateTime.Now);
  68. if (App.User != null)
  69. {
  70. if (entityInfo.PropertyName == "TenantId")
  71. {
  72. var tenantId = ((dynamic)entityInfo.EntityValue).TenantId;
  73. if (tenantId == null || tenantId == 0)
  74. entityInfo.SetValue(App.User.FindFirst(ClaimConst.TenantId)?.Value);
  75. }
  76. if (entityInfo.PropertyName == "CreateUserId")
  77. entityInfo.SetValue(App.User.FindFirst(ClaimConst.UserId)?.Value);
  78. if (entityInfo.PropertyName == "CreateOrgId")
  79. entityInfo.SetValue(App.User.FindFirst(ClaimConst.OrgId)?.Value);
  80. }
  81. }
  82. // 更新操作
  83. if (entityInfo.OperationType == DataFilterType.UpdateByObject)
  84. {
  85. if (entityInfo.PropertyName == "UpdateTime")
  86. entityInfo.SetValue(DateTime.Now);
  87. if (entityInfo.PropertyName == "UpdateUserId")
  88. entityInfo.SetValue(App.User?.FindFirst(ClaimConst.UserId)?.Value);
  89. }
  90. };
  91. // 差异日志
  92. dbProvider.Aop.OnDiffLogEvent = async u =>
  93. {
  94. if (!dbOptions.EnableDiffLog) return;
  95. var LogDiff = new SysLogDiff
  96. {
  97. // 操作后记录(字段描述、列名、值、表名、表描述)
  98. AfterData = Newtonsoft.Json.JsonConvert.SerializeObject(u.AfterData),
  99. // 操作前记录(字段描述、列名、值、表名、表描述)
  100. BeforeData = Newtonsoft.Json.JsonConvert.SerializeObject(u.BeforeData),
  101. // 传进来的对象
  102. BusinessData = Newtonsoft.Json.JsonConvert.SerializeObject(u.BusinessData),
  103. // 枚举(insert、update、delete)
  104. DiffType = u.DiffType.ToString(),
  105. Sql = UtilMethods.GetSqlString(DbType.MySql, u.Sql, u.Parameters),
  106. Parameters = Newtonsoft.Json.JsonConvert.SerializeObject(u.Parameters),
  107. Duration = u.Time == null ? 0 : (long)u.Time.Value.TotalMilliseconds
  108. };
  109. await db.GetConnectionScope(SqlSugarConst.ConfigId).Insertable(LogDiff).ExecuteCommandAsync();
  110. Console.ForegroundColor = ConsoleColor.Red;
  111. Console.WriteLine(DateTime.Now + $"\r\n**********差异日志开始**********\r\n{Environment.NewLine}{Newtonsoft.Json.JsonConvert.SerializeObject(LogDiff)}{Environment.NewLine}**********差异日志结束**********\r\n");
  112. };
  113. // 配置实体假删除过滤器
  114. SetDeletedEntityFilter(dbProvider);
  115. // 配置实体机构过滤器
  116. SetOrgEntityFilter(dbProvider);
  117. // 配置自定义实体过滤器
  118. SetCustomEntityFilter(dbProvider);
  119. // 配置租户实体过滤器
  120. SetTenantEntityFilter(dbProvider);
  121. });
  122. });
  123. // 初始化数据库结构及种子数据
  124. if (dbOptions.EnableInitTable)
  125. InitDataBase(sqlSugar, dbOptions);
  126. services.AddSingleton<ISqlSugarClient>(sqlSugar); // 单例注册
  127. services.AddScoped(typeof(SqlSugarRepository<>)); // 注册仓储
  128. services.AddUnitOfWork<SqlSugarUnitOfWork>(); // 注册事务与工作单元
  129. }
  130. /// <summary>
  131. /// 初始化数据库结构
  132. /// </summary>
  133. public static void InitDataBase(SqlSugarScope db, DbConnectionOptions dbOptions)
  134. {
  135. // 创建数据库
  136. dbOptions.ConnectionConfigs.ForEach(config =>
  137. {
  138. if (config.DbType != DbType.Oracle)
  139. db.GetConnectionScope(config.ConfigId).DbMaintenance.CreateDatabase();
  140. });
  141. // 获取所有实体表
  142. var entityTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
  143. && u.IsDefined(typeof(SugarTable), false) && !u.IsDefined(typeof(NotTableAttribute), false));
  144. if (!entityTypes.Any()) return;
  145. // 初始化库表结构
  146. foreach (var entityType in entityTypes)
  147. {
  148. var tAtt = entityType.GetCustomAttribute<TenantAttribute>();
  149. var provider = db.GetConnectionScope(tAtt == null ? SqlSugarConst.ConfigId : tAtt.configId);
  150. provider.CodeFirst.InitTables(entityType);
  151. }
  152. // 获取所有实体种子数据
  153. var seedDataTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
  154. && u.GetInterfaces().Any(i => i.HasImplementedRawGeneric(typeof(ISqlSugarEntitySeedData<>))));
  155. if (!seedDataTypes.Any()) return;
  156. foreach (var seedType in seedDataTypes)
  157. {
  158. var instance = Activator.CreateInstance(seedType);
  159. var hasDataMethod = seedType.GetMethod("HasData");
  160. var seedData = ((IEnumerable)hasDataMethod?.Invoke(instance, null))?.Cast<object>();
  161. if (seedData == null) continue;
  162. var entityType = seedType.GetInterfaces().First().GetGenericArguments().First();
  163. var tAtt = entityType.GetCustomAttribute<TenantAttribute>();
  164. var provider = db.GetConnectionScope(tAtt == null ? SqlSugarConst.ConfigId : tAtt.configId);
  165. var seedDataTable = seedData.ToList().ToDataTable();
  166. seedDataTable.TableName = db.EntityMaintenance.GetEntityInfo(entityType).DbTableName;
  167. if (seedDataTable.Columns.Contains(SqlSugarConst.PrimaryKey))
  168. {
  169. var storage = provider.Storageable(seedDataTable).WhereColumns(SqlSugarConst.PrimaryKey).ToStorage();
  170. // 如果添加一条种子数,sqlsugar 默认以 @param 的方式赋值,如果 PropertyType 为空,则默认数据类型为字符串。插入 pgsql 时候会报错,所以要忽略为空的值添加
  171. _ = ((InsertableProvider<Dictionary<string, object>>)storage.AsInsertable).IsSingle ?
  172. storage.AsInsertable.IgnoreColumns("UpdateTime", "UpdateUserId", "CreateUserId").ExecuteCommand() :
  173. storage.AsInsertable.ExecuteCommand();
  174. storage.AsUpdateable.ExecuteCommand();
  175. }
  176. else // 没有主键或者不是预定义的主键(没主键有重复的可能)
  177. {
  178. var storage = provider.Storageable(seedDataTable).ToStorage();
  179. storage.AsInsertable.ExecuteCommand();
  180. }
  181. }
  182. }
  183. /// <summary>
  184. /// 配置实体假删除过滤器
  185. /// </summary>
  186. public static void SetDeletedEntityFilter(SqlSugarScopeProvider db)
  187. {
  188. // 获取所有继承基类数据表集合
  189. var entityTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
  190. && (u.BaseType == typeof(EntityBase) || u.BaseType == typeof(EntityTenant) || u.BaseType == typeof(DataEntityBase)));
  191. if (!entityTypes.Any()) return;
  192. foreach (var entityType in entityTypes)
  193. {
  194. Expression<Func<DataEntityBase, bool>> dynamicExpression = u => u.IsDelete == false;
  195. db.QueryFilter.Add(new TableFilterItem<object>(entityType, dynamicExpression));
  196. }
  197. }
  198. /// <summary>
  199. /// 配置实体机构过滤器
  200. /// </summary>
  201. public static async void SetOrgEntityFilter(SqlSugarScopeProvider db)
  202. {
  203. // 获取业务数据表集合
  204. var dataEntityTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
  205. && u.BaseType == typeof(DataEntityBase));
  206. if (!dataEntityTypes.Any()) return;
  207. var userId = App.User?.FindFirst(ClaimConst.UserId)?.Value;
  208. if (string.IsNullOrWhiteSpace(userId)) return;
  209. // 获取用户机构Id集合
  210. var orgIds = await App.GetService<SysCacheService>().GetOrgIdList(long.Parse(userId));
  211. if (orgIds == null) return;
  212. foreach (var dataEntityType in dataEntityTypes)
  213. {
  214. Expression<Func<DataEntityBase, bool>> dynamicExpression = u => orgIds.Contains((long)u.CreateOrgId);
  215. db.QueryFilter.Add(new TableFilterItem<object>(dataEntityType, dynamicExpression));
  216. }
  217. }
  218. /// <summary>
  219. /// 配置自定义实体过滤器
  220. /// </summary>
  221. public static void SetCustomEntityFilter(SqlSugarScopeProvider db)
  222. {
  223. // 排除超管过滤
  224. if (App.User?.FindFirst(ClaimConst.SuperAdmin)?.Value == ((int)UserTypeEnum.SuperAdmin).ToString())
  225. return;
  226. // 获取继承自定义实体过滤器接口的类集合
  227. var entityFilterTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
  228. && u.GetInterfaces().Any(i => i.HasImplementedRawGeneric(typeof(IEntityFilter))));
  229. if (!entityFilterTypes.Any()) return;
  230. foreach (var entityFilter in entityFilterTypes)
  231. {
  232. var instance = Activator.CreateInstance(entityFilter);
  233. var entityFilterMethod = entityFilter.GetMethod("AddEntityFilter");
  234. var entityFilters = ((IList)entityFilterMethod?.Invoke(instance, null))?.Cast<object>();
  235. if (entityFilters == null) continue;
  236. foreach (TableFilterItem<object> filter in entityFilters)
  237. db.QueryFilter.Add(filter);
  238. }
  239. }
  240. /// <summary>
  241. /// 配置租户实体过滤器
  242. /// </summary>
  243. public static void SetTenantEntityFilter(SqlSugarScopeProvider db)
  244. {
  245. // 获取租户实体数据表集合
  246. var dataEntityTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
  247. && u.BaseType == typeof(EntityTenant));
  248. if (!dataEntityTypes.Any()) return;
  249. var tenantId = App.User?.FindFirst(ClaimConst.TenantId)?.Value;
  250. if (string.IsNullOrWhiteSpace(tenantId)) return;
  251. foreach (var dataEntityType in dataEntityTypes)
  252. {
  253. Expression<Func<EntityTenant, bool>> dynamicExpression = u => u.TenantId == long.Parse(tenantId);
  254. db.QueryFilter.Add(new TableFilterItem<object>(dataEntityType, dynamicExpression));
  255. }
  256. }
  257. }