using System.Globalization; using System.Text.Json.Nodes; using Shouldly; using Xunit; using ZB.MOM.WW.OtOpcUa.Core.Abstractions; using ZB.MOM.WW.OtOpcUa.Driver.Sql.Contracts; namespace ZB.MOM.WW.OtOpcUa.Driver.Sql.IntegrationTests; /// /// lmxopcua#987 (review finding S-10): a table write's "exactly one row" commit rule against a SQL Server table /// whose AFTER INSERT/UPDATE trigger writes two audit rows per changed row and does not SET NOCOUNT ON. /// SqlClient's ExecuteNonQuery returns the SUM of every DML statement the command caused (1 + 2 = 3), so a /// driver trusting it rolled every such write back as "touched 3 rows". The dialect now reads the target /// statement's own @@ROWCOUNT. /// Positive controls: the audit rows exist (the trigger really fired inside the committed write), and an /// Update of an absent key is still BadNoData (the count is the target's, not a constant 1). /// [Collection(SqlPollServerCollection.Name)] public sealed class SqlServerTriggerWriteLiveTests(SqlPollServerFixture fixture) { [Theory] [InlineData("Update")] [InlineData("Upsert")] public async Task Write_toATableWithARowWritingTrigger_commitsTheOneTargetRow(string mode) { SkipUnlessLive(); var key = mode == "Update" ? "Present" : NewKey(); var value = 100.0 + Random.Shared.Next(1, 1000); await using var driver = await StartAsync(Target("Sp", key, mode)); (await WriteAsync(driver, "Sp", value)).ShouldBe(SqlStatusCodes.Good); Convert.ToDouble(await ScalarAsync( $"SELECT sp_value FROM [{SqlPollServerFixture.Schema}].[{SqlPollServerFixture.AuditedTable}] WHERE tag_name = N'{key}'"), CultureInfo.InvariantCulture).ShouldBe(value); Convert.ToInt32(await ScalarAsync( $"SELECT COUNT(*) FROM [{SqlPollServerFixture.Schema}].[{SqlPollServerFixture.AuditLogTable}] " + $"WHERE tag_name = N'{key}' AND sp_value = {value.ToString(CultureInfo.InvariantCulture)}"), CultureInfo.InvariantCulture).ShouldBe(2); } [Fact] public async Task Insert_intoATableWithARowWritingTrigger_commitsTheOneNewRow() { SkipUnlessLive(); var key = NewKey(); await using var driver = await StartAsync(Target("Sp", key, "Insert")); (await WriteAsync(driver, "Sp", 4.5)).ShouldBe(SqlStatusCodes.Good); Convert.ToInt32(await ScalarAsync( $"SELECT COUNT(*) FROM [{SqlPollServerFixture.Schema}].[{SqlPollServerFixture.AuditedTable}] WHERE tag_name = N'{key}'"), CultureInfo.InvariantCulture).ShouldBe(1); } [Fact] public async Task Update_ofAnAbsentKey_onATriggeredTable_isStillBadNoData() { SkipUnlessLive(); await using var driver = await StartAsync(Target("Sp", NewKey(), "Update")); (await WriteAsync(driver, "Sp", 1.0)).ShouldBe(SqlStatusCodes.BadNoData); } private void SkipUnlessLive() { if (fixture.SkipReason is { } reason) Assert.Skip(reason); } private static string NewKey() => "T-" + Guid.NewGuid().ToString("N")[..12]; private static RawTagEntry Target(string rawPath, string key, string mode) { var config = new JsonObject { ["driver"] = "Sql", ["model"] = "KeyValue", ["table"] = SqlPollServerFixture.Schema + "." + SqlPollServerFixture.AuditedTable, ["keyColumn"] = "tag_name", ["keyValue"] = key, ["valueColumn"] = "sp_value", ["type"] = "Float64", ["writable"] = true, ["write"] = new JsonObject { ["mode"] = mode }, }; return new RawTagEntry(rawPath, config.ToJsonString(), WriteIdempotent: false); } private async Task StartAsync(params RawTagEntry[] tags) { var driver = new SqlDriver( new SqlDriverOptions { RawTags = tags, CommandTimeout = TimeSpan.FromSeconds(30), OperationTimeout = TimeSpan.FromSeconds(45), AllowWrites = true, }, driverInstanceId: "sql-trigger-writes", dialect: new SqlServerDialect(), connectionString: fixture.ConnectionString); try { await driver.InitializeAsync("{}", TestContext.Current.CancellationToken); } catch { await driver.DisposeAsync(); throw; } return driver; } private static async Task WriteAsync(SqlDriver driver, string reference, object? value) => (await ((IWritable)driver).WriteAsync([new WriteRequest(reference, value)], TestContext.Current.CancellationToken)) .ShouldHaveSingleItem().StatusCode; private async Task ScalarAsync(string sql) { var connection = await fixture.OpenInspectionConnectionAsync(); await using (connection) { var command = connection.CreateCommand(); await using (command) { command.CommandText = sql; return await command.ExecuteScalarAsync(TestContext.Current.CancellationToken); } } } }