SqlSugarSetup.cs 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978
  1. // Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
  2. //
  3. // 本项目主要遵循 MIT 许可证和 Apache 许可证(版本 2.0)进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
  4. //
  5. // 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动!任何基于本项目二次开发而产生的一切法律纠纷和责任,我们不承担任何责任!
  6. using System.Reflection;
  7. using Microsoft.Data.Sqlite;
  8. using DbType = SqlSugar.DbType;
  9. namespace Admin.NET.Core;
  10. public static class SqlSugarSetup
  11. {
  12. // 多租户实例
  13. public static ITenant ITenant { get; set; }
  14. // 是否正在处理种子数据
  15. private static bool _isHandlingSeedData = false;
  16. /// <summary>
  17. /// SqlSugar 上下文初始化
  18. /// </summary>
  19. /// <param name="services"></param>
  20. public static void AddSqlSugar(this IServiceCollection services)
  21. {
  22. // 注册雪花Id
  23. var snowIdOpt = App.GetConfig<SnowIdOptions>("SnowId", true);
  24. YitIdHelper.SetIdGenerator(snowIdOpt);
  25. // 自定义 SqlSugar 雪花ID算法
  26. SnowFlakeSingle.WorkId = snowIdOpt.WorkerId;
  27. StaticConfig.CustomSnowFlakeFunc = YitIdHelper.NextId;
  28. // 注册 MongoDb
  29. InstanceFactory.CustomAssemblies = [typeof(SqlSugar.MongoDb.MongoDbProvider).Assembly];
  30. // 动态表达式 SqlFunc 支持,https://www.donet5.com/Home/Doc?typeId=2569
  31. StaticConfig.DynamicExpressionParserType = typeof(DynamicExpressionParser);
  32. StaticConfig.DynamicExpressionParsingConfig = new ParsingConfig
  33. {
  34. CustomTypeProvider = new SqlSugarTypeProvider()
  35. };
  36. var dbOptions = App.GetConfig<DbConnectionOptions>("DbConnection", true);
  37. // Docker 等对已有库部署:避免每次启动跑 CodeFirst/全量种子导致冲突(见 docker-compose 环境变量 DOCKER_SKIP_DBINIT)
  38. if (string.Equals(Environment.GetEnvironmentVariable("DOCKER_SKIP_DBINIT"), "1", StringComparison.Ordinal)
  39. && dbOptions.ConnectionConfigs != null)
  40. {
  41. foreach (var c in dbOptions.ConnectionConfigs)
  42. {
  43. if (c.DbSettings != null)
  44. {
  45. c.DbSettings.EnableInitDb = false;
  46. c.DbSettings.EnableInitView = false;
  47. }
  48. if (c.TableSettings != null)
  49. c.TableSettings.EnableInitTable = false;
  50. if (c.SeedSettings != null)
  51. c.SeedSettings.EnableInitSeed = false;
  52. }
  53. }
  54. dbOptions.ConnectionConfigs.ForEach(SetDbConfig);
  55. SqlSugarScope sqlSugar = new(dbOptions.ConnectionConfigs.Adapt<List<ConnectionConfig>>(), db =>
  56. {
  57. dbOptions.ConnectionConfigs.ForEach(config =>
  58. {
  59. var dbProvider = db.GetConnectionScope(config.ConfigId);
  60. SetDbAop(dbProvider, dbOptions.EnableConsoleSql, dbOptions.SuperAdminIgnoreIDeletedFilter);
  61. SetDbDiffLog(dbProvider, config);
  62. });
  63. });
  64. ITenant = sqlSugar;
  65. services.AddSingleton<ISqlSugarClient>(sqlSugar); // 单例注册
  66. services.AddScoped(typeof(SqlSugarRepository<>)); // 仓储注册
  67. services.AddUnitOfWork<SqlSugarUnitOfWork>(); // 事务与工作单元注册
  68. // 初始化数据库表结构及种子数据
  69. dbOptions.ConnectionConfigs.ForEach(config =>
  70. {
  71. InitDatabase(sqlSugar, config);
  72. });
  73. }
  74. /// <summary>
  75. /// 配置连接属性
  76. /// </summary>
  77. /// <param name="config"></param>
  78. public static void SetDbConfig(DbConnectionConfig config)
  79. {
  80. if (config.DbSettings.EnableConnStringEncrypt)
  81. config.ConnectionString = CryptogramUtil.Decrypt(config.ConnectionString);
  82. var configureExternalServices = new ConfigureExternalServices
  83. {
  84. EntityNameService = (type, entity) => // 处理表
  85. {
  86. entity.IsDisabledDelete = true; // 禁止删除非 sqlsugar 创建的列
  87. // 只处理贴了特性[SugarTable]表
  88. if (!type.GetCustomAttributes<SugarTable>().Any())
  89. return;
  90. if (config.DbSettings.EnableUnderLine && !entity.DbTableName.Contains('_'))
  91. entity.DbTableName = entity.DbTableName.ToUnderLine(); // 驼峰转下划线
  92. },
  93. EntityService = (type, column) => // 处理列
  94. {
  95. // 只处理贴了特性[SugarColumn]列
  96. if (!type.GetCustomAttributes<SugarColumn>().Any())
  97. return;
  98. if (new NullabilityInfoContext().Create(type).WriteState is NullabilityState.Nullable)
  99. column.IsNullable = true;
  100. if (config.DbSettings.EnableUnderLine && !column.IsIgnore && !column.DbColumnName.Contains('_'))
  101. {
  102. // 遗留表 NbrControl:库中为 PascalCase 审计列。若再转下划线会变成 create_time 等,
  103. // CodeFirst 会误判缺列并执行 ADD;在要求「不改表」的部署下应保持 Pascal 物理列名。
  104. const string nbrControlTypeFullName = "Admin.NET.Plugin.AiDOP.Entity.S0.Warehouse.AdoS0NbrControl";
  105. var skipUnderline = type is PropertyInfo pi
  106. && string.Equals(pi.DeclaringType?.FullName, nbrControlTypeFullName, StringComparison.Ordinal)
  107. && (pi.Name == "CreateTime" || pi.Name == "UpdateTime" || pi.Name == "CreateUser" || pi.Name == "UpdateUser");
  108. if (!skipUnderline)
  109. column.DbColumnName = column.DbColumnName.ToUnderLine();
  110. }
  111. },
  112. DataInfoCacheService = new SqlSugarCache(),
  113. };
  114. config.ConfigureExternalServices = configureExternalServices;
  115. config.InitKeyType = InitKeyType.Attribute;
  116. config.IsAutoCloseConnection = true;
  117. config.MoreSettings = new ConnMoreSettings
  118. {
  119. IsAutoRemoveDataCache = true, // 启用自动删除缓存,所有增删改会自动调用.RemoveDataCache()
  120. IsAutoDeleteQueryFilter = true, // 启用删除查询过滤器
  121. IsAutoUpdateQueryFilter = true, // 启用更新查询过滤器
  122. SqlServerCodeFirstNvarchar = true // 采用Nvarchar
  123. };
  124. // 若库类型是人大金仓则默认设置PG模式
  125. if (config.DbType == DbType.Kdbndp)
  126. config.MoreSettings.DatabaseModel = DbType.PostgreSQL; // 配置PG模式主要是兼容系统表差异
  127. // 若库类型是Oracle则默认主键名字和参数名字最大长度
  128. if (config.DbType == DbType.Oracle)
  129. config.MoreSettings.MaxParameterNameLength = 30;
  130. }
  131. /// <summary>
  132. /// 配置Aop
  133. /// </summary>
  134. /// <param name="db"></param>
  135. /// <param name="enableConsoleSql"></param>
  136. /// <param name="superAdminIgnoreIDeletedFilter"></param>
  137. public static void SetDbAop(SqlSugarScopeProvider db, bool enableConsoleSql, bool superAdminIgnoreIDeletedFilter)
  138. {
  139. // 设置超时时间
  140. db.Ado.CommandTimeOut = 30;
  141. // 打印SQL语句
  142. if (enableConsoleSql)
  143. {
  144. db.Aop.OnLogExecuting = (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. var log = $"【{DateTime.Now}——执行SQL】\r\n{UtilMethods.GetNativeSql(sql, pars)}\r\n";
  154. var originColor = Console.ForegroundColor;
  155. if (sql.StartsWith("SELECT", StringComparison.OrdinalIgnoreCase))
  156. Console.ForegroundColor = ConsoleColor.Green;
  157. if (sql.StartsWith("UPDATE", StringComparison.OrdinalIgnoreCase) || sql.StartsWith("INSERT", StringComparison.OrdinalIgnoreCase))
  158. Console.ForegroundColor = ConsoleColor.Yellow;
  159. if (sql.StartsWith("DELETE", StringComparison.OrdinalIgnoreCase))
  160. Console.ForegroundColor = ConsoleColor.Red;
  161. Console.WriteLine(log);
  162. Console.ForegroundColor = originColor;
  163. };
  164. }
  165. db.Aop.OnError = ex =>
  166. {
  167. if (ex.Parametres == null) return;
  168. var log = $"【{DateTime.Now}——错误SQL】\r\n{UtilMethods.GetNativeSql(ex.Sql, (SugarParameter[])ex.Parametres)}\r\n";
  169. Log.Error(log, ex);
  170. };
  171. db.Aop.OnLogExecuted = (sql, pars) =>
  172. {
  173. //// 若参数值超过100个字符则进行截取
  174. //foreach (var par in pars)
  175. //{
  176. // if (par.DbType != System.Data.DbType.String || par.Value == null) continue;
  177. // if (par.Value.ToString().Length > 100)
  178. // par.Value = string.Concat(par.Value.ToString()[..100], "......");
  179. //}
  180. // 执行时间超过5秒时
  181. if (!(db.Ado.SqlExecutionTime.TotalSeconds > 5)) return;
  182. var fileName = db.Ado.SqlStackTrace.FirstFileName; // 文件名
  183. var fileLine = db.Ado.SqlStackTrace.FirstLine; // 行号
  184. var firstMethodName = db.Ado.SqlStackTrace.FirstMethodName; // 方法名
  185. var log = $"【{DateTime.Now}——超时SQL】\r\n【所在文件名】:{fileName}\r\n【代码行数】:{fileLine}\r\n【方法名】:{firstMethodName}\r\n" + $"【SQL语句】:{UtilMethods.GetNativeSql(sql, pars)}";
  186. Log.Warning(log);
  187. };
  188. // 数据审计
  189. db.Aop.DataExecuting = (_, entityInfo) =>
  190. {
  191. // 若正在处理种子数据则直接返回
  192. if (_isHandlingSeedData) return;
  193. // 新增/插入
  194. if (entityInfo.OperationType == DataFilterType.InsertByObject)
  195. {
  196. // 若主键是长整型且空则赋值雪花Id
  197. if (entityInfo.EntityColumnInfo.IsPrimarykey && !entityInfo.EntityColumnInfo.IsIdentity && entityInfo.EntityColumnInfo.PropertyInfo.PropertyType == typeof(long))
  198. {
  199. var id = entityInfo.EntityColumnInfo.PropertyInfo.GetValue(entityInfo.EntityValue);
  200. if (id == null || (long)id == 0)
  201. entityInfo.SetValue(YitIdHelper.NextId());
  202. }
  203. // 若创建时间为空则赋值当前时间
  204. else if (entityInfo.PropertyName == nameof(EntityBase.CreateTime))
  205. {
  206. var createTime = entityInfo.EntityColumnInfo.PropertyInfo.GetValue(entityInfo.EntityValue)!;
  207. if (createTime == null || createTime.Equals(DateTime.MinValue))
  208. entityInfo.SetValue(DateTime.Now);
  209. }
  210. // 若当前用户为空(非web线程时)
  211. if (App.User == null) return;
  212. dynamic entityValue = entityInfo.EntityValue;
  213. if (entityInfo.PropertyName == nameof(EntityBaseTenantId.TenantId))
  214. {
  215. var tenantId = entityValue.TenantId;
  216. if (tenantId == null || tenantId == 0)
  217. entityInfo.SetValue(App.User.FindFirst(ClaimConst.TenantId)?.Value);
  218. }
  219. else if (entityInfo.PropertyName == nameof(EntityBase.CreateUserId))
  220. {
  221. var createUserId = entityValue.CreateUserId;
  222. if (createUserId == 0 || createUserId == null)
  223. entityInfo.SetValue(App.User.FindFirst(ClaimConst.UserId)?.Value);
  224. }
  225. else if (entityInfo.PropertyName == nameof(EntityBase.CreateUserName))
  226. {
  227. var createUserName = entityValue.CreateUserName;
  228. if (string.IsNullOrEmpty(createUserName))
  229. entityInfo.SetValue(App.User.FindFirst(ClaimConst.RealName)?.Value);
  230. }
  231. else if (entityInfo.PropertyName == "CreateOrgId")
  232. {
  233. var createOrgId = entityValue.CreateOrgId;
  234. if (createOrgId == 0 || createOrgId == null)
  235. entityInfo.SetValue(App.User.FindFirst(ClaimConst.OrgId)?.Value);
  236. }
  237. else if (entityInfo.PropertyName == "CreateOrgName")
  238. {
  239. var createOrgName = entityValue.CreateOrgName;
  240. if (string.IsNullOrEmpty(createOrgName))
  241. entityInfo.SetValue(App.User.FindFirst(ClaimConst.OrgName)?.Value);
  242. }
  243. }
  244. // 编辑/更新
  245. else if (entityInfo.OperationType == DataFilterType.UpdateByObject
  246. || entityInfo.OperationType == DataFilterType.DeleteByObject)
  247. {
  248. MdmMirrorWriteScope.RejectPageWrite(entityInfo.EntityValue);
  249. if (entityInfo.OperationType == DataFilterType.DeleteByObject)
  250. return;
  251. if (entityInfo.PropertyName == nameof(EntityBase.UpdateTime))
  252. entityInfo.SetValue(DateTime.Now);
  253. else if (entityInfo.PropertyName == nameof(EntityBaseDel.DeleteTime))
  254. {
  255. dynamic entityValue = entityInfo.EntityValue;
  256. var isDelete = entityValue.IsDelete;
  257. if (isDelete == true)
  258. {
  259. entityInfo.SetValue(DateTime.Now);
  260. }
  261. }
  262. // 若当前用户为空(非web线程时)
  263. if (App.User == null) return;
  264. if (entityInfo.PropertyName == nameof(EntityBase.UpdateUserId))
  265. entityInfo.SetValue(App.User?.FindFirst(ClaimConst.UserId)?.Value);
  266. else if (entityInfo.PropertyName == nameof(EntityBase.UpdateUserName))
  267. entityInfo.SetValue(App.User?.FindFirst(ClaimConst.RealName)?.Value);
  268. }
  269. };
  270. // 是否为超级管理员
  271. var isSuperAdmin = App.User?.FindFirst(ClaimConst.AccountType)?.Value == ((int)AccountTypeEnum.SuperAdmin).ToString();
  272. // 配置假删除过滤器,如果当前用户是超级管理员并且允许忽略软删除过滤器则不会应用
  273. if (!isSuperAdmin || !superAdminIgnoreIDeletedFilter)
  274. db.QueryFilter.AddTableFilter<IDeletedFilter>(u => u.IsDelete == false);
  275. // 超管排除其他过滤器
  276. if (isSuperAdmin) return;
  277. // 配置租户过滤器
  278. var tenantId = App.User?.FindFirst(ClaimConst.TenantId)?.Value;
  279. if (!string.IsNullOrWhiteSpace(tenantId))
  280. db.QueryFilter.AddTableFilter<ITenantIdFilter>(u => u.TenantId == long.Parse(tenantId));
  281. // 配置用户机构(数据范围)过滤器
  282. SqlSugarFilter.SetOrgEntityFilter(db);
  283. // 配置自定义过滤器
  284. SqlSugarFilter.SetCustomEntityFilter(db);
  285. }
  286. /// <summary>
  287. /// 开启库表差异化日志
  288. /// </summary>
  289. /// <param name="db"></param>
  290. /// <param name="config"></param>
  291. private static void SetDbDiffLog(SqlSugarScopeProvider db, DbConnectionConfig config)
  292. {
  293. if (!config.DbSettings.EnableDiffLog) return;
  294. async void AopOnDiffLogEvent(DiffLogModel u)
  295. {
  296. // 记录差异数据
  297. var diffData = new List<dynamic>();
  298. for (int i = 0; i < u.AfterData.Count; i++)
  299. {
  300. var diffColumns = new List<dynamic>();
  301. var afterColumns = u.AfterData[i].Columns;
  302. var beforeColumns = u.BeforeData[i].Columns;
  303. for (int j = 0; j < afterColumns.Count; j++)
  304. {
  305. if (afterColumns[j].Value.Equals(beforeColumns[j].Value)) continue;
  306. diffColumns.Add(new
  307. {
  308. afterColumns[j].IsPrimaryKey,
  309. afterColumns[j].ColumnName,
  310. afterColumns[j].ColumnDescription,
  311. BeforeValue = beforeColumns[j].Value,
  312. AfterValue = afterColumns[j].Value,
  313. });
  314. }
  315. diffData.Add(new { u.AfterData[i].TableName, u.AfterData[i].TableDescription, Columns = diffColumns });
  316. }
  317. var logDiff = new SysLogDiff
  318. {
  319. // 差异数据(字段描述、列名、值、表名、表描述)
  320. DiffData = JSON.Serialize(diffData),
  321. // 传进来的对象(如果对象为空,则使用首个数据的表名作为业务对象)
  322. BusinessData = u.BusinessData == null ? u.AfterData.FirstOrDefault()?.TableName : JSON.Serialize(u.BusinessData),
  323. // 枚举(insert、update、delete)
  324. DiffType = u.DiffType.ToString(),
  325. Sql = u.Sql,
  326. Parameters = JSON.Serialize(u.Parameters.Select(e => new { e.ParameterName, e.Value, TypeName = e.DbType.ToString() })),
  327. Elapsed = u.Time == null ? 0 : (long)u.Time.Value.TotalMilliseconds
  328. };
  329. var logDb = ITenant.IsAnyConnection(SqlSugarConst.LogConfigId) ? ITenant.GetConnectionScope(SqlSugarConst.LogConfigId) : ITenant.GetConnectionScope(SqlSugarConst.MainConfigId);
  330. await logDb.CopyNew().Insertable(logDiff).ExecuteCommandAsync();
  331. Console.ForegroundColor = ConsoleColor.Red;
  332. Console.WriteLine(DateTime.Now + $"\r\n*****开始差异日志*****\r\n{Environment.NewLine}{JSON.Serialize(logDiff)}{Environment.NewLine}*****结束差异日志*****\r\n");
  333. }
  334. db.Aop.OnDiffLogEvent = AopOnDiffLogEvent;
  335. }
  336. /// <summary>
  337. /// 初始化视图
  338. /// </summary>
  339. /// <param name="dbProvider"></param>
  340. private static void InitView(SqlSugarScopeProvider dbProvider)
  341. {
  342. var totalWatch = Stopwatch.StartNew(); // 开始总计时
  343. Log.Information($"初始化视图 {dbProvider.CurrentConnectionConfig.DbType} - {dbProvider.CurrentConnectionConfig.ConfigId}");
  344. var viewTypeList = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass && u.GetInterfaces().Any(i => i.HasImplementedRawGeneric(typeof(ISqlSugarView)))).ToList();
  345. int taskIndex = 0, size = viewTypeList.Count;
  346. var taskList = viewTypeList.Select(viewType => Task.Run(() =>
  347. {
  348. try
  349. {
  350. // 开始计时
  351. var stopWatch = Stopwatch.StartNew();
  352. // 获取视图实体和配置信息
  353. var entityInfo = dbProvider.EntityMaintenance.GetEntityInfo(viewType) ?? throw new Exception("获取视图实体配置有误");
  354. // 如果视图存在,则删除视图
  355. if (dbProvider.DbMaintenance.GetViewInfoList(false).Any(it => it.Name.EqualIgnoreCase(entityInfo.DbTableName)))
  356. {
  357. try
  358. {
  359. dbProvider.DbMaintenance.DropView(entityInfo.DbTableName);
  360. }
  361. catch (Exception dropEx)
  362. {
  363. Log.Warning($"删除视图失败(可能无权限),跳过:{entityInfo.DbTableName} — {dropEx.Message}");
  364. }
  365. }
  366. // 获取初始化视图查询SQL
  367. var sql = viewType.GetMethod(nameof(ISqlSugarView.GetQueryableSqlString))?.Invoke(Activator.CreateInstance(viewType), [dbProvider]) as string;
  368. if (string.IsNullOrWhiteSpace(sql)) throw new Exception("视图初始化Sql语句不能为空");
  369. // 创建视图
  370. dbProvider.Ado.ExecuteCommand($"CREATE VIEW {entityInfo.DbTableName} AS " + Environment.NewLine + " " + sql);
  371. // 停止计时
  372. stopWatch.Stop();
  373. Console.ForegroundColor = ConsoleColor.Green;
  374. Console.WriteLine($"初始化视图 {viewType.FullName,-58} ({dbProvider.CurrentConnectionConfig.ConfigId} - {Interlocked.Increment(ref taskIndex):D003}/{size:D003},耗时:{stopWatch.ElapsedMilliseconds:N0} ms)");
  375. }
  376. catch (Exception ex)
  377. {
  378. Log.Warning($"初始化视图失败已跳过:{viewType.FullName} — {ex.Message}");
  379. }
  380. }));
  381. Task.WaitAll(taskList.ToArray());
  382. totalWatch.Stop(); // 停止总计时
  383. Console.ForegroundColor = ConsoleColor.Green;
  384. Console.WriteLine($"初始化视图 {dbProvider.CurrentConnectionConfig.DbType} - {dbProvider.CurrentConnectionConfig.ConfigId} 总耗时:{totalWatch.ElapsedMilliseconds:N0} ms");
  385. }
  386. /// <summary>
  387. /// 等待数据库就绪
  388. /// </summary>
  389. /// <param name="dbProvider"></param>
  390. private static void WaitForDatabaseReady(SqlSugarScopeProvider dbProvider)
  391. {
  392. var maxWaitSeconds = 0;
  393. _ = int.TryParse(Environment.GetEnvironmentVariable("AIDOP_DB_WAIT_MAX_SECONDS"), out maxWaitSeconds);
  394. var deadline = maxWaitSeconds > 0 ? DateTime.UtcNow.AddSeconds(maxWaitSeconds) : DateTime.MaxValue;
  395. do
  396. {
  397. if (maxWaitSeconds > 0 && DateTime.UtcNow > deadline)
  398. {
  399. throw new TimeoutException(
  400. $"等待数据库就绪已超过 {maxWaitSeconds} 秒(环境变量 AIDOP_DB_WAIT_MAX_SECONDS)。请检查连接串、网络与账号权限;不需要超时限制时请移除此环境变量。");
  401. }
  402. try
  403. {
  404. if (dbProvider.Ado.Connection.State != ConnectionState.Open)
  405. dbProvider.Ado.Connection.Open();
  406. // 如果连接成功,直接返回
  407. Log.Information("数据库连接成功。");
  408. return;
  409. }
  410. catch (Exception ex)
  411. {
  412. Log.Warning($"数据库尚未就绪,等待中... 错误:{ex.Message}");
  413. Thread.Sleep(1000);
  414. }
  415. } while (true);
  416. }
  417. /// <summary>
  418. /// 初始化数据库
  419. /// </summary>
  420. /// <param name="db">SqlSugarScope 实例</param>
  421. /// <param name="config">数据库连接配置</param>
  422. private static void InitDatabase(SqlSugarScope db, DbConnectionConfig config)
  423. {
  424. var dbProvider = db.GetConnectionScope(config.ConfigId);
  425. // 初始化数据库 如果是没有数据库的话,是先初始化数据库再做连接
  426. if (config.DbSettings.EnableInitDb)
  427. {
  428. Log.Information($"初始化数据库 {config.DbType} - {config.ConfigId} - {config.ConnectionString}");
  429. if (config.DbType != DbType.Oracle) dbProvider.DbMaintenance.CreateDatabase();
  430. }
  431. // 等待数据库连接就绪
  432. WaitForDatabaseReady(dbProvider);
  433. // 初始化表结构
  434. if (config.TableSettings.EnableInitTable)
  435. {
  436. Log.Information($"初始化表结构 {config.DbType} - {config.ConfigId}");
  437. var entityTypes = GetEntityTypesForInit(config);
  438. var originCommandTimeout = dbProvider.Ado.CommandTimeOut;
  439. dbProvider.Ado.CommandTimeOut = ResolveInitTableCommandTimeout(config);
  440. try
  441. {
  442. RunPreInitMigrations(dbProvider, entityTypes);
  443. InitializeTables(dbProvider, entityTypes, config);
  444. }
  445. finally
  446. {
  447. dbProvider.Ado.CommandTimeOut = originCommandTimeout;
  448. }
  449. }
  450. // 初始化视图
  451. if (config.DbSettings.EnableInitView) InitView(dbProvider);
  452. // 初始化种子数据
  453. if (config.SeedSettings.EnableInitSeed) InitSeedData(db, config);
  454. }
  455. /// <summary>
  456. /// 获取需要初始化的实体类型
  457. /// </summary>
  458. /// <param name="config">数据库连接配置</param>
  459. /// <returns>实体类型列表</returns>
  460. private static List<Type> GetEntityTypesForInit(DbConnectionConfig config)
  461. {
  462. return App.EffectiveTypes
  463. .Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass && u.IsDefined(typeof(SugarTable), false))
  464. .Where(u => !u.GetCustomAttributes<IgnoreTableAttribute>().Any())
  465. .WhereIF(config.TableSettings.EnableIncreTable, u => u.IsDefined(typeof(IncreTableAttribute), false))
  466. .Where(u => IsEntityForConfig(u, config))
  467. .ToList();
  468. }
  469. /// <summary>
  470. /// 在全局 InitTables 之前执行插件级预迁移,避免 CodeFirst 先补出新列。
  471. /// </summary>
  472. private static void RunPreInitMigrations(SqlSugarScopeProvider dbProvider, List<Type> entityTypes)
  473. {
  474. if (!entityTypes.Any(t => t.FullName?.Contains(".Entity.S0.") == true))
  475. return;
  476. var migrationType = App.EffectiveTypes.FirstOrDefault(t =>
  477. t.FullName == "Admin.NET.Plugin.AiDOP.Infrastructure.AidopS0ExcelColumnMigration");
  478. var migrateMethod = migrationType?.GetMethod("Migrate", BindingFlags.Public | BindingFlags.Static);
  479. if (migrateMethod == null)
  480. return;
  481. try
  482. {
  483. migrateMethod.Invoke(null, [dbProvider]);
  484. }
  485. catch (TargetInvocationException tie) when (tie.InnerException != null)
  486. {
  487. Log.Error($"AidopS0ExcelColumnMigration.Migrate 执行失败:{tie.InnerException.Message}", tie.InnerException);
  488. throw tie.InnerException;
  489. }
  490. }
  491. /// <summary>
  492. /// 判断实体是否属于当前配置
  493. /// </summary>
  494. /// <param name="entityType">实体类型</param>
  495. /// <param name="config">数据库连接配置</param>
  496. /// <returns>是否属于当前配置</returns>
  497. private static bool IsEntityForConfig(Type entityType, DbConnectionConfig config)
  498. {
  499. switch (config.ConfigId.ToString())
  500. {
  501. case SqlSugarConst.MainConfigId:
  502. return entityType.GetCustomAttributes<SysTableAttribute>().Any() ||
  503. (!entityType.GetCustomAttributes<LogTableAttribute>().Any() &&
  504. !entityType.GetCustomAttributes<TenantAttribute>().Any(o => o.configId.ToString() != config.ConfigId.ToString()));
  505. case SqlSugarConst.LogConfigId:
  506. return entityType.GetCustomAttributes<LogTableAttribute>().Any();
  507. default:
  508. {
  509. var tenantAttribute = entityType.GetCustomAttribute<TenantAttribute>();
  510. return tenantAttribute != null && tenantAttribute.configId.ToString() == config.ConfigId.ToString();
  511. }
  512. }
  513. }
  514. /// <summary>
  515. /// 初始化表结构
  516. /// </summary>
  517. /// <param name="dbProvider">SqlSugarScopeProvider 实例</param>
  518. /// <param name="entityTypes">实体类型列表</param>
  519. /// <param name="config">数据库连接配置</param>
  520. private static void InitializeTables(SqlSugarScopeProvider dbProvider, List<Type> entityTypes, DbConnectionConfig config)
  521. {
  522. // 删除视图再初始化表结构,防止因为视图导致无法同步表结构
  523. var viewTypeList = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass && u.GetInterfaces().Any(i => i.HasImplementedRawGeneric(typeof(ISqlSugarView)))).ToList();
  524. foreach (var viewType in viewTypeList)
  525. {
  526. var entityInfo = dbProvider.EntityMaintenance.GetEntityInfo(viewType) ?? throw new Exception("获取视图实体配置有误");
  527. if (dbProvider.DbMaintenance.GetViewInfoList(false).Any(it => it.Name.EqualIgnoreCase(entityInfo.DbTableName)))
  528. {
  529. try
  530. {
  531. dbProvider.DbMaintenance.DropView(entityInfo.DbTableName);
  532. }
  533. catch (Exception ex)
  534. {
  535. // 低权限账号下可能不具备 DROP VIEW 权限,跳过视图删除避免启动中断
  536. Console.WriteLine($"跳过删除视图 {entityInfo.DbTableName}:{ex.Message}");
  537. }
  538. }
  539. }
  540. var maxDegree = ResolveInitTableMaxDegreeOfParallelism(config);
  541. int count = 0, sum = entityTypes.Count;
  542. var continueOnEntityFailure = ResolveContinueInitTableOnEntityFailure(config);
  543. void InitOne(Type entityType)
  544. {
  545. var label = entityType.FullName ?? entityType.Name;
  546. string tableName = "";
  547. try
  548. {
  549. tableName = dbProvider.EntityMaintenance.GetEntityInfo(entityType).DbTableName;
  550. }
  551. catch
  552. {
  553. // 仅用于日志;后续 UpdateNullableColumns 仍会抛出更具体错误
  554. }
  555. Console.WriteLine($"初始化表结构 {entityType.FullName,-64} ({config.ConfigId} - {Interlocked.Increment(ref count):D003}/{sum:D003})");
  556. try
  557. {
  558. UpdateNullableColumns(dbProvider, entityType);
  559. InitializeTable(dbProvider, entityType, config);
  560. }
  561. catch (Exception ex)
  562. {
  563. // MySQL 上部分 DDL 具备幂等语义,但不同版本/元数据读取差异可能导致 CodeFirst 重复生成 DDL。
  564. // 典型:表已有主键时仍尝试 ADD PRIMARY KEY -> Multiple primary key defined。
  565. // 这类问题不应阻塞启动与其余实体初始化(联调环境更常见)。
  566. var msg = ex.ToString();
  567. if (msg.Contains("Multiple primary key defined", StringComparison.OrdinalIgnoreCase)
  568. || msg.Contains("Duplicate key name", StringComparison.OrdinalIgnoreCase)
  569. || msg.Contains("Duplicate column name", StringComparison.OrdinalIgnoreCase)
  570. || msg.Contains("All parts of a PRIMARY KEY must be NOT NULL", StringComparison.OrdinalIgnoreCase)
  571. || msg.Contains("Can't DROP", StringComparison.OrdinalIgnoreCase) && msg.Contains("check that column/key exists", StringComparison.OrdinalIgnoreCase))
  572. {
  573. Log.Warning($"初始化表结构遇到可忽略的 DDL 冲突,已跳过:Entity={label} Table={tableName} ConfigId={config.ConfigId} — {ex.Message}");
  574. return;
  575. }
  576. Log.Error($"初始化表结构失败 Entity={label} Table={tableName} ConfigId={config.ConfigId}: {ex.Message}", ex);
  577. if (continueOnEntityFailure)
  578. {
  579. Log.Warning(
  580. "已启用跳过单表失败(TableSettings:ContinueInitTableOnEntityFailure 或环境变量 AIDOP_CODEFIRST_CONTINUE_ON_ENTITY_ERROR=1),将继续初始化其余实体;库结构可能不完整。");
  581. return;
  582. }
  583. throw new InvalidOperationException(
  584. $"表结构初始化失败: {label}(表 {tableName})。请检查上方日志中的 DDL/SQL 异常;可临时关闭 TableSettings:EnableInitTable,或仅在联调时开启 ContinueInitTableOnEntityFailure / AIDOP_CODEFIRST_CONTINUE_ON_ENTITY_ERROR=1。",
  585. ex);
  586. }
  587. }
  588. if (maxDegree <= 1)
  589. {
  590. foreach (var entityType in entityTypes)
  591. InitOne(entityType);
  592. return;
  593. }
  594. Parallel.ForEach(entityTypes, new ParallelOptions { MaxDegreeOfParallelism = maxDegree }, InitOne);
  595. }
  596. /// <summary>
  597. /// 更新表中不存在于实体的字段为可空
  598. /// </summary>
  599. /// <param name="dbProvider">SqlSugarScopeProvider 实例</param>
  600. /// <param name="entityType">实体类型</param>
  601. private static void UpdateNullableColumns(SqlSugarScopeProvider dbProvider, Type entityType)
  602. {
  603. var entityInfo = dbProvider.EntityMaintenance.GetEntityInfo(entityType);
  604. var dbColumns = dbProvider.DbMaintenance.GetColumnInfosByTableName(entityInfo.DbTableName) ?? new List<DbColumnInfo>();
  605. foreach (var dbColumn in dbColumns.Where(c => !c.IsPrimarykey && entityInfo.Columns.All(u => u.DbColumnName != c.DbColumnName)))
  606. {
  607. try
  608. {
  609. dbColumn.IsNullable = true;
  610. Retry(() =>
  611. {
  612. dbProvider.DbMaintenance.UpdateColumn(entityInfo.DbTableName, dbColumn);
  613. }, maxRetry: 3, retryIntervalMs: 1000);
  614. }
  615. catch (Exception ex)
  616. {
  617. // 低权限或列类型不支持等:不应阻塞整张表 CodeFirst
  618. Log.Warning($"将多余列改为可空失败,已跳过:{entityInfo.DbTableName}.{dbColumn.DbColumnName} — {ex.Message}");
  619. }
  620. }
  621. }
  622. /// <summary>
  623. /// 初始化表
  624. /// </summary>
  625. /// <param name="dbProvider">SqlSugarScopeProvider 实例</param>
  626. /// <param name="entityType">实体类型</param>
  627. private static void InitializeTable(SqlSugarScopeProvider dbProvider, Type entityType, DbConnectionConfig config)
  628. {
  629. Retry(() =>
  630. {
  631. if (entityType.GetCustomAttribute<SplitTableAttribute>() == null)
  632. {
  633. dbProvider.CodeFirst.InitTables(entityType);
  634. }
  635. else
  636. {
  637. dbProvider.CodeFirst.SplitTables().InitTables(entityType);
  638. }
  639. }, ResolveInitTableRetryCount(config), ResolveInitTableRetryIntervalMs(config));
  640. }
  641. /// <summary>
  642. /// 初始化种子数据
  643. /// </summary>
  644. /// <param name="db">SqlSugarScope 实例</param>
  645. /// <param name="config">数据库连接配置</param>
  646. private static void InitSeedData(SqlSugarScope db, DbConnectionConfig config)
  647. {
  648. _isHandlingSeedData = true;
  649. try
  650. {
  651. Log.Information($"初始化种子数据 {config.DbType} - {config.ConfigId}");
  652. var seedDataTypes = GetSeedDataTypes(config);
  653. int count = 0, sum = seedDataTypes.Count;
  654. foreach (var seedType in seedDataTypes)
  655. {
  656. var entityType = seedType.GetInterfaces().First().GetGenericArguments().First();
  657. if (!IsEntityForConfig(entityType, config)) continue;
  658. var seedData = GetSeedData(seedType)?.ToList();
  659. if (seedData == null) continue;
  660. AdjustSeedDataIds(seedData, config);
  661. try
  662. {
  663. var dbProvider = db.GetConnectionScope(config.ConfigId);
  664. InsertOrUpdateSeedData(dbProvider, seedType, entityType, seedData, config, ref count, sum);
  665. }
  666. catch (Exception ex)
  667. {
  668. throw Oops.Oh($"初始化种子数据失败: Seed={seedType.FullName}, Entity={entityType.FullName}, ConfigId={config.ConfigId}", ex);
  669. }
  670. }
  671. }
  672. finally
  673. {
  674. _isHandlingSeedData = false;
  675. }
  676. }
  677. /// <summary>
  678. /// 获取种子数据类型
  679. /// </summary>
  680. /// <param name="config">数据库连接配置</param>
  681. /// <returns>种子数据类型列表</returns>
  682. private static List<Type> GetSeedDataTypes(DbConnectionConfig config)
  683. {
  684. return App.EffectiveTypes
  685. .Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass && u.GetInterfaces().Any(i => i.HasImplementedRawGeneric(typeof(ISqlSugarEntitySeedData<>))))
  686. .WhereIF(config.SeedSettings.EnableIncreSeed, u => u.IsDefined(typeof(IncreSeedAttribute), false))
  687. .OrderBy(u => u.GetCustomAttributes(typeof(SeedDataAttribute), false).Length > 0 ? ((SeedDataAttribute)u.GetCustomAttributes(typeof(SeedDataAttribute), false)[0]).Order : 0)
  688. .ToList();
  689. }
  690. /// <summary>
  691. /// 获取种子数据
  692. /// </summary>
  693. /// <param name="seedType">种子数据类型</param>
  694. /// <returns>种子数据列表</returns>
  695. private static IEnumerable<object> GetSeedData(Type seedType)
  696. {
  697. var instance = Activator.CreateInstance(seedType);
  698. var hasDataMethod = seedType.GetMethod("HasData");
  699. return ((IEnumerable)hasDataMethod?.Invoke(instance, null))?.Cast<object>();
  700. }
  701. /// <summary>
  702. /// 调整种子数据的 ID
  703. /// </summary>
  704. /// <param name="seedData">种子数据列表</param>
  705. /// <param name="config">数据库连接配置</param>
  706. private static void AdjustSeedDataIds(IEnumerable<object> seedData, DbConnectionConfig config)
  707. {
  708. var seedId = config.ConfigId.ToLong();
  709. foreach (var data in seedData)
  710. {
  711. var idProperty = data.GetType().GetProperty(nameof(EntityBaseId.Id));
  712. if (idProperty == null || idProperty.PropertyType != typeof(Int64)) continue;
  713. var idValue = idProperty.GetValue(data);
  714. if (idValue == null || idValue.ToString() == "0" || string.IsNullOrWhiteSpace(idValue.ToString()))
  715. {
  716. idProperty.SetValue(data, ++seedId);
  717. }
  718. }
  719. }
  720. /// <summary>
  721. /// 插入或更新种子数据
  722. /// </summary>
  723. /// <param name="dbProvider">SqlSugarScopeProvider 实例</param>
  724. /// <param name="seedType">种子数据类型</param>
  725. /// <param name="entityType">实体类型</param>
  726. /// <param name="seedData">种子数据列表</param>
  727. /// <param name="config">数据库连接配置</param>
  728. /// <param name="count">当前处理的数量</param>
  729. /// <param name="sum">总数量</param>
  730. private static void InsertOrUpdateSeedData(SqlSugarScopeProvider dbProvider, Type seedType, Type entityType, IEnumerable<object> seedData, DbConnectionConfig config, ref int count, int sum)
  731. {
  732. var entityInfo = dbProvider.EntityMaintenance.GetEntityInfo(entityType);
  733. var dataList = seedData.ToList();
  734. if (entityType.GetCustomAttribute<SplitTableAttribute>(true) != null)
  735. {
  736. var initMethod = seedType.GetMethod("Init");
  737. initMethod?.Invoke(Activator.CreateInstance(seedType), new object[] { dbProvider });
  738. }
  739. else
  740. {
  741. int updateCount = 0, insertCount = 0;
  742. if (entityInfo.Columns.Any(u => u.IsPrimarykey))
  743. {
  744. var storage = dbProvider.StorageableByObject(dataList).ToStorage();
  745. if (seedType.GetCustomAttribute<IgnoreUpdateSeedAttribute>() == null)
  746. {
  747. updateCount = storage.AsUpdateable
  748. .IgnoreColumns(entityInfo.Columns
  749. .Where(u => u.PropertyInfo.GetCustomAttribute<IgnoreUpdateSeedColumnAttribute>() != null)
  750. .Select(u => u.PropertyName).ToArray())
  751. .ExecuteCommand();
  752. }
  753. insertCount = storage.AsInsertable.ExecuteCommand();
  754. }
  755. else
  756. {
  757. if (!dbProvider.Queryable(entityInfo.DbTableName, entityInfo.DbTableName).Any())
  758. {
  759. insertCount = dataList.Count;
  760. dbProvider.InsertableByObject(dataList).ExecuteCommand();
  761. }
  762. }
  763. Console.WriteLine($"添加数据 {entityInfo.DbTableName,-32} ({config.ConfigId} - {Interlocked.Increment(ref count):D003}/{sum:D003},数据量:{dataList.Count:D003},插入 {insertCount:D003} 条记录,修改 {updateCount:D003} 条记录)");
  764. }
  765. }
  766. /// <summary>
  767. /// 初始化租户业务数据库
  768. /// </summary>
  769. /// <param name="iTenant"></param>
  770. /// <param name="config"></param>
  771. public static void InitTenantDatabase(ITenant iTenant, DbConnectionConfig config)
  772. {
  773. SetDbConfig(config);
  774. if (!iTenant.IsAnyConnection(config.ConfigId.ToString()))
  775. iTenant.AddConnection(config);
  776. var db = iTenant.GetConnectionScope(config.ConfigId.ToString());
  777. db.DbMaintenance.CreateDatabase();
  778. // 获取所有业务表-初始化租户库表结构(排除系统表、日志表、特定库表)
  779. var entityTypes = App.EffectiveTypes
  780. .Where(u => !u.GetCustomAttributes<IgnoreTableAttribute>().Any())
  781. .Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass && u.IsDefined(typeof(SugarTable), false) &&
  782. !u.IsDefined(typeof(SysTableAttribute), false) && !u.IsDefined(typeof(LogTableAttribute), false) && !u.IsDefined(typeof(TenantAttribute), false)).ToList();
  783. if (entityTypes.Count == 0) return;
  784. foreach (var entityType in entityTypes)
  785. {
  786. var splitTable = entityType.GetCustomAttribute<SplitTableAttribute>();
  787. if (splitTable == null)
  788. db.CodeFirst.InitTables(entityType);
  789. else
  790. db.CodeFirst.SplitTables().InitTables(entityType);
  791. }
  792. }
  793. /// <summary>
  794. /// 简单的重试机制
  795. /// </summary>
  796. /// <param name="action"></param>
  797. /// <param name="maxRetry"></param>
  798. /// <param name="retryIntervalMs"></param>
  799. private static void Retry(Action action, int maxRetry, int retryIntervalMs)
  800. {
  801. int attempt = 0;
  802. while (true)
  803. {
  804. try
  805. {
  806. action();
  807. return;
  808. }
  809. catch (Exception ex) when (IsRetryableDatabaseInitException(ex))
  810. {
  811. if (++attempt >= maxRetry)
  812. {
  813. Log.Error($"简单的重试机制:{ex.Message}"); throw;
  814. }
  815. Log.Information($"数据库初始化异常,正在重试... (尝试 {attempt}/{maxRetry}) {ex.Message}");
  816. Thread.Sleep(retryIntervalMs);
  817. }
  818. }
  819. }
  820. private static int ResolveInitTableMaxDegreeOfParallelism(DbConnectionConfig config)
  821. {
  822. var value = config.TableSettings?.InitTableMaxDegreeOfParallelism ?? 1;
  823. return value <= 0 ? 1 : value;
  824. }
  825. private static int ResolveInitTableRetryCount(DbConnectionConfig config)
  826. {
  827. var value = config.TableSettings?.InitTableRetryCount ?? 3;
  828. return value <= 0 ? 1 : value;
  829. }
  830. private static int ResolveInitTableRetryIntervalMs(DbConnectionConfig config)
  831. {
  832. var value = config.TableSettings?.InitTableRetryIntervalMs ?? 2000;
  833. return value < 0 ? 2000 : value;
  834. }
  835. private static int ResolveInitTableCommandTimeout(DbConnectionConfig config)
  836. {
  837. var value = config.TableSettings?.InitTableCommandTimeoutSeconds ?? 120;
  838. return value <= 0 ? 120 : value;
  839. }
  840. /// <summary>
  841. /// 单实体 CodeFirst 失败时是否跳过并继续(环境变量优先)。
  842. /// </summary>
  843. private static bool ResolveContinueInitTableOnEntityFailure(DbConnectionConfig config)
  844. {
  845. if (string.Equals(Environment.GetEnvironmentVariable("AIDOP_CODEFIRST_CONTINUE_ON_ENTITY_ERROR"), "1", StringComparison.OrdinalIgnoreCase))
  846. return true;
  847. return config.TableSettings?.ContinueInitTableOnEntityFailure == true;
  848. }
  849. private static bool IsRetryableDatabaseInitException(Exception ex)
  850. {
  851. if (ex is SqliteException sqliteException && sqliteException.SqliteErrorCode == 5)
  852. return true;
  853. var current = ex;
  854. while (current != null)
  855. {
  856. if (current is TimeoutException)
  857. return true;
  858. var typeName = current.GetType().FullName ?? "";
  859. var message = current.Message ?? "";
  860. if (typeName.Contains("SqlSugarException", StringComparison.OrdinalIgnoreCase) &&
  861. ContainsRetryableDatabaseMessage(message))
  862. return true;
  863. if (typeName.Contains("MySql", StringComparison.OrdinalIgnoreCase) &&
  864. ContainsRetryableDatabaseMessage(message))
  865. return true;
  866. if (ContainsRetryableDatabaseMessage(message))
  867. return true;
  868. current = current.InnerException;
  869. }
  870. return false;
  871. }
  872. private static bool ContainsRetryableDatabaseMessage(string message)
  873. {
  874. return message.Contains("timeout", StringComparison.OrdinalIgnoreCase)
  875. || message.Contains("timed out", StringComparison.OrdinalIgnoreCase)
  876. || message.Contains("Lock wait timeout", StringComparison.OrdinalIgnoreCase)
  877. || message.Contains("Deadlock found", StringComparison.OrdinalIgnoreCase)
  878. || message.Contains("database is locked", StringComparison.OrdinalIgnoreCase)
  879. || message.Contains("SQLITE_BUSY", StringComparison.OrdinalIgnoreCase);
  880. }
  881. }