SqlSugarSetup.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  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. // SqlSugarScope用AddSingleton单例
  13. services.AddSingleton<ISqlSugarClient>(provider =>
  14. {
  15. var dbOptions = App.GetOptions<ConnectionStringsOptions>();
  16. DealConnectionStr(ref dbOptions); // 处理本地库根目录路径
  17. var connectionConfigs = SqlSugarConst.ConnectionConfigs; // 方便多库生成
  18. var configureExternalServices = new ConfigureExternalServices
  19. {
  20. EntityService = (type, column) => // 修改列可空
  21. {
  22. // 1、带?问号 2、String类型若没有Required
  23. if ((type.PropertyType.IsGenericType && type.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
  24. || (type.PropertyType == typeof(string) && type.GetCustomAttribute<RequiredAttribute>() == null))
  25. column.IsNullable = true;
  26. },
  27. };
  28. var defaultConnection = new ConnectionConfig()
  29. {
  30. DbType = (DbType)Convert.ToInt32(Enum.Parse(typeof(DbType), dbOptions.DefaultDbType)),
  31. ConnectionString = dbOptions.DefaultConnection,
  32. IsAutoCloseConnection = true,
  33. ConfigId = dbOptions.DefaultConfigId,
  34. ConfigureExternalServices = configureExternalServices
  35. };
  36. connectionConfigs.Add(defaultConnection);
  37. dbOptions.DbConfigs.ForEach(config =>
  38. {
  39. var connection = new ConnectionConfig()
  40. {
  41. DbType = (DbType)Convert.ToInt32(Enum.Parse(typeof(DbType), config.DbType)),
  42. ConnectionString = config.DbConnection,
  43. IsAutoCloseConnection = true,
  44. ConfigId = config.DbConfigId,
  45. ConfigureExternalServices = configureExternalServices
  46. };
  47. connectionConfigs.Add(connection);
  48. });
  49. SqlSugarScope sqlSugar = new(connectionConfigs, db =>
  50. {
  51. connectionConfigs.ForEach(config =>
  52. {
  53. var dbProvider = db.GetConnection((string)config.ConfigId);
  54. // 设置超时时间
  55. dbProvider.Ado.CommandTimeOut = 30;
  56. // 打印SQL语句
  57. dbProvider.Aop.OnLogExecuting = (sql, pars) =>
  58. {
  59. if (sql.StartsWith("SELECT"))
  60. Console.ForegroundColor = ConsoleColor.Green;
  61. if (sql.StartsWith("UPDATE") || sql.StartsWith("INSERT"))
  62. Console.ForegroundColor = ConsoleColor.White;
  63. if (sql.StartsWith("DELETE"))
  64. Console.ForegroundColor = ConsoleColor.Blue;
  65. Console.WriteLine("\r\n" + "=========执行SQL============" + "\r\n" + UtilMethods.GetSqlString(DbType.MySql, sql, pars) + "\r\n");
  66. //Console.WriteLine(sql + "\r\n" + db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)) + "\r\n" + "========================" + "\r\n");
  67. App.PrintToMiniProfiler("SqlSugar", "Info", sql + "\r\n" + db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
  68. };
  69. dbProvider.Aop.OnError = (ex) =>
  70. {
  71. Console.ForegroundColor = ConsoleColor.Red;
  72. var pars = db.Utilities.SerializeObject(((SugarParameter[])ex.Parametres).ToDictionary(it => it.ParameterName, it => it.Value));
  73. Console.WriteLine("\r\n" + "=========SQL错误============" + "\r\n" + UtilMethods.GetSqlString(DbType.MySql, ex.Sql, (SugarParameter[])ex.Parametres) + "\r\n");
  74. //Console.WriteLine($"{ex.Message}{Environment.NewLine}{ex.Sql}{Environment.NewLine}{pars}{Environment.NewLine}");
  75. App.PrintToMiniProfiler("SqlSugar", "Error", $"{ex.Message}{Environment.NewLine}{ex.Sql}{pars}{Environment.NewLine}");
  76. };
  77. // 数据审计
  78. dbProvider.Aop.DataExecuting = (oldValue, entityInfo) =>
  79. {
  80. // 新增操作
  81. if (entityInfo.OperationType == DataFilterType.InsertByObject)
  82. {
  83. // 主键(long)-赋值雪花Id
  84. if (entityInfo.EntityColumnInfo.IsPrimarykey && entityInfo.EntityColumnInfo.PropertyInfo.PropertyType == typeof(long))
  85. entityInfo.SetValue(Yitter.IdGenerator.YitIdHelper.NextId());
  86. if (entityInfo.PropertyName == "CreateTime")
  87. entityInfo.SetValue(DateTime.Now);
  88. if (App.User != null)
  89. {
  90. if (entityInfo.PropertyName == "TenantId")
  91. {
  92. var tenantId = ((dynamic)entityInfo.EntityValue).TenantId;
  93. if (tenantId == null || tenantId == 0)
  94. entityInfo.SetValue(App.User.FindFirst(ClaimConst.TenantId)?.Value);
  95. }
  96. if (entityInfo.PropertyName == "CreateUserId")
  97. entityInfo.SetValue(App.User.FindFirst(ClaimConst.UserId)?.Value);
  98. if (entityInfo.PropertyName == "CreateOrgId")
  99. entityInfo.SetValue(App.User.FindFirst(ClaimConst.OrgId)?.Value);
  100. }
  101. }
  102. // 更新操作
  103. if (entityInfo.OperationType == DataFilterType.UpdateByObject)
  104. {
  105. if (entityInfo.PropertyName == "UpdateTime")
  106. entityInfo.SetValue(DateTime.Now);
  107. if (entityInfo.PropertyName == "UpdateUserId")
  108. entityInfo.SetValue(App.User?.FindFirst(ClaimConst.UserId)?.Value);
  109. }
  110. };
  111. dbProvider.Aop.OnDiffLogEvent = async it =>
  112. {
  113. if (dbOptions.DisableDiffLog) return;
  114. var logProvider = db.GetConnectionScope(SqlSugarConst.ConfigId);
  115. var log = new SysLogDiff
  116. {
  117. //操作后记录 包含: 字段描述 列名 值 表名 表描述
  118. AfterData = Newtonsoft.Json.JsonConvert.SerializeObject(it.AfterData),
  119. //操作前记录 包含: 字段描述 列名 值 表名 表描述
  120. BeforeData = Newtonsoft.Json.JsonConvert.SerializeObject(it.BeforeData),
  121. //传进来的对象
  122. BusinessData = Newtonsoft.Json.JsonConvert.SerializeObject(it.BusinessData),
  123. //enum insert 、update and delete
  124. DiffType = it.DiffType.ToString(),
  125. Sql = UtilMethods.GetSqlString(DbType.MySql, it.Sql, it.Parameters),
  126. Parameters = Newtonsoft.Json.JsonConvert.SerializeObject(it.Parameters),
  127. Duration = it.Time == null ? 0 : (long)it.Time.Value.TotalMilliseconds
  128. };
  129. await logProvider.Insertable(log).ExecuteCommandAsync();
  130. Console.ForegroundColor = ConsoleColor.Red;
  131. Console.WriteLine($"***差异日志开始***{Environment.NewLine}{Newtonsoft.Json.JsonConvert.SerializeObject(log)}{Environment.NewLine}***差异日志结束***");
  132. };
  133. // 配置实体假删除过滤器
  134. SetDeletedEntityFilter(dbProvider);
  135. // 配置实体机构过滤器
  136. SetOrgEntityFilter(dbProvider);
  137. // 配置自定义实体过滤器
  138. SetCustomEntityFilter(dbProvider);
  139. // 配置租户实体过滤器
  140. SetTenantEntityFilter(dbProvider);
  141. });
  142. });
  143. // 初始化数据库结构及种子数据
  144. if (dbOptions.InitTable)
  145. InitDataBase(sqlSugar, dbOptions);
  146. return sqlSugar;
  147. });
  148. services.AddScoped(typeof(SqlSugarRepository<>)); // 注册仓储
  149. }
  150. /// <summary>
  151. /// 初始化数据库结构
  152. /// </summary>
  153. public static void InitDataBase(SqlSugarScope db, ConnectionStringsOptions dbOptions)
  154. {
  155. // 创建系统默认数据库
  156. db.DbMaintenance.CreateDatabase();
  157. // 创建其他业务数据库
  158. dbOptions.DbConfigs.ForEach(config =>
  159. {
  160. db.GetConnection(config.DbConfigId).DbMaintenance.CreateDatabase();
  161. });
  162. // 获取所有实体表
  163. var entityTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
  164. && u.IsDefined(typeof(SqlSugarEntityAttribute), false))
  165. .OrderByDescending(u => u.GetSqlSugarEntityOrder());
  166. if (!entityTypes.Any()) return;
  167. // 初始化库表结构
  168. foreach (var entityType in entityTypes)
  169. {
  170. var dbConfigId = entityType.GetCustomAttribute<SqlSugarEntityAttribute>(true).DbConfigId;
  171. db.ChangeDatabase(dbConfigId);
  172. db.CodeFirst.InitTables(entityType);
  173. }
  174. // 获取所有实体种子数据
  175. var seedDataTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
  176. && u.GetInterfaces().Any(i => i.HasImplementedRawGeneric(typeof(ISqlSugarEntitySeedData<>))));
  177. if (!seedDataTypes.Any()) return;
  178. foreach (var seedType in seedDataTypes)
  179. {
  180. var instance = Activator.CreateInstance(seedType);
  181. var hasDataMethod = seedType.GetMethod("HasData");
  182. var seedData = ((IList)hasDataMethod?.Invoke(instance, null))?.Cast<object>();
  183. if (seedData == null) continue;
  184. var entityType = seedType.GetInterfaces().First().GetGenericArguments().First();
  185. var dbConfigId = entityType.GetCustomAttribute<SqlSugarEntityAttribute>(true).DbConfigId;
  186. db.ChangeDatabase(dbConfigId);
  187. var seedDataTable = seedData.ToList().ToDataTable();
  188. if (seedDataTable.Columns.Contains(SqlSugarConst.PrimaryKey))
  189. {
  190. var storage = db.Storageable(seedDataTable).WhereColumns(SqlSugarConst.PrimaryKey).ToStorage();
  191. storage.AsInsertable.ExecuteCommand();
  192. storage.AsUpdateable.ExecuteCommand();
  193. }
  194. else //没有主键或者不是预定义的主键(没主键有重复的可能)
  195. {
  196. var storage = db.Storageable(seedDataTable).ToStorage();
  197. storage.AsInsertable.ExecuteCommand();
  198. }
  199. }
  200. }
  201. /// <summary>
  202. /// 配置实体假删除过滤器
  203. /// </summary>
  204. public static void SetDeletedEntityFilter(SqlSugarProvider db)
  205. {
  206. // 获取所有继承基类数据表集合
  207. var entityTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
  208. && u.BaseType == typeof(EntityBase));
  209. if (!entityTypes.Any()) return;
  210. foreach (var entityType in entityTypes)
  211. {
  212. Expression<Func<DataEntityBase, bool>> dynamicExpression = u => u.IsDelete == false;
  213. db.QueryFilter.Add(new TableFilterItem<object>(entityType, dynamicExpression));
  214. }
  215. }
  216. /// <summary>
  217. /// 配置实体机构过滤器
  218. /// </summary>
  219. public static async void SetOrgEntityFilter(SqlSugarProvider db)
  220. {
  221. // 获取业务数据表集合
  222. var dataEntityTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
  223. && u.BaseType == typeof(DataEntityBase));
  224. if (!dataEntityTypes.Any()) return;
  225. var userId = App.User?.FindFirst(ClaimConst.UserId)?.Value;
  226. if (string.IsNullOrWhiteSpace(userId)) return;
  227. // 获取用户机构Id集合
  228. var orgIds = await App.GetService<SysCacheService>().GetOrgIdList(long.Parse(userId));
  229. if (orgIds == null) return;
  230. foreach (var dataEntityType in dataEntityTypes)
  231. {
  232. Expression<Func<DataEntityBase, bool>> dynamicExpression = u => orgIds.Contains((long)u.CreateOrgId);
  233. db.QueryFilter.Add(new TableFilterItem<object>(dataEntityType, dynamicExpression));
  234. }
  235. }
  236. /// <summary>
  237. /// 配置自定义实体过滤器
  238. /// </summary>
  239. public static void SetCustomEntityFilter(SqlSugarProvider db)
  240. {
  241. // 获取继承自定义实体过滤器接口的类集合
  242. var entityFilterTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
  243. && u.GetInterfaces().Any(i => i.HasImplementedRawGeneric(typeof(IEntityFilter))));
  244. if (!entityFilterTypes.Any()) return;
  245. foreach (var entityFilter in entityFilterTypes)
  246. {
  247. var instance = Activator.CreateInstance(entityFilter);
  248. var entityFilterMethod = entityFilter.GetMethod("AddEntityFilter");
  249. var entityFilters = ((IList)entityFilterMethod?.Invoke(instance, null))?.Cast<object>();
  250. if (entityFilters == null) continue;
  251. foreach (TableFilterItem<object> filter in entityFilters)
  252. db.QueryFilter.Add(filter);
  253. }
  254. }
  255. /// <summary>
  256. /// 配置租户实体过滤器
  257. /// </summary>
  258. public static void SetTenantEntityFilter(SqlSugarProvider db)
  259. {
  260. // 获取租户实体数据表集合
  261. var dataEntityTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass
  262. && u.BaseType == typeof(EntityTenant));
  263. if (!dataEntityTypes.Any()) return;
  264. var tenantId = App.User?.FindFirst(ClaimConst.TenantId)?.Value;
  265. if (string.IsNullOrWhiteSpace(tenantId)) return;
  266. foreach (var dataEntityType in dataEntityTypes)
  267. {
  268. Expression<Func<EntityTenant, bool>> dynamicExpression = u => u.TenantId == long.Parse(tenantId);
  269. db.QueryFilter.Add(new TableFilterItem<object>(dataEntityType, dynamicExpression));
  270. }
  271. }
  272. /// <summary>
  273. /// 处理本地库根目录路径
  274. /// </summary>
  275. /// <param name="dbOptions"></param>
  276. private static void DealConnectionStr(ref ConnectionStringsOptions dbOptions)
  277. {
  278. if (dbOptions.DefaultDbType.Trim().ToLower() == "sqlite" && dbOptions.DefaultConnection.Contains("./"))
  279. {
  280. dbOptions.DefaultConnection = UpdateDbPath(dbOptions.DefaultConnection);
  281. }
  282. dbOptions.DbConfigs.ForEach(cofing =>
  283. {
  284. if (cofing.DbType.Trim().ToLower() == "sqlite" && cofing.DbConnection.Contains("./"))
  285. cofing.DbConnection = UpdateDbPath(cofing.DbConnection);
  286. });
  287. }
  288. private static string UpdateDbPath(string dbConnection)
  289. {
  290. var file = Path.GetFileName(dbConnection.Replace("DataSource=", ""));
  291. return $"DataSource={Environment.CurrentDirectory.Replace(@"\bin\Debug", "")}/{file}";
  292. }
  293. }