SqlSugarSetup.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733
  1. // Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
  2. //
  3. // 本项目主要遵循 MIT 许可证和 Apache 许可证(版本 2.0)进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
  4. //
  5. // 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动!任何基于本项目二次开发而产生的一切法律纠纷和责任,我们不承担任何责任!
  6. using Microsoft.Data.Sqlite;
  7. using DbType = SqlSugar.DbType;
  8. namespace Admin.NET.Core;
  9. public static class SqlSugarSetup
  10. {
  11. // 多租户实例
  12. public static ITenant ITenant { get; set; }
  13. // 是否正在处理种子数据
  14. private static bool _isHandlingSeedData = false;
  15. /// <summary>
  16. /// SqlSugar 上下文初始化
  17. /// </summary>
  18. /// <param name="services"></param>
  19. public static void AddSqlSugar(this IServiceCollection services)
  20. {
  21. // 注册雪花Id
  22. var snowIdOpt = App.GetConfig<SnowIdOptions>("SnowId", true);
  23. YitIdHelper.SetIdGenerator(snowIdOpt);
  24. // 自定义 SqlSugar 雪花ID算法
  25. SnowFlakeSingle.WorkId = snowIdOpt.WorkerId;
  26. StaticConfig.CustomSnowFlakeFunc = YitIdHelper.NextId;
  27. // 注册 MongoDb
  28. InstanceFactory.CustomAssemblies = [typeof(SqlSugar.MongoDb.MongoDbProvider).Assembly];
  29. // 动态表达式 SqlFunc 支持,https://www.donet5.com/Home/Doc?typeId=2569
  30. StaticConfig.DynamicExpressionParserType = typeof(DynamicExpressionParser);
  31. StaticConfig.DynamicExpressionParsingConfig = new ParsingConfig
  32. {
  33. CustomTypeProvider = new SqlSugarTypeProvider()
  34. };
  35. var dbOptions = App.GetConfig<DbConnectionOptions>("DbConnection", true);
  36. dbOptions.ConnectionConfigs.ForEach(SetDbConfig);
  37. SqlSugarScope sqlSugar = new(dbOptions.ConnectionConfigs.Adapt<List<ConnectionConfig>>(), db =>
  38. {
  39. dbOptions.ConnectionConfigs.ForEach(config =>
  40. {
  41. var dbProvider = db.GetConnectionScope(config.ConfigId);
  42. SetDbAop(dbProvider, dbOptions.EnableConsoleSql, dbOptions.SuperAdminIgnoreIDeletedFilter);
  43. SetDbDiffLog(dbProvider, config);
  44. });
  45. });
  46. ITenant = sqlSugar;
  47. services.AddSingleton<ISqlSugarClient>(sqlSugar); // 单例注册
  48. services.AddScoped(typeof(SqlSugarRepository<>)); // 仓储注册
  49. services.AddUnitOfWork<SqlSugarUnitOfWork>(); // 事务与工作单元注册
  50. // 初始化数据库表结构及种子数据
  51. dbOptions.ConnectionConfigs.ForEach(config =>
  52. {
  53. InitDatabase(sqlSugar, config);
  54. });
  55. }
  56. /// <summary>
  57. /// 配置连接属性
  58. /// </summary>
  59. /// <param name="config"></param>
  60. public static void SetDbConfig(DbConnectionConfig config)
  61. {
  62. if (config.DbSettings.EnableConnStringEncrypt)
  63. config.ConnectionString = CryptogramUtil.Decrypt(config.ConnectionString);
  64. var configureExternalServices = new ConfigureExternalServices
  65. {
  66. EntityNameService = (type, entity) => // 处理表
  67. {
  68. entity.IsDisabledDelete = true; // 禁止删除非 sqlsugar 创建的列
  69. // 只处理贴了特性[SugarTable]表
  70. if (!type.GetCustomAttributes<SugarTable>().Any())
  71. return;
  72. if (config.DbSettings.EnableUnderLine && !entity.DbTableName.Contains('_'))
  73. entity.DbTableName = entity.DbTableName.ToUnderLine(); // 驼峰转下划线
  74. },
  75. EntityService = (type, column) => // 处理列
  76. {
  77. // 只处理贴了特性[SugarColumn]列
  78. if (!type.GetCustomAttributes<SugarColumn>().Any())
  79. return;
  80. if (new NullabilityInfoContext().Create(type).WriteState is NullabilityState.Nullable)
  81. column.IsNullable = true;
  82. if (config.DbSettings.EnableUnderLine && !column.IsIgnore && !column.DbColumnName.Contains('_'))
  83. column.DbColumnName = column.DbColumnName.ToUnderLine(); // 驼峰转下划线
  84. },
  85. DataInfoCacheService = new SqlSugarCache(),
  86. };
  87. config.ConfigureExternalServices = configureExternalServices;
  88. config.InitKeyType = InitKeyType.Attribute;
  89. config.IsAutoCloseConnection = true;
  90. config.MoreSettings = new ConnMoreSettings
  91. {
  92. IsAutoRemoveDataCache = true, // 启用自动删除缓存,所有增删改会自动调用.RemoveDataCache()
  93. IsAutoDeleteQueryFilter = true, // 启用删除查询过滤器
  94. IsAutoUpdateQueryFilter = true, // 启用更新查询过滤器
  95. SqlServerCodeFirstNvarchar = true // 采用Nvarchar
  96. };
  97. // 若库类型是人大金仓则默认设置PG模式
  98. if (config.DbType == DbType.Kdbndp)
  99. config.MoreSettings.DatabaseModel = DbType.PostgreSQL; // 配置PG模式主要是兼容系统表差异
  100. // 若库类型是Oracle则默认主键名字和参数名字最大长度
  101. if (config.DbType == DbType.Oracle)
  102. config.MoreSettings.MaxParameterNameLength = 30;
  103. }
  104. /// <summary>
  105. /// 配置Aop
  106. /// </summary>
  107. /// <param name="db"></param>
  108. /// <param name="enableConsoleSql"></param>
  109. /// <param name="superAdminIgnoreIDeletedFilter"></param>
  110. public static void SetDbAop(SqlSugarScopeProvider db, bool enableConsoleSql, bool superAdminIgnoreIDeletedFilter)
  111. {
  112. // 设置超时时间
  113. db.Ado.CommandTimeOut = 30;
  114. // 打印SQL语句
  115. if (enableConsoleSql)
  116. {
  117. db.Aop.OnLogExecuting = (sql, pars) =>
  118. {
  119. //// 若参数值超过100个字符则进行截取
  120. //foreach (var par in pars)
  121. //{
  122. // if (par.DbType != System.Data.DbType.String || par.Value == null) continue;
  123. // if (par.Value.ToString().Length > 100)
  124. // par.Value = string.Concat(par.Value.ToString()[..100], "......");
  125. //}
  126. var log = $"【{DateTime.Now}——执行SQL】\r\n{UtilMethods.GetNativeSql(sql, pars)}\r\n";
  127. var originColor = Console.ForegroundColor;
  128. if (sql.StartsWith("SELECT", StringComparison.OrdinalIgnoreCase))
  129. Console.ForegroundColor = ConsoleColor.Green;
  130. if (sql.StartsWith("UPDATE", StringComparison.OrdinalIgnoreCase) || sql.StartsWith("INSERT", StringComparison.OrdinalIgnoreCase))
  131. Console.ForegroundColor = ConsoleColor.Yellow;
  132. if (sql.StartsWith("DELETE", StringComparison.OrdinalIgnoreCase))
  133. Console.ForegroundColor = ConsoleColor.Red;
  134. Console.WriteLine(log);
  135. Console.ForegroundColor = originColor;
  136. };
  137. }
  138. db.Aop.OnError = ex =>
  139. {
  140. if (ex.Parametres == null) return;
  141. var log = $"【{DateTime.Now}——错误SQL】\r\n{UtilMethods.GetNativeSql(ex.Sql, (SugarParameter[])ex.Parametres)}\r\n";
  142. Log.Error(log, ex);
  143. };
  144. db.Aop.OnLogExecuted = (sql, pars) =>
  145. {
  146. //// 若参数值超过100个字符则进行截取
  147. //foreach (var par in pars)
  148. //{
  149. // if (par.DbType != System.Data.DbType.String || par.Value == null) continue;
  150. // if (par.Value.ToString().Length > 100)
  151. // par.Value = string.Concat(par.Value.ToString()[..100], "......");
  152. //}
  153. // 执行时间超过5秒时
  154. if (!(db.Ado.SqlExecutionTime.TotalSeconds > 5)) return;
  155. var fileName = db.Ado.SqlStackTrace.FirstFileName; // 文件名
  156. var fileLine = db.Ado.SqlStackTrace.FirstLine; // 行号
  157. var firstMethodName = db.Ado.SqlStackTrace.FirstMethodName; // 方法名
  158. var log = $"【{DateTime.Now}——超时SQL】\r\n【所在文件名】:{fileName}\r\n【代码行数】:{fileLine}\r\n【方法名】:{firstMethodName}\r\n" + $"【SQL语句】:{UtilMethods.GetNativeSql(sql, pars)}";
  159. Log.Warning(log);
  160. };
  161. // 数据审计
  162. db.Aop.DataExecuting = (_, entityInfo) =>
  163. {
  164. // 若正在处理种子数据则直接返回
  165. if (_isHandlingSeedData) return;
  166. // 新增/插入
  167. if (entityInfo.OperationType == DataFilterType.InsertByObject)
  168. {
  169. // 若主键是长整型且空则赋值雪花Id
  170. if (entityInfo.EntityColumnInfo.IsPrimarykey && !entityInfo.EntityColumnInfo.IsIdentity && entityInfo.EntityColumnInfo.PropertyInfo.PropertyType == typeof(long))
  171. {
  172. var id = entityInfo.EntityColumnInfo.PropertyInfo.GetValue(entityInfo.EntityValue);
  173. if (id == null || (long)id == 0)
  174. entityInfo.SetValue(YitIdHelper.NextId());
  175. }
  176. // 若创建时间为空则赋值当前时间
  177. else if (entityInfo.PropertyName == nameof(EntityBase.CreateTime))
  178. {
  179. var createTime = entityInfo.EntityColumnInfo.PropertyInfo.GetValue(entityInfo.EntityValue)!;
  180. if (createTime == null || createTime.Equals(DateTime.MinValue))
  181. entityInfo.SetValue(DateTime.Now);
  182. }
  183. // 若当前用户为空(非web线程时)
  184. if (App.User == null) return;
  185. dynamic entityValue = entityInfo.EntityValue;
  186. if (entityInfo.PropertyName == nameof(EntityBaseTenantId.TenantId))
  187. {
  188. var tenantId = entityValue.TenantId;
  189. if (tenantId == null || tenantId == 0)
  190. entityInfo.SetValue(App.User.FindFirst(ClaimConst.TenantId)?.Value);
  191. }
  192. else if (entityInfo.PropertyName == nameof(EntityBase.CreateUserId))
  193. {
  194. var createUserId = entityValue.CreateUserId;
  195. if (createUserId == 0 || createUserId == null)
  196. entityInfo.SetValue(App.User.FindFirst(ClaimConst.UserId)?.Value);
  197. }
  198. else if (entityInfo.PropertyName == nameof(EntityBase.CreateUserName))
  199. {
  200. var createUserName = entityValue.CreateUserName;
  201. if (string.IsNullOrEmpty(createUserName))
  202. entityInfo.SetValue(App.User.FindFirst(ClaimConst.RealName)?.Value);
  203. }
  204. else if (entityInfo.PropertyName == "CreateOrgId")
  205. {
  206. var createOrgId = entityValue.CreateOrgId;
  207. if (createOrgId == 0 || createOrgId == null)
  208. entityInfo.SetValue(App.User.FindFirst(ClaimConst.OrgId)?.Value);
  209. }
  210. else if (entityInfo.PropertyName == "CreateOrgName")
  211. {
  212. var createOrgName = entityValue.CreateOrgName;
  213. if (string.IsNullOrEmpty(createOrgName))
  214. entityInfo.SetValue(App.User.FindFirst(ClaimConst.OrgName)?.Value);
  215. }
  216. }
  217. // 编辑/更新
  218. else if (entityInfo.OperationType == DataFilterType.UpdateByObject)
  219. {
  220. if (entityInfo.PropertyName == nameof(EntityBase.UpdateTime))
  221. entityInfo.SetValue(DateTime.Now);
  222. else if (entityInfo.PropertyName == nameof(EntityBaseDel.DeleteTime))
  223. {
  224. dynamic entityValue = entityInfo.EntityValue;
  225. var isDelete = entityValue.IsDelete;
  226. if (isDelete == true)
  227. {
  228. entityInfo.SetValue(DateTime.Now);
  229. }
  230. }
  231. // 若当前用户为空(非web线程时)
  232. if (App.User == null) return;
  233. if (entityInfo.PropertyName == nameof(EntityBase.UpdateUserId))
  234. entityInfo.SetValue(App.User?.FindFirst(ClaimConst.UserId)?.Value);
  235. else if (entityInfo.PropertyName == nameof(EntityBase.UpdateUserName))
  236. entityInfo.SetValue(App.User?.FindFirst(ClaimConst.RealName)?.Value);
  237. }
  238. };
  239. // 是否为超级管理员
  240. var isSuperAdmin = App.User?.FindFirst(ClaimConst.AccountType)?.Value == ((int)AccountTypeEnum.SuperAdmin).ToString();
  241. // 配置假删除过滤器,如果当前用户是超级管理员并且允许忽略软删除过滤器则不会应用
  242. if (!isSuperAdmin || !superAdminIgnoreIDeletedFilter)
  243. db.QueryFilter.AddTableFilter<IDeletedFilter>(u => u.IsDelete == false);
  244. // 超管排除其他过滤器
  245. if (isSuperAdmin) return;
  246. // 配置租户过滤器
  247. var tenantId = App.User?.FindFirst(ClaimConst.TenantId)?.Value;
  248. if (!string.IsNullOrWhiteSpace(tenantId))
  249. db.QueryFilter.AddTableFilter<ITenantIdFilter>(u => u.TenantId == long.Parse(tenantId));
  250. // 配置用户机构(数据范围)过滤器
  251. SqlSugarFilter.SetOrgEntityFilter(db);
  252. // 配置自定义过滤器
  253. SqlSugarFilter.SetCustomEntityFilter(db);
  254. }
  255. /// <summary>
  256. /// 开启库表差异化日志
  257. /// </summary>
  258. /// <param name="db"></param>
  259. /// <param name="config"></param>
  260. private static void SetDbDiffLog(SqlSugarScopeProvider db, DbConnectionConfig config)
  261. {
  262. if (!config.DbSettings.EnableDiffLog) return;
  263. async void AopOnDiffLogEvent(DiffLogModel u)
  264. {
  265. // 记录差异数据
  266. var diffData = new List<dynamic>();
  267. for (int i = 0; i < u.AfterData.Count; i++)
  268. {
  269. var diffColumns = new List<dynamic>();
  270. var afterColumns = u.AfterData[i].Columns;
  271. var beforeColumns = u.BeforeData[i].Columns;
  272. for (int j = 0; j < afterColumns.Count; j++)
  273. {
  274. if (afterColumns[j].Value.Equals(beforeColumns[j].Value)) continue;
  275. diffColumns.Add(new
  276. {
  277. afterColumns[j].IsPrimaryKey,
  278. afterColumns[j].ColumnName,
  279. afterColumns[j].ColumnDescription,
  280. BeforeValue = beforeColumns[j].Value,
  281. AfterValue = afterColumns[j].Value,
  282. });
  283. }
  284. diffData.Add(new { u.AfterData[i].TableName, u.AfterData[i].TableDescription, Columns = diffColumns });
  285. }
  286. var logDiff = new SysLogDiff
  287. {
  288. // 差异数据(字段描述、列名、值、表名、表描述)
  289. DiffData = JSON.Serialize(diffData),
  290. // 传进来的对象(如果对象为空,则使用首个数据的表名作为业务对象)
  291. BusinessData = u.BusinessData == null ? u.AfterData.FirstOrDefault()?.TableName : JSON.Serialize(u.BusinessData),
  292. // 枚举(insert、update、delete)
  293. DiffType = u.DiffType.ToString(),
  294. Sql = u.Sql,
  295. Parameters = JSON.Serialize(u.Parameters.Select(e => new { e.ParameterName, e.Value, TypeName = e.DbType.ToString() })),
  296. Elapsed = u.Time == null ? 0 : (long)u.Time.Value.TotalMilliseconds
  297. };
  298. var logDb = ITenant.IsAnyConnection(SqlSugarConst.LogConfigId) ? ITenant.GetConnectionScope(SqlSugarConst.LogConfigId) : ITenant.GetConnectionScope(SqlSugarConst.MainConfigId);
  299. await logDb.CopyNew().Insertable(logDiff).ExecuteCommandAsync();
  300. Console.ForegroundColor = ConsoleColor.Red;
  301. Console.WriteLine(DateTime.Now + $"\r\n*****开始差异日志*****\r\n{Environment.NewLine}{JSON.Serialize(logDiff)}{Environment.NewLine}*****结束差异日志*****\r\n");
  302. }
  303. db.Aop.OnDiffLogEvent = AopOnDiffLogEvent;
  304. }
  305. /// <summary>
  306. /// 初始化视图
  307. /// </summary>
  308. /// <param name="dbProvider"></param>
  309. private static void InitView(SqlSugarScopeProvider dbProvider)
  310. {
  311. var totalWatch = Stopwatch.StartNew(); // 开始总计时
  312. Log.Information($"初始化视图 {dbProvider.CurrentConnectionConfig.DbType} - {dbProvider.CurrentConnectionConfig.ConfigId}");
  313. var viewTypeList = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass && u.GetInterfaces().Any(i => i.HasImplementedRawGeneric(typeof(ISqlSugarView)))).ToList();
  314. int taskIndex = 0, size = viewTypeList.Count;
  315. var taskList = viewTypeList.Select(viewType => Task.Run(() =>
  316. {
  317. // 开始计时
  318. var stopWatch = Stopwatch.StartNew();
  319. // 获取视图实体和配置信息
  320. var entityInfo = dbProvider.EntityMaintenance.GetEntityInfo(viewType) ?? throw new Exception("获取视图实体配置有误");
  321. // 如果视图存在,则删除视图
  322. if (dbProvider.DbMaintenance.GetViewInfoList(false).Any(it => it.Name.EqualIgnoreCase(entityInfo.DbTableName)))
  323. dbProvider.DbMaintenance.DropView(entityInfo.DbTableName);
  324. // 获取初始化视图查询SQL
  325. var sql = viewType.GetMethod(nameof(ISqlSugarView.GetQueryableSqlString))?.Invoke(Activator.CreateInstance(viewType), [dbProvider]) as string;
  326. if (string.IsNullOrWhiteSpace(sql)) throw new Exception("视图初始化Sql语句不能为空");
  327. // 创建视图
  328. dbProvider.Ado.ExecuteCommand($"CREATE VIEW {entityInfo.DbTableName} AS " + Environment.NewLine + " " + sql);
  329. // 停止计时
  330. stopWatch.Stop();
  331. Console.ForegroundColor = ConsoleColor.Green;
  332. Console.WriteLine($"初始化视图 {viewType.FullName,-58} ({dbProvider.CurrentConnectionConfig.ConfigId} - {Interlocked.Increment(ref taskIndex):D003}/{size:D003},耗时:{stopWatch.ElapsedMilliseconds:N0} ms)");
  333. }));
  334. Task.WaitAll(taskList.ToArray());
  335. totalWatch.Stop(); // 停止总计时
  336. Console.ForegroundColor = ConsoleColor.Green;
  337. Console.WriteLine($"初始化视图 {dbProvider.CurrentConnectionConfig.DbType} - {dbProvider.CurrentConnectionConfig.ConfigId} 总耗时:{totalWatch.ElapsedMilliseconds:N0} ms");
  338. }
  339. /// <summary>
  340. /// 等待数据库就绪
  341. /// </summary>
  342. /// <param name="dbProvider"></param>
  343. private static void WaitForDatabaseReady(SqlSugarScopeProvider dbProvider)
  344. {
  345. do
  346. {
  347. try
  348. {
  349. if (dbProvider.Ado.Connection.State != ConnectionState.Open)
  350. dbProvider.Ado.Connection.Open();
  351. // 如果连接成功,直接返回
  352. Log.Information("数据库连接成功。");
  353. return;
  354. }
  355. catch (Exception ex)
  356. {
  357. Log.Warning($"数据库尚未就绪,等待中... 错误:{ex.Message}");
  358. Thread.Sleep(1000);
  359. }
  360. } while (true);
  361. }
  362. /// <summary>
  363. /// 初始化数据库
  364. /// </summary>
  365. /// <param name="db">SqlSugarScope 实例</param>
  366. /// <param name="config">数据库连接配置</param>
  367. private static void InitDatabase(SqlSugarScope db, DbConnectionConfig config)
  368. {
  369. var dbProvider = db.GetConnectionScope(config.ConfigId);
  370. // 初始化数据库 如果是没有数据库的话,是先初始化数据库再做连接
  371. if (config.DbSettings.EnableInitDb)
  372. {
  373. Log.Information($"初始化数据库 {config.DbType} - {config.ConfigId} - {config.ConnectionString}");
  374. if (config.DbType != DbType.Oracle) dbProvider.DbMaintenance.CreateDatabase();
  375. }
  376. // 等待数据库连接就绪
  377. WaitForDatabaseReady(dbProvider);
  378. // 初始化表结构
  379. if (config.TableSettings.EnableInitTable)
  380. {
  381. Log.Information($"初始化表结构 {config.DbType} - {config.ConfigId}");
  382. var entityTypes = GetEntityTypesForInit(config);
  383. InitializeTables(dbProvider, entityTypes, config);
  384. }
  385. // 初始化视图
  386. if (config.DbSettings.EnableInitView) InitView(dbProvider);
  387. // 初始化种子数据
  388. if (config.SeedSettings.EnableInitSeed) InitSeedData(db, config);
  389. }
  390. /// <summary>
  391. /// 获取需要初始化的实体类型
  392. /// </summary>
  393. /// <param name="config">数据库连接配置</param>
  394. /// <returns>实体类型列表</returns>
  395. private static List<Type> GetEntityTypesForInit(DbConnectionConfig config)
  396. {
  397. return App.EffectiveTypes
  398. .Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass && u.IsDefined(typeof(SugarTable), false))
  399. .Where(u => !u.GetCustomAttributes<IgnoreTableAttribute>().Any())
  400. .WhereIF(config.TableSettings.EnableIncreTable, u => u.IsDefined(typeof(IncreTableAttribute), false))
  401. .Where(u => IsEntityForConfig(u, config))
  402. .ToList();
  403. }
  404. /// <summary>
  405. /// 判断实体是否属于当前配置
  406. /// </summary>
  407. /// <param name="entityType">实体类型</param>
  408. /// <param name="config">数据库连接配置</param>
  409. /// <returns>是否属于当前配置</returns>
  410. private static bool IsEntityForConfig(Type entityType, DbConnectionConfig config)
  411. {
  412. switch (config.ConfigId.ToString())
  413. {
  414. case SqlSugarConst.MainConfigId:
  415. return entityType.GetCustomAttributes<SysTableAttribute>().Any() ||
  416. (!entityType.GetCustomAttributes<LogTableAttribute>().Any() &&
  417. !entityType.GetCustomAttributes<TenantAttribute>().Any(o => o.configId.ToString() != config.ConfigId.ToString()));
  418. case SqlSugarConst.LogConfigId:
  419. return entityType.GetCustomAttributes<LogTableAttribute>().Any();
  420. default:
  421. {
  422. var tenantAttribute = entityType.GetCustomAttribute<TenantAttribute>();
  423. return tenantAttribute != null && tenantAttribute.configId.ToString() == config.ConfigId.ToString();
  424. }
  425. }
  426. }
  427. /// <summary>
  428. /// 初始化表结构
  429. /// </summary>
  430. /// <param name="dbProvider">SqlSugarScopeProvider 实例</param>
  431. /// <param name="entityTypes">实体类型列表</param>
  432. /// <param name="config">数据库连接配置</param>
  433. private static void InitializeTables(SqlSugarScopeProvider dbProvider, List<Type> entityTypes, DbConnectionConfig config)
  434. {
  435. // 删除视图再初始化表结构,防止因为视图导致无法同步表结构
  436. var viewTypeList = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass && u.GetInterfaces().Any(i => i.HasImplementedRawGeneric(typeof(ISqlSugarView)))).ToList();
  437. foreach (var viewType in viewTypeList)
  438. {
  439. var entityInfo = dbProvider.EntityMaintenance.GetEntityInfo(viewType) ?? throw new Exception("获取视图实体配置有误");
  440. if (dbProvider.DbMaintenance.GetViewInfoList(false).Any(it => it.Name.EqualIgnoreCase(entityInfo.DbTableName)))
  441. dbProvider.DbMaintenance.DropView(entityInfo.DbTableName);
  442. }
  443. int count = 0, sum = entityTypes.Count;
  444. var tasks = entityTypes.Select(entityType => Task.Run(() =>
  445. {
  446. Console.WriteLine($"初始化表结构 {entityType.FullName,-64} ({config.ConfigId} - {Interlocked.Increment(ref count):D003}/{sum:D003})");
  447. UpdateNullableColumns(dbProvider, entityType);
  448. InitializeTable(dbProvider, entityType);
  449. }));
  450. Task.WhenAll(tasks).GetAwaiter().GetResult();
  451. }
  452. /// <summary>
  453. /// 更新表中不存在于实体的字段为可空
  454. /// </summary>
  455. /// <param name="dbProvider">SqlSugarScopeProvider 实例</param>
  456. /// <param name="entityType">实体类型</param>
  457. private static void UpdateNullableColumns(SqlSugarScopeProvider dbProvider, Type entityType)
  458. {
  459. var entityInfo = dbProvider.EntityMaintenance.GetEntityInfo(entityType);
  460. var dbColumns = dbProvider.DbMaintenance.GetColumnInfosByTableName(entityInfo.DbTableName) ?? new List<DbColumnInfo>();
  461. foreach (var dbColumn in dbColumns.Where(c => !c.IsPrimarykey && entityInfo.Columns.All(u => u.DbColumnName != c.DbColumnName)))
  462. {
  463. dbColumn.IsNullable = true;
  464. Retry(() =>
  465. {
  466. dbProvider.DbMaintenance.UpdateColumn(entityInfo.DbTableName, dbColumn);
  467. }, maxRetry: 3, retryIntervalMs: 1000);
  468. }
  469. }
  470. /// <summary>
  471. /// 初始化表
  472. /// </summary>
  473. /// <param name="dbProvider">SqlSugarScopeProvider 实例</param>
  474. /// <param name="entityType">实体类型</param>
  475. private static void InitializeTable(SqlSugarScopeProvider dbProvider, Type entityType)
  476. {
  477. Retry(() =>
  478. {
  479. if (entityType.GetCustomAttribute<SplitTableAttribute>() == null)
  480. {
  481. dbProvider.CodeFirst.InitTables(entityType);
  482. }
  483. else
  484. {
  485. dbProvider.CodeFirst.SplitTables().InitTables(entityType);
  486. }
  487. }, maxRetry: 3, retryIntervalMs: 1000);
  488. }
  489. /// <summary>
  490. /// 初始化种子数据
  491. /// </summary>
  492. /// <param name="db">SqlSugarScope 实例</param>
  493. /// <param name="config">数据库连接配置</param>
  494. private static void InitSeedData(SqlSugarScope db, DbConnectionConfig config)
  495. {
  496. var dbProvider = db.GetConnectionScope(config.ConfigId);
  497. _isHandlingSeedData = true;
  498. Log.Information($"初始化种子数据 {config.DbType} - {config.ConfigId}");
  499. var seedDataTypes = GetSeedDataTypes(config);
  500. int count = 0, sum = seedDataTypes.Count;
  501. var tasks = seedDataTypes.Select(seedType => Task.Run(() =>
  502. {
  503. var entityType = seedType.GetInterfaces().First().GetGenericArguments().First();
  504. if (!IsEntityForConfig(entityType, config)) return;
  505. var seedData = GetSeedData(seedType)?.ToList();
  506. if (seedData == null) return;
  507. AdjustSeedDataIds(seedData, config);
  508. InsertOrUpdateSeedData(dbProvider, seedType, entityType, seedData, config, ref count, sum);
  509. }));
  510. Task.WhenAll(tasks).GetAwaiter().GetResult();
  511. _isHandlingSeedData = false;
  512. }
  513. /// <summary>
  514. /// 获取种子数据类型
  515. /// </summary>
  516. /// <param name="config">数据库连接配置</param>
  517. /// <returns>种子数据类型列表</returns>
  518. private static List<Type> GetSeedDataTypes(DbConnectionConfig config)
  519. {
  520. return App.EffectiveTypes
  521. .Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass && u.GetInterfaces().Any(i => i.HasImplementedRawGeneric(typeof(ISqlSugarEntitySeedData<>))))
  522. .WhereIF(config.SeedSettings.EnableIncreSeed, u => u.IsDefined(typeof(IncreSeedAttribute), false))
  523. .OrderBy(u => u.GetCustomAttributes(typeof(SeedDataAttribute), false).Length > 0 ? ((SeedDataAttribute)u.GetCustomAttributes(typeof(SeedDataAttribute), false)[0]).Order : 0)
  524. .ToList();
  525. }
  526. /// <summary>
  527. /// 获取种子数据
  528. /// </summary>
  529. /// <param name="seedType">种子数据类型</param>
  530. /// <returns>种子数据列表</returns>
  531. private static IEnumerable<object> GetSeedData(Type seedType)
  532. {
  533. var instance = Activator.CreateInstance(seedType);
  534. var hasDataMethod = seedType.GetMethod("HasData");
  535. return ((IEnumerable)hasDataMethod?.Invoke(instance, null))?.Cast<object>();
  536. }
  537. /// <summary>
  538. /// 调整种子数据的 ID
  539. /// </summary>
  540. /// <param name="seedData">种子数据列表</param>
  541. /// <param name="config">数据库连接配置</param>
  542. private static void AdjustSeedDataIds(IEnumerable<object> seedData, DbConnectionConfig config)
  543. {
  544. var seedId = config.ConfigId.ToLong();
  545. foreach (var data in seedData)
  546. {
  547. var idProperty = data.GetType().GetProperty(nameof(EntityBaseId.Id));
  548. if (idProperty == null || idProperty.PropertyType != typeof(Int64)) continue;
  549. var idValue = idProperty.GetValue(data);
  550. if (idValue == null || idValue.ToString() == "0" || string.IsNullOrWhiteSpace(idValue.ToString()))
  551. {
  552. idProperty.SetValue(data, ++seedId);
  553. }
  554. }
  555. }
  556. /// <summary>
  557. /// 插入或更新种子数据
  558. /// </summary>
  559. /// <param name="dbProvider">SqlSugarScopeProvider 实例</param>
  560. /// <param name="seedType">种子数据类型</param>
  561. /// <param name="entityType">实体类型</param>
  562. /// <param name="seedData">种子数据列表</param>
  563. /// <param name="config">数据库连接配置</param>
  564. /// <param name="count">当前处理的数量</param>
  565. /// <param name="sum">总数量</param>
  566. private static void InsertOrUpdateSeedData(SqlSugarScopeProvider dbProvider, Type seedType, Type entityType, IEnumerable<object> seedData, DbConnectionConfig config, ref int count, int sum)
  567. {
  568. var entityInfo = dbProvider.EntityMaintenance.GetEntityInfo(entityType);
  569. var dataList = seedData.ToList();
  570. if (entityType.GetCustomAttribute<SplitTableAttribute>(true) != null)
  571. {
  572. var initMethod = seedType.GetMethod("Init");
  573. initMethod?.Invoke(Activator.CreateInstance(seedType), new object[] { dbProvider });
  574. }
  575. else
  576. {
  577. int updateCount = 0, insertCount = 0;
  578. if (entityInfo.Columns.Any(u => u.IsPrimarykey))
  579. {
  580. var storage = dbProvider.StorageableByObject(dataList).ToStorage();
  581. if (seedType.GetCustomAttribute<IgnoreUpdateSeedAttribute>() == null)
  582. {
  583. updateCount = storage.AsUpdateable
  584. .IgnoreColumns(entityInfo.Columns
  585. .Where(u => u.PropertyInfo.GetCustomAttribute<IgnoreUpdateSeedColumnAttribute>() != null)
  586. .Select(u => u.PropertyName).ToArray())
  587. .ExecuteCommand();
  588. }
  589. insertCount = storage.AsInsertable.ExecuteCommand();
  590. }
  591. else
  592. {
  593. if (!dbProvider.Queryable(entityInfo.DbTableName, entityInfo.DbTableName).Any())
  594. {
  595. insertCount = dataList.Count;
  596. dbProvider.InsertableByObject(dataList).ExecuteCommand();
  597. }
  598. }
  599. Console.WriteLine($"添加数据 {entityInfo.DbTableName,-32} ({config.ConfigId} - {Interlocked.Increment(ref count):D003}/{sum:D003},数据量:{dataList.Count:D003},插入 {insertCount:D003} 条记录,修改 {updateCount:D003} 条记录)");
  600. }
  601. }
  602. /// <summary>
  603. /// 初始化租户业务数据库
  604. /// </summary>
  605. /// <param name="iTenant"></param>
  606. /// <param name="config"></param>
  607. public static void InitTenantDatabase(ITenant iTenant, DbConnectionConfig config)
  608. {
  609. SetDbConfig(config);
  610. if (!iTenant.IsAnyConnection(config.ConfigId.ToString()))
  611. iTenant.AddConnection(config);
  612. var db = iTenant.GetConnectionScope(config.ConfigId.ToString());
  613. db.DbMaintenance.CreateDatabase();
  614. // 获取所有业务表-初始化租户库表结构(排除系统表、日志表、特定库表)
  615. var entityTypes = App.EffectiveTypes
  616. .Where(u => !u.GetCustomAttributes<IgnoreTableAttribute>().Any())
  617. .Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass && u.IsDefined(typeof(SugarTable), false) &&
  618. !u.IsDefined(typeof(SysTableAttribute), false) && !u.IsDefined(typeof(LogTableAttribute), false) && !u.IsDefined(typeof(TenantAttribute), false)).ToList();
  619. if (entityTypes.Count == 0) return;
  620. foreach (var entityType in entityTypes)
  621. {
  622. var splitTable = entityType.GetCustomAttribute<SplitTableAttribute>();
  623. if (splitTable == null)
  624. db.CodeFirst.InitTables(entityType);
  625. else
  626. db.CodeFirst.SplitTables().InitTables(entityType);
  627. }
  628. }
  629. /// <summary>
  630. /// 简单的重试机制
  631. /// </summary>
  632. /// <param name="action"></param>
  633. /// <param name="maxRetry"></param>
  634. /// <param name="retryIntervalMs"></param>
  635. private static void Retry(Action action, int maxRetry, int retryIntervalMs)
  636. {
  637. int attempt = 0;
  638. while (true)
  639. {
  640. try
  641. {
  642. action();
  643. return;
  644. }
  645. catch (SqliteException ex) when (ex.SqliteErrorCode == 5) // SQLITE_BUSY
  646. {
  647. if (++attempt >= maxRetry)
  648. {
  649. Log.Error($"简单的重试机制:{ex.Message}"); throw;
  650. }
  651. Log.Information($"数据库忙,正在重试... (尝试 {attempt}/{maxRetry})");
  652. Thread.Sleep(retryIntervalMs);
  653. }
  654. }
  655. }
  656. }