DatabaseInitializer.cs 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. using SqlSugar;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using TeamAAS_VP.Interfaces;
  8. using TeamAAS_VP.Models;
  9. namespace TeamAAS_VP.Data
  10. {
  11. // 数据库初始化实现
  12. public class DatabaseInitializer : IDatabaseInitializer
  13. {
  14. private readonly ISqlSugarClient _db;
  15. public DatabaseInitializer(ISqlSugarClient db)
  16. {
  17. _db = db;
  18. }
  19. public void InitializeDatabase()
  20. {
  21. const int maxRetry = 3;
  22. Exception lastEx = null;
  23. for (int attempt = 1; attempt <= maxRetry; attempt++)
  24. {
  25. try
  26. {
  27. // 创建数据库(如果不存在)
  28. _db.DbMaintenance.CreateDatabase();
  29. // 创建表
  30. _db.CodeFirst.InitTables(typeof(User), typeof(ProductionRecord), typeof(UserLoginRecord), typeof(AlarmRecord), typeof(LockResult), typeof(ProductWithMes));
  31. // 创建索引
  32. CreateIndexes();
  33. // 如果用户表为空,插入三个基础用户
  34. var userCount = _db.Queryable<User>().Count();
  35. if (userCount == 0)
  36. {
  37. var op = new User { UserName = "操作员", UserPassword = "", userPart = Enums.UserPart.Operator, CreateTime = DateTime.Now, IsRemember = false };
  38. var eng = new User { UserName = "工程师", UserPassword = "10086", userPart = Enums.UserPart.Engineer, CreateTime = DateTime.Now, IsRemember = false };
  39. var admin = new User { UserName = "管理员", UserPassword = "team123456", userPart = Enums.UserPart.Administrator, CreateTime = DateTime.Now, IsRemember = false };
  40. _db.Insertable(new List<User> { op, eng, admin }).ExecuteCommand();
  41. }
  42. return; // 成功,退出
  43. }
  44. catch (Exception ex)
  45. {
  46. lastEx = ex;
  47. bool isDbCorrupted = ex.Message.Contains("invalid") || ex.Message.Contains("corrupt")
  48. || ex.Message.Contains("无效") || ex.Message.Contains("损坏");
  49. if (attempt < maxRetry)
  50. {
  51. if (isDbCorrupted)
  52. {
  53. // 数据库可能损坏,尝试删除重建
  54. try
  55. {
  56. string dbPath = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "AlignerDB.db");
  57. if (System.IO.File.Exists(dbPath))
  58. {
  59. System.IO.File.Delete(dbPath);
  60. }
  61. LogHelper.WriteLogInfo($"数据库文件已删除,准备重建 (attempt {attempt})");
  62. }
  63. catch
  64. {
  65. // 删除失败,继续重试
  66. }
  67. }
  68. System.Threading.Thread.Sleep(500 * attempt); // 递增等待
  69. }
  70. }
  71. }
  72. // 所有重试均失败
  73. throw new Exception($"数据库初始化失败(已重试{maxRetry}次): {lastEx?.Message}", lastEx);
  74. }
  75. public bool DatabaseExists()
  76. {
  77. return _db.DbMaintenance.GetDataBaseList().Contains("AlignerDB");
  78. }
  79. private void CreateIndexes()
  80. {
  81. try
  82. {
  83. // Ensure LockResult indexes for common queries
  84. // 单列索引:Timestamp, ProductNumber, LockPassed
  85. try { _db.DbMaintenance.CreateIndex("LockResult", new string[] { "Timestamp" }, "IX_LockResult_Timestamp", false); } catch { }
  86. try { _db.DbMaintenance.CreateIndex("LockResult", new string[] { "ProductNumber" }, "IX_LockResult_ProductNumber", false); } catch { }
  87. try { _db.DbMaintenance.CreateIndex("LockResult", new string[] { "LockPassed" }, "IX_LockResult_LockPassed", false); } catch { }
  88. // 新增索引:Number, FeederNumber, NozzleNumber
  89. try { _db.DbMaintenance.CreateIndex("LockResult", new string[] { "Number" }, "IX_LockResult_Number", false); } catch { }
  90. try { _db.DbMaintenance.CreateIndex("LockResult", new string[] { "FeederNumber" }, "IX_LockResult_FeederNumber", false); } catch { }
  91. try { _db.DbMaintenance.CreateIndex("LockResult", new string[] { "NozzleNumber" }, "IX_LockResult_NozzleNumber", false); } catch { }
  92. // 复合索引:ProductNumber + Timestamp(支持按产品+时间范围查询)
  93. try { _db.DbMaintenance.CreateIndex("LockResult", new string[] { "ProductNumber", "Timestamp" }, "IX_LockResult_ProductNumber_Timestamp", false); } catch { }
  94. // 你可以在这里为其他表添加索引,例如 ProductionRecord 的 Timestamp 或 ProductName
  95. try { _db.DbMaintenance.CreateIndex("ProductionRecord", new string[] { "ProductName", "Timestamp" }, "IX_ProductionRecord_ProductName_Timestamp", false); } catch { }
  96. }
  97. catch
  98. {
  99. // 忽略索引创建中的错误(如已存在),调用方仍然可以继续
  100. }
  101. }
  102. }
  103. }