Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/Harness/SqlServerTestDatabase.cs
T
Joseph Doherty f7e7ba0263 fix(controlplane): audit writer drops only already-persisted EventIds, never the whole SQL Server batch
SQL Server's DbUpdateException for one duplicate names every entry in the statement batch, so detaching
ex.Entries dropped the whole flush. On a row-level rejection the writer now asks the database which of the
batch's EventIds it already holds, drops exactly those, re-saves the rest, and falls back to row-by-row only
if a non-duplicate row is still refused. Fresh context + entities per attempt. Pinned against the real
central SQL Server (new SqlServerTestDatabase harness) and a faithful whole-batch interceptor.

Refs #733
Claude-Session: https://claude.ai/code/session_01Ub9hGmYLQvn9XETzw7CMsT
2026-10-22 13:42:29 -04:00

78 lines
3.4 KiB
C#

using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using ZB.MOM.WW.OtOpcUa.Configuration;
namespace ZB.MOM.WW.OtOpcUa.ControlPlane.Tests.Harness;
/// <summary>
/// A migrated, throw-away config database on the central SQL Server, for the few ControlPlane behaviours
/// the InMemory provider cannot model (a SQL Server <c>DbUpdateException</c> names the WHOLE statement
/// batch; collation-ordered reads). Same server / credentials / env overrides as
/// <c>Configuration.Tests.SchemaComplianceFixture</c> (<c>OTOPCUA_CONFIG_TEST_SERVER</c>,
/// <c>OTOPCUA_CONFIG_TEST_SA_PASSWORD</c>; default the shared docker host's dev SA), and the same database
/// name shape, so that suite's 24 h orphan reaper also reclaims a database a killed run leaks here.
/// </summary>
public sealed class SqlServerTestDatabase : IDisposable
{
private const string DefaultServer = "10.100.0.35,14330";
private const string DefaultSaPassword = "OtOpcUaDev_2026!";
/// <summary>Gets the connection string of the migrated database.</summary>
public string ConnectionString { get; }
private readonly string _databaseName;
/// <summary>Creates and migrates the database.</summary>
public SqlServerTestDatabase()
{
var server = Environment.GetEnvironmentVariable("OTOPCUA_CONFIG_TEST_SERVER") ?? DefaultServer;
var saPassword = Environment.GetEnvironmentVariable("OTOPCUA_CONFIG_TEST_SA_PASSWORD") ?? DefaultSaPassword;
_databaseName = $"OtOpcUaConfig_Test_{DateTime.UtcNow:yyyyMMddHHmmss}_{Guid.NewGuid():N}";
ConnectionString =
$"Server={server};Database={_databaseName};User Id=sa;Password={saPassword};TrustServerCertificate=True;Encrypt=False;";
using var ctx = NewContext();
ctx.Database.Migrate();
}
/// <summary>A new context on the database.</summary>
/// <returns>The context.</returns>
public OtOpcUaConfigDbContext NewContext() =>
new(new DbContextOptionsBuilder<OtOpcUaConfigDbContext>().UseSqlServer(ConnectionString).Options);
/// <summary>A factory over <see cref="NewContext"/>.</summary>
/// <returns>The factory.</returns>
public IDbContextFactory<OtOpcUaConfigDbContext> Factory() => new ContextFactory(this);
/// <summary>Drops the database (best effort; a leak is reaped by the Configuration suite).</summary>
public void Dispose()
{
try
{
SqlConnection.ClearAllPools();
var master = new SqlConnectionStringBuilder(ConnectionString) { InitialCatalog = "master" }.ConnectionString;
using var conn = new SqlConnection(master);
conn.Open();
using var cmd = conn.CreateCommand();
cmd.CommandText = @"
DECLARE @sql nvarchar(max);
IF DB_ID(@name) IS NOT NULL
BEGIN
SET @sql = N'ALTER DATABASE ' + QUOTENAME(@name) + N' SET SINGLE_USER WITH ROLLBACK IMMEDIATE; ' +
N'DROP DATABASE ' + QUOTENAME(@name) + N';';
EXEC sp_executesql @sql;
END";
cmd.Parameters.Add(new SqlParameter("@name", _databaseName));
cmd.ExecuteNonQuery();
}
catch (Exception)
{
// Best effort — see the class remarks.
}
}
private sealed class ContextFactory(SqlServerTestDatabase owner) : IDbContextFactory<OtOpcUaConfigDbContext>
{
public OtOpcUaConfigDbContext CreateDbContext() => owner.NewContext();
}
}