using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
namespace ZB.MOM.WW.OtOpcUa.Configuration.Tests;
///
/// A private, throw-away ConfigDb on the shared test SQL Server that a test migrates to a chosen migration
/// (not necessarily the latest), so a migration's pre-check can be exercised against data that the NEXT
/// migration must refuse. Named with so an orphan is
/// reclaimed by the fixture's reaper; dropped in .
///
internal sealed class MigrationScratchDatabase : IDisposable
{
private const string DefaultServer = "10.100.0.35,14330";
private const string DefaultSaPassword = "OtOpcUaDev_2026!";
/// Gets the database name.
public string DatabaseName { get; }
/// Gets the connection string to the scratch database.
public string ConnectionString { get; }
/// Creates the (empty) database; nothing is migrated until .
public MigrationScratchDatabase()
{
var server = Environment.GetEnvironmentVariable("OTOPCUA_CONFIG_TEST_SERVER") ?? DefaultServer;
var saPassword = Environment.GetEnvironmentVariable("OTOPCUA_CONFIG_TEST_SA_PASSWORD") ?? DefaultSaPassword;
DatabaseName = $"{SchemaComplianceFixture.TestDatabasePrefix}{DateTime.UtcNow:yyyyMMddHHmmss}_{Guid.NewGuid():N}";
ConnectionString =
$"Server={server};Database={DatabaseName};User Id=sa;Password={saPassword};TrustServerCertificate=True;Encrypt=False;";
}
/// Opens a context on the scratch database.
/// A new context.
public OtOpcUaConfigDbContext NewContext() =>
new(new DbContextOptionsBuilder().UseSqlServer(ConnectionString).Options);
/// Migrates (up) to , or to the latest when null.
/// The migration id or name to stop at.
public void MigrateTo(string? targetMigration = null)
{
using var db = NewContext();
db.GetService().Migrate(targetMigration);
}
/// The most recently applied migration id.
/// The id, or null when none is applied.
public string? LastAppliedMigration()
{
using var db = NewContext();
return db.Database.GetAppliedMigrations().LastOrDefault();
}
/// Runs one non-query statement.
/// The T-SQL.
public void Execute(string sql)
{
using var conn = new SqlConnection(ConnectionString);
conn.Open();
using var cmd = conn.CreateCommand();
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
/// Runs one scalar query.
/// The T-SQL.
/// The scalar.
public object? Scalar(string sql)
{
using var conn = new SqlConnection(ConnectionString);
conn.Open();
using var cmd = conn.CreateCommand();
cmd.CommandText = sql;
return cmd.ExecuteScalar();
}
///
public void Dispose()
{
SqlConnection.ClearAllPools();
var master = new SqlConnectionStringBuilder(ConnectionString) { InitialCatalog = "master" }.ConnectionString;
SqlTestDatabaseReaper.TryDropDatabase(master, DatabaseName);
}
}