Files
lmxopcua/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql.Tests/SqlKeyAttributionTests.cs
T
Joseph Doherty 65c4330a68 fix(sql): #974 #987 named queries are lexed per dialect and run read-only + single-statement; key rows attribute by server semantics; SQL Server writes count only the target statement
#974 (S-7) — the named-query guard had one lexer for five dialects and took live SQL for literal text
where a provider ends a literal earlier (MySQL backslash escapes, PostgreSQL dollar quotes, T-SQL ]],
nested comments, MySQL # / "--x", bare-CR line comments, Oracle q'..'). All 13 bypass strings were
accepted; the MySQL and PostgreSQL ones were executed against the live fixtures and the smuggled
UPDATE committed past the always-rolled-back transaction.
- SqlReadOnlyStatement (own file) lexes per provider and REFUSES constructs dialects disagree on;
  Odbc / no provider = every dialect must agree. Factory and AdminUI form pass the provider; the form
  re-validates queries on a provider change.
- ISqlDialect.BeginNamedQueryAsync / SealNamedQueryCommand / EndNamedQueryAsync: PostgreSQL and Oracle
  SET TRANSACTION READ ONLY; MySQL read-only session + transaction (restored after); PostgreSQL rewrites
  @name markers to positional $n (a parameterless query gets one unused typed $1) so Npgsql sends the
  text unsplit and the server refuses a second statement.

#987 (S-6) — key-value rows are attributed by SqlKeyMatcher (exact, then typed / padding-insensitive,
then case/accent-insensitive — only for rows the server matched); a named query's rowKey uses the
exact + representational stages only.
#987 (S-10) — SQL Server table writes read the target statement's own @@ROWCOUNT through an OUTPUT
parameter; SqlClient's ExecuteNonQuery sums trigger DML (reproduced: 1 + 2 audit rows = 3, every write
rolled back BadConfigurationError).

Tests: per-dialect bypass theory + positive controls, matcher + SQLite collation/affinity attribution,
Postgres seal, dialect-hook wiring, SQL Server write-plan capture; live NamedQueryBypassLiveTests
(PG/MySQL/Oracle), SqlServerTriggerWriteLiveTests, MySQL writing-function now refused.
2026-12-03 10:33:45 -05:00

138 lines
6.8 KiB
C#

using System.Globalization;
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.Tests;
/// <summary>
/// lmxopcua#987 (review finding S-6): a key-value row the SERVER matched (<c>WHERE key IN (…)</c>, with the column's
/// type and collation) must be attributed back to its tag by the same semantics — before the fix the reader
/// re-compared the stringified cell ordinally, so a padded <c>CHAR</c> key, a case-insensitive collation or an
/// integer key authored <c>007</c> returned the row and published <c>BadNoData</c> forever. The SQLite legs use
/// SQLite's own <c>NOCASE</c> / <c>RTRIM</c> collations and integer affinity, so the database really does match
/// what the reader then has to attribute; the <see cref="SqlKeyMatcher"/> legs cover the CLR types SQLite cannot
/// return (Guid, decimal, float).
/// </summary>
public sealed class SqlKeyAttributionTests
{
// ---- end to end over SQLite: the server matched, the reader must attribute ----
[Theory]
[InlineData("TEXT COLLATE NOCASE", "'PUMP1'", "pump1")] // case-insensitive collation
[InlineData("TEXT COLLATE RTRIM", "'PUMP1 '", "PUMP1")] // fixed-width padding
[InlineData("INTEGER", "7", "007")] // integer key, leading-zero authoring
[InlineData("INTEGER", "7", "7.0")]
public async Task KeyValue_aRowTheServerMatched_isAttributedToItsTag(string keyType, string storedKey, string authored)
{
using var fixture = new SqlitePollFixture();
fixture.Execute($"CREATE TABLE Keys (k {keyType}, v REAL, ts TEXT)");
fixture.Execute($"INSERT INTO Keys VALUES ({storedKey}, 12.5, '2026-07-24T10:00:00Z')");
var reader = Reader(fixture, Kv("Tag", authored));
var snapshot = (await reader.ReadAsync(["Tag"], CancellationToken.None))[0];
snapshot.StatusCode.ShouldBe(SqlStatusCodes.Good);
Convert.ToDouble(snapshot.Value, CultureInfo.InvariantCulture).ShouldBe(12.5);
}
/// <summary>
/// The control that keeps the looser stages honest: on a case-SENSITIVE column two keys differing only in case
/// are two rows, and each tag must keep its own (exact match wins before any case folding).
/// </summary>
[Fact]
public async Task KeyValue_onACaseSensitiveColumn_keysDifferingInCase_stayDistinct()
{
using var fixture = new SqlitePollFixture();
fixture.Execute("CREATE TABLE Keys (k TEXT, v REAL, ts TEXT)");
fixture.Execute("INSERT INTO Keys VALUES ('pump1', 1.0, '2026-07-24T10:00:00Z'), ('PUMP1', 2.0, '2026-07-24T10:00:00Z')");
var reader = Reader(fixture, Kv("Lower", "pump1"), Kv("Upper", "PUMP1"), Kv("Mixed", "Pump1"));
var snapshots = await reader.ReadAsync(["Lower", "Upper", "Mixed"], CancellationToken.None);
Convert.ToDouble(snapshots[0].Value, CultureInfo.InvariantCulture).ShouldBe(1.0);
Convert.ToDouble(snapshots[1].Value, CultureInfo.InvariantCulture).ShouldBe(2.0);
snapshots[2].StatusCode.ShouldBe(SqlStatusCodes.BadNoData); // the server returned no row for "Pump1"
}
/// <summary>
/// A case-insensitive column holding 'PUMP1' and 'pump1': the server returns both for the key 'pump1', so the
/// selector IS ambiguous — the duplicate-key configuration error, not a silent pick of the exact spelling.
/// </summary>
[Fact]
public async Task KeyValue_onACaseInsensitiveColumn_twoRowsTheServerMatched_areAmbiguous()
{
using var fixture = new SqlitePollFixture();
fixture.Execute("CREATE TABLE Keys (k TEXT COLLATE NOCASE, v REAL, ts TEXT)");
fixture.Execute("INSERT INTO Keys VALUES ('pump1', 1.0, '2026-07-24T10:00:00Z'), ('PUMP1', 2.0, '2026-07-24T10:00:00Z')");
var reader = Reader(fixture, Kv("Tag", "pump1"));
(await reader.ReadAsync(["Tag"], CancellationToken.None))[0].StatusCode.ShouldBe(SqlStatusCodes.BadConfigurationError);
}
// ---- the matcher, over the CLR types providers return ----
[Fact]
public void Match_aGuidCell_matchesAnyCasingOfTheAuthoredGuid()
{
var guid = Guid.Parse("0f8fad5b-d9cb-469f-a165-70867728950e");
var matcher = new SqlKeyMatcher(["0F8FAD5B-D9CB-469F-A165-70867728950E"], collationStages: false);
matcher.Match(guid).ShouldBe(["0F8FAD5B-D9CB-469F-A165-70867728950E"]);
matcher.Match(Guid.NewGuid()).ShouldBeEmpty();
}
[Theory]
[InlineData(1.00, "1.0")]
[InlineData(7.0, "007")]
public void Match_aDecimalCell_comparesNumerically(double cell, string authored)
=> new SqlKeyMatcher([authored], collationStages: false).Match((decimal)cell).ShouldBe([authored]);
[Fact]
public void Match_aRealCell_comparesAtItsOwnPrecision()
=> new SqlKeyMatcher(["1.1"], collationStages: false).Match(1.1f).ShouldBe(["1.1"]);
[Fact]
public void Match_aBooleanCell_acceptsBitSpellings()
{
var matcher = new SqlKeyMatcher(["1", "false"], collationStages: false);
matcher.Match(true).ShouldBe(["1"]);
matcher.Match(false).ShouldBe(["false"]);
}
[Fact]
public void Match_collationStages_areOffForAClientSidePick()
{
new SqlKeyMatcher(["pump1"], collationStages: false).Match("PUMP1").ShouldBeEmpty();
new SqlKeyMatcher(["pump1"], collationStages: true).Match("PUMP1").ShouldBe(["pump1"]);
new SqlKeyMatcher(["PUMP1"], collationStages: false).Match("PUMP1 ").ShouldBe(["PUMP1"]); // padding is representational
}
[Fact]
public void Match_aRowEqualToSeveralKeysAtItsStage_isEachOfTheirs()
=> new SqlKeyMatcher(["pump1", "Pump1"], collationStages: true).Match("PUMP1").ShouldBe(["pump1", "Pump1"]);
[Fact]
public void Match_exactBeatsEveryLooserStage()
=> new SqlKeyMatcher(["pump1", "PUMP1"], collationStages: true).Match("PUMP1").ShouldBe(["PUMP1"]);
[Fact]
public void Match_aStringCellIsNeverComparedNumerically()
=> new SqlKeyMatcher(["7"], collationStages: true).Match("007").ShouldBeEmpty(); // a VARCHAR '007' is not '7'
// ---- helpers ----
private static SqlTagDefinition Kv(string name, string key)
=> new(name, SqlTagModel.KeyValue, "Keys", KeyColumn: "k", KeyValue: key, ValueColumn: "v",
DeclaredType: DriverDataType.Float64);
private static SqlPollReader Reader(SqlitePollFixture fixture, params SqlTagDefinition[] tags)
{
var table = tags.ToDictionary(t => t.Name, StringComparer.Ordinal);
return new SqlPollReader(fixture.Factory, fixture.ConnectionString, new SqliteDialect(),
commandTimeout: TimeSpan.FromSeconds(10), operationTimeout: TimeSpan.FromSeconds(15),
maxConcurrentGroups: 4, nullIsBad: false, resolve: rawPath => table.GetValueOrDefault(rawPath));
}
}