using Microsoft.Data.SqlClient;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
namespace ZB.MOM.WW.OtOpcUa.Configuration.Tests;
///
/// lmxopcua#1040 / #1049: migration ScriptForeignKeysAndExternalIdUniqueness must refuse — loudly, naming the
/// rows, and changing NOTHING — a populated ConfigDb holding data its constraints cannot hold (dangling script
/// references, duplicated ZTag / SAPID, reservation history it would drop); and apply cleanly once they are fixed.
/// Each test migrates its own scratch database to the previous migration, seeds, then migrates up.
///
[Trait("Category", "SchemaCompliance")]
[Collection(nameof(SchemaComplianceCollection))]
public sealed class ScriptForeignKeysAndExternalIdUniquenessMigrationTests
{
private const string Previous = "20261203154217_ConfigurationGapsIndexesAndRowVersions";
// Migrate up to THIS migration, not the latest: a later migration must not change what these tests assert (#1084 added one).
private const string This = "20261203200204_ScriptForeignKeysAndExternalIdUniqueness";
private static Equipment NewEquipment(string? zTag = null, string? sapId = null)
{
var uuid = Guid.NewGuid();
return new Equipment
{
EquipmentId = "EQ-" + uuid.ToString("N")[..12], EquipmentUuid = uuid, UnsLineId = "line-" + uuid.ToString("N"),
Name = "eq", MachineCode = "mc-" + uuid.ToString("N"), ZTag = zTag, SAPID = sapId,
};
}
/// Every offending row class is named in ONE refusal and the schema is left exactly as it was.
[Fact]
public void Offending_rows_refuse_the_migration_and_nothing_changes()
{
using var scratch = new MigrationScratchDatabase();
scratch.MigrateTo(Previous);
using (var db = scratch.NewContext())
{
db.VirtualTags.Add(new VirtualTag
{
VirtualTagId = "VT-dangling", EquipmentId = "EQ-x", Name = "V", DataType = "Int32", ScriptId = "SC-gone",
});
db.ScriptedAlarms.Add(new ScriptedAlarm
{
ScriptedAlarmId = "SA-dangling", EquipmentId = "EQ-x", Name = "A", AlarmType = "AlarmCondition",
MessageTemplate = "m", PredicateScriptId = "SC-also-gone",
});
db.Equipment.AddRange(NewEquipment(zTag: "ZT-1"), NewEquipment(zTag: "zt-1"), NewEquipment(sapId: "SAP-1"), NewEquipment(sapId: "SAP-1"));
db.SaveChanges();
}
scratch.Execute(
"INSERT ExternalIdReservation (Kind, Value, EquipmentUuid, ClusterId, FirstPublishedBy) VALUES ('ZTag', 'ZT-9', NEWID(), 'c', 't')");
var ex = Should.Throw(() => scratch.MigrateTo(This));
ex.Number.ShouldBe(51049);
ex.Message.ShouldContain("VT-dangling->SC-gone");
ex.Message.ShouldContain("SA-dangling->SC-also-gone");
ex.Message.ShouldContain("ZTag value(s)");
ex.Message.ShouldContain("SAPID value(s)");
ex.Message.ShouldContain("1 ExternalIdReservation row(s)");
scratch.LastAppliedMigration().ShouldBe(Previous);
scratch.Scalar("SELECT COUNT(*) FROM sys.indexes WHERE name = 'IX_Equipment_ZTag'").ShouldBe(1);
scratch.Scalar("SELECT COUNT(*) FROM ExternalIdReservation").ShouldBe(1);
scratch.Scalar("SELECT COUNT(*) FROM sys.foreign_keys WHERE name = 'FK_VirtualTag_Script'").ShouldBe(0);
}
/// Positive control: once the operator fixes the rows the same database migrates and the constraints exist.
[Fact]
public void A_clean_populated_database_migrates_and_gains_the_constraints()
{
using var scratch = new MigrationScratchDatabase();
scratch.MigrateTo(Previous);
using (var db = scratch.NewContext())
{
db.Scripts.Add(new Script { ScriptId = "SC-1", Name = "s", SourceCode = "return 1;", SourceHash = new string('a', 64) });
db.VirtualTags.Add(new VirtualTag
{
VirtualTagId = "VT-ok", EquipmentId = "EQ-x", Name = "V", DataType = "Int32", ScriptId = "SC-1",
});
db.ScriptedAlarms.Add(new ScriptedAlarm
{
ScriptedAlarmId = "SA-ok", EquipmentId = "EQ-x", Name = "A", AlarmType = "AlarmCondition",
MessageTemplate = "m", PredicateScriptId = "SC-1",
});
// Blank and NULL identifiers are "none" and may repeat; distinct values are fine.
db.Equipment.AddRange(NewEquipment(), NewEquipment(), NewEquipment(zTag: "", sapId: ""), NewEquipment(zTag: "", sapId: ""),
NewEquipment(zTag: "ZT-1", sapId: "SAP-1"), NewEquipment(zTag: "ZT-2", sapId: "SAP-2"));
db.SaveChanges();
}
Should.NotThrow(() => scratch.MigrateTo(This));
scratch.LastAppliedMigration().ShouldEndWith("_ScriptForeignKeysAndExternalIdUniqueness");
scratch.Scalar("SELECT COUNT(*) FROM sys.foreign_keys WHERE name IN ('FK_VirtualTag_Script', 'FK_ScriptedAlarm_Script')").ShouldBe(2);
scratch.Scalar("SELECT COUNT(*) FROM sys.indexes WHERE is_unique = 1 AND name IN ('UX_Equipment_ZTag', 'UX_Equipment_SAPID')").ShouldBe(2);
scratch.Scalar("SELECT OBJECT_ID(N'ExternalIdReservation')").ShouldBe(DBNull.Value);
scratch.Scalar("SELECT OBJECT_ID(N'dbo.sp_ReleaseExternalIdReservation')").ShouldBe(DBNull.Value);
scratch.Scalar("SELECT COUNT(*) FROM VirtualTag").ShouldBe(1);
// Down restores the previous shape (table, procedure, non-unique indexes) without touching the data.
Should.NotThrow(() => scratch.MigrateTo(Previous));
scratch.Scalar("SELECT COUNT(*) FROM sys.indexes WHERE is_unique = 0 AND name IN ('IX_Equipment_ZTag', 'IX_Equipment_SAPID')").ShouldBe(2);
scratch.Scalar("SELECT COUNT(*) FROM sys.foreign_keys WHERE name LIKE 'FK_%_Script'").ShouldBe(0);
scratch.Scalar("SELECT CASE WHEN OBJECT_ID(N'dbo.sp_ReleaseExternalIdReservation') IS NULL THEN 0 ELSE 1 END").ShouldBe(1);
scratch.Scalar("SELECT COUNT(*) FROM ExternalIdReservation").ShouldBe(0);
scratch.Scalar("SELECT COUNT(*) FROM Equipment").ShouldBe(6);
}
}