SqlSugarSetup.cs 15 KB

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