using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
using ZB.MOM.WW.OtOpcUa.ControlPlane.Preflight;
using ZB.MOM.WW.OtOpcUa.ControlPlane.Tests.Harness;
using ZB.MOM.WW.OtOpcUa.Core.Scripting;
namespace ZB.MOM.WW.OtOpcUa.ControlPlane.Tests;
///
/// lmxopcua#1013 / #1015 / #1021 / #1058: the read-only upgrade preflight against real SQL Server. A ConfigDb still
/// on an OLDER schema (pending migrations add tables and columns) is read through this build's model, and every row
/// a pending migration or the next deploy would refuse is named — with nothing written. Positive controls: a clean
/// database reports no blocking finding; a database that is not a v3 ConfigDb is refused, not guessed at.
///
[Trait("Category", "SchemaCompliance")]
public sealed class UpgradePreflightSqlServerTests
{
/// Before the gRPC data-connection tables, the #998 RowVersion columns and the #1040/#1049 constraints.
private const string OldSchema = "20261022102459_EnableSnapshotIsolation";
private static readonly RoslynDeployScriptChecker Checker = new();
private static async Task ExecAsync(SqlServerTestDatabase sql, string text)
{
await using var conn = new SqlConnection(sql.ConnectionString);
await conn.OpenAsync(TestContext.Current.CancellationToken);
await using var cmd = conn.CreateCommand();
cmd.CommandText = text;
await cmd.ExecuteNonQueryAsync(TestContext.Current.CancellationToken);
}
private static async Task RowCountAsync(SqlServerTestDatabase sql)
{
await using var conn = new SqlConnection(sql.ConnectionString);
await conn.OpenAsync(TestContext.Current.CancellationToken);
await using var cmd = conn.CreateCommand();
cmd.CommandText = "SELECT SUM(p.rows) FROM sys.partitions p JOIN sys.tables t ON t.object_id = p.object_id WHERE p.index_id IN (0, 1)";
return Convert.ToInt64(await cmd.ExecuteScalarAsync(TestContext.Current.CancellationToken));
}
private static Equipment NewEquipment(string lineId, string name, string? zTag)
{
var uuid = Guid.NewGuid();
return new Equipment
{
EquipmentId = "EQ-" + uuid.ToString("N")[..12], EquipmentUuid = uuid, UnsLineId = lineId, Name = name,
MachineCode = "mc-" + uuid.ToString("N"), ZTag = zTag,
};
}
///
/// Every class of finding on one old-schema database: the migration pre-checks (#1021), the new VirtualTag /
/// script-reference / ZTag gate rules (#1015), the Sql named-query rule (#1058) and the script compile gate (#1013).
///
[Fact]
public async Task An_old_schema_database_is_read_and_every_blocking_row_is_named_without_writing()
{
var ct = TestContext.Current.CancellationToken;
using var sql = new SqlServerTestDatabase(OldSchema);
// Rows the old schema allows and the new one refuses. ServerCluster / NodeAcl by SQL: this build's model has
// columns (RowVersion) the old tables do not.
await ExecAsync(sql, """
INSERT ServerCluster (ClusterId, Name, Enterprise, Site, NodeCount, RedundancyMode, Enabled, CreatedBy)
VALUES ('C1', 'Cluster one', 'zb', 's1', 1, 'None', 1, 't');
INSERT NodeAcl (NodeAclId, ClusterId, Principal, ScopeKind, ScopeId, PermissionFlags)
VALUES ('acl-1', 'C1', 'ops', 'Cluster', NULL, 1), ('acl-2', 'C1', 'ops', 'Cluster', NULL, 1);
INSERT ExternalIdReservation (Kind, Value, EquipmentUuid, ClusterId, FirstPublishedBy)
VALUES ('ZTag', 'ZT-OLD', NEWID(), 'C1', 't');
""");
await using (var db = sql.NewContext())
{
db.UnsAreas.Add(new UnsArea { UnsAreaId = "AREA-1", ClusterId = "C1", Name = "area" });
db.UnsLines.Add(new UnsLine { UnsLineId = "LINE-1", UnsAreaId = "AREA-1", Name = "line" });
var eq1 = NewEquipment("LINE-1", "press1", "ZT-1");
db.Equipment.AddRange(eq1, NewEquipment("LINE-1", "press2", "zt-1"));
db.Scripts.Add(new Script { ScriptId = "SC-ok", Name = "ok", SourceCode = "return 1;", SourceHash = new string('a', 64) });
db.Scripts.Add(new Script
{
ScriptId = "SC-file", Name = "reads a file", SourceHash = new string('b', 64),
SourceCode = "return System.IO.File.ReadAllText(\"c:/x\");",
});
db.VirtualTags.AddRange(
new VirtualTag { VirtualTagId = "VT-dangling", EquipmentId = eq1.EquipmentId, Name = "dangling", DataType = "Int32", ScriptId = "SC-gone" },
new VirtualTag { VirtualTagId = "VT-slash", EquipmentId = eq1.EquipmentId, Name = "a/b", DataType = "Int32", ScriptId = "SC-ok" },
new VirtualTag { VirtualTagId = "VT-file", EquipmentId = eq1.EquipmentId, Name = "file", DataType = "String", ScriptId = "SC-file" });
db.DriverInstances.Add(new DriverInstance
{
DriverInstanceId = "DRV-odbc", ClusterId = "C1", Name = "odbc", DriverType = "Sql",
DriverConfig = """{"provider":"Odbc","queries":{"line":{"sql":"SELECT v FROM t WHERE v ILIKE 'a%'"}}}""",
});
await db.SaveChangesAsync(ct);
}
var before = await RowCountAsync(sql);
var report = await UpgradePreflight.RunAsync(sql.ConnectionString, Checker, ct: ct);
report.PendingMigrations.ShouldContain(m => m.EndsWith("_ConfigurationGapsIndexesAndRowVersions", StringComparison.Ordinal));
report.PendingMigrations.ShouldContain(m => m.EndsWith("_ScriptForeignKeysAndExternalIdUniqueness", StringComparison.Ordinal));
report.Findings.ShouldContain(f => f.Check == "schema" && f.Code == "ReadAsEmpty" && f.Message.Contains("DataConnection"));
void Blocking(string check, string code, string text) =>
report.Findings.ShouldContain(f => f.Check == check && f.Code == code && f.Severity == PreflightSeverity.Blocking && f.Message.Contains(text),
$"expected {check}/{code} naming '{text}'");
// #1021: the migrations' own pre-checks, row-named.
Blocking("migration:ConfigurationGapsIndexesAndRowVersions", "DuplicateNodeAcl", "acl-1, acl-2");
Blocking("migration:ScriptForeignKeysAndExternalIdUniqueness", "VirtualTagScriptDangling", "VT-dangling");
Blocking("migration:ScriptForeignKeysAndExternalIdUniqueness", "DuplicateZTag", "ZT-1");
Blocking("migration:ScriptForeignKeysAndExternalIdUniqueness", "ExternalIdReservationRows", "ZT-OLD");
// #1015: the new deploy-gate rules.
Blocking("deploy-gate", "VirtualTagScriptNotFound", "VT-dangling");
Blocking("deploy-gate", "VirtualTagNameInvalid", "VT-slash");
Blocking("deploy-gate", "BadDuplicateExternalIdentifier", "ZT-1");
// #1058: an Odbc named query that does not parse as T-SQL.
Blocking("deploy-gate", "SqlNamedQueryInvalid", "DRV-odbc");
// #1013: the sandbox analyzer over the scripts in use.
Blocking("script-gate", "ScriptCompileFailed", "SC-file");
report.HasBlocking.ShouldBeTrue();
// Read-only: nothing written, no migration applied.
(await RowCountAsync(sql)).ShouldBe(before);
await using var verify = sql.NewContext();
verify.Database.GetAppliedMigrations().Last().ShouldBe(OldSchema);
}
/// Positive control: a clean, current database has no blocking finding; an unused broken script is a Warning only.
[Fact]
public async Task A_clean_current_database_has_no_blocking_finding()
{
var ct = TestContext.Current.CancellationToken;
using var sql = new SqlServerTestDatabase();
await using (var db = sql.NewContext())
{
db.Scripts.Add(new Script { ScriptId = "SC-unused", Name = "unused", SourceHash = new string('c', 64), SourceCode = "this is not C#" });
await db.SaveChangesAsync(ct);
}
var report = await UpgradePreflight.RunAsync(sql.ConnectionString, Checker, ct: ct);
report.PendingMigrations.ShouldBeEmpty();
report.HasBlocking.ShouldBeFalse(string.Join("\n", report.Findings.Select(f => $"{f.Check}/{f.Code}: {f.Message}")));
report.Findings.ShouldContain(f => f.Check == "deploy-gate" && f.Code == "Clean");
report.Findings.ShouldContain(f => f.Code == "UnusedScriptDoesNotCompile" && f.Severity == PreflightSeverity.Warning && f.Subject == "SC-unused");
}
/// Positive control for the migration pre-checks: an old schema with clean data reports each pending check Clean.
[Fact]
public async Task An_old_schema_database_with_clean_data_reports_the_migrations_will_apply()
{
using var sql = new SqlServerTestDatabase(OldSchema);
var report = await UpgradePreflight.RunAsync(sql.ConnectionString, Checker, ct: TestContext.Current.CancellationToken);
report.HasBlocking.ShouldBeFalse(string.Join("\n", report.Findings.Select(f => $"{f.Check}/{f.Code}: {f.Message}")));
report.Findings.Count(f => f.Check.StartsWith("migration:", StringComparison.Ordinal) && f.Code == "Clean").ShouldBe(2);
}
///
/// A NULL Script.ScriptId (legal in the old schema) is named by the migration pre-check, and the snapshot
/// this build cannot read is reported as Blocking instead of crashing the tool.
///
[Fact]
public async Task A_null_script_id_is_named_and_the_unreadable_snapshot_is_reported()
{
using var sql = new SqlServerTestDatabase(OldSchema);
await ExecAsync(sql, "INSERT Script (ScriptId, Name, SourceCode, SourceHash, Language) VALUES (NULL, 'orphan', 'return 1;', 'h', 'CSharp')");
var report = await UpgradePreflight.RunAsync(sql.ConnectionString, Checker, ct: TestContext.Current.CancellationToken);
report.Findings.ShouldContain(f => f.Code == "ScriptIdNull" && f.Severity == PreflightSeverity.Blocking && f.Message.Contains("orphan"));
report.Findings.ShouldContain(f => f.Code == "SnapshotUnreadable" && f.Severity == PreflightSeverity.Blocking);
report.HasBlocking.ShouldBeTrue();
}
/// A database without the v3 migration history is refused, never checked against the wrong model.
[Fact]
public async Task A_database_that_is_not_a_v3_ConfigDb_is_refused()
{
using var sql = new SqlServerTestDatabase("0"); // created, nothing applied
var ex = await Should.ThrowAsync(() =>
UpgradePreflight.RunAsync(sql.ConnectionString, Checker, ct: TestContext.Current.CancellationToken));
ex.Message.ShouldContain("is not a v3 OtOpcUa ConfigDb");
}
}