AidopTenantMigration.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. using System.Diagnostics;
  2. using Admin.NET.Core;
  3. using SqlSugar;
  4. namespace Admin.NET.Plugin.AiDOP.Infrastructure;
  5. /// <summary>
  6. /// 一次性迁移:将历史 TenantId=1 的 AiDOP 业务数据更新为框架默认租户。
  7. /// 幂等——若已无 TenantId=1 的行则不做任何事。
  8. /// </summary>
  9. public static class AidopTenantMigration
  10. {
  11. private static readonly string[] Tables =
  12. {
  13. "ado_smart_ops_kpi_master",
  14. "ado_smart_ops_layout_item",
  15. "ado_smart_ops_home_module",
  16. "ado_s9_kpi_value_l1_day",
  17. "ado_s9_kpi_value_l2_day",
  18. "ado_s9_kpi_value_l3_day"
  19. };
  20. public static void MigrateOldTenantId(ISqlSugarClient db)
  21. {
  22. var target = SqlSugarConst.DefaultTenantId;
  23. if (target == 1) return;
  24. foreach (var tbl in Tables)
  25. {
  26. try
  27. {
  28. db.Ado.ExecuteCommand(
  29. $"UPDATE `{tbl}` SET `TenantId` = @target WHERE `TenantId` = 1",
  30. new { target });
  31. }
  32. catch (Exception ex)
  33. {
  34. Trace.TraceWarning($"AidopTenantMigration [{tbl}]: {ex.Message}");
  35. }
  36. }
  37. DropOldUniqueIndex(db);
  38. BackfillThresholds(db);
  39. }
  40. private static void BackfillThresholds(ISqlSugarClient db)
  41. {
  42. try
  43. {
  44. db.Ado.ExecuteCommand(
  45. "UPDATE ado_smart_ops_kpi_master SET YellowThreshold=95, RedThreshold=80 " +
  46. "WHERE YellowThreshold IS NULL AND Direction='higher_is_better'");
  47. db.Ado.ExecuteCommand(
  48. "UPDATE ado_smart_ops_kpi_master SET YellowThreshold=110, RedThreshold=120 " +
  49. "WHERE YellowThreshold IS NULL AND Direction='lower_is_better'");
  50. }
  51. catch (Exception ex)
  52. {
  53. Trace.TraceWarning($"AidopTenantMigration backfill thresholds: {ex.Message}");
  54. }
  55. }
  56. private static void DropOldUniqueIndex(ISqlSugarClient db)
  57. {
  58. try
  59. {
  60. var rows = db.Ado.SqlQuery<dynamic>(
  61. "SHOW INDEX FROM ado_smart_ops_kpi_master WHERE Key_name = 'uk_kpi_master_code'");
  62. if (rows != null && rows.Count > 0)
  63. db.Ado.ExecuteCommand("ALTER TABLE ado_smart_ops_kpi_master DROP INDEX uk_kpi_master_code");
  64. }
  65. catch (Exception ex)
  66. {
  67. Trace.TraceWarning($"AidopTenantMigration drop old index: {ex.Message}");
  68. }
  69. }
  70. }