feat(sql): opt-in writes — allowWrites + per-tag writable, single-row parameterised UPDATE (lmxopcua#753)
v2-ci / unit-tests (push) Waiting to run
v2-ci / unit-tests (push) Waiting to run
allowWrites is no longer inert: SqlDriver implements IWritable, default off. - Gates (outermost first): node Writable + WriteOperate (server), driver allowWrites, the tag's own TagConfig "writable": true (strict JSON boolean; anything else refuses the tag, and the deploy gate says why), and a model that names exactly one row — KeyValue, or WideRow by where-pair. topByTimestamp and Query are BadNotWritable. - SqlWritePlanner: the only statement a write can become is UPDATE <table> SET <value col> = @v WHERE <key col> = @k, built from the catalog-gate-canonical identifiers (dialect-quoted) with value and key bound; value-before-key marker order so positional ODBC binds correctly. No authored write SQL, INSERT, UPSERT or procedure. - Executed in a transaction that commits only when exactly one row was touched: 0 rows -> BadNoData (never inserts), >1 -> rolled back, BadConfigurationError, unknown count -> rolled back, BadNotSupported. Bounded by operationTimeout; provider errors -> BadCommunicationError; health untouched. - Discovery advertises Operate only where a write could succeed. - AdminUI: driver form's Allow writes switch is live; tag editor gains a per-tag write switch; model validates writable strictly (parity corpus). - Factory no longer warns "allowWrites ignored"; it logs whether writes are on. - Tests: SqlWriteTests (planner SQL/bind order/injection/coercion, every gate, readback, absent key, two-row rollback, gate-rejected tag, discovery); MySqlReadTests write legs against InnoDB (keyed row only, two-row rollback, server-side grant refusal, default-off). Seed adds a setpoints table and the one UPDATE grant. (lmxopcua#753) Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV
This commit is contained in:
+16
-2
@@ -6,8 +6,8 @@
|
||||
-- backends. Two things are load-bearing:
|
||||
--
|
||||
-- 1. The suite connects as `otopcua`, which holds SELECT on `sqlpoll` and nothing else (plus EXECUTE on the
|
||||
-- side-effect function, below). A MySQL "schema" is a database, and information_schema shows a principal
|
||||
-- only the objects it holds a privilege on — so MySqlDialect.ListSchemasSql returning `sqlpoll` for this
|
||||
-- side-effect function and UPDATE on the one write-target table, below). A MySQL "schema" is a database,
|
||||
-- and information_schema shows a principal only the objects it holds a privilege on — so MySqlDialect.ListSchemasSql returning `sqlpoll` for this
|
||||
-- login is the real provisioning check, not a superuser's view.
|
||||
-- 2. Every identifier is lower case. The suite authors the table name in UPPER case and expects the catalog
|
||||
-- gate to resolve it through a unique case-insensitive match: on Linux, MySQL table names are case-
|
||||
@@ -65,9 +65,23 @@ BEGIN
|
||||
END//
|
||||
DELIMITER ;
|
||||
|
||||
-- Write target (lmxopcua#753): the ONLY table the suite login may UPDATE. `dup` deliberately holds two rows
|
||||
-- for one key, so a write keyed on it matches two rows and must be rolled back. tag_values stays SELECT-only,
|
||||
-- so a write tag pointed there proves the server's own grant refuses it.
|
||||
CREATE TABLE setpoints (
|
||||
tag_name varchar(128) NOT NULL,
|
||||
sp_value double NULL
|
||||
) ENGINE = InnoDB;
|
||||
INSERT INTO setpoints (tag_name, sp_value) VALUES
|
||||
('Line1.SpeedSp', 10.0),
|
||||
('Line1.TempSp', 20.0),
|
||||
('dup', 1.0),
|
||||
('dup', 2.0);
|
||||
|
||||
-- ── the read-only login ──────────────────────────────────────────────────────────────────────
|
||||
DROP USER IF EXISTS 'otopcua'@'%';
|
||||
CREATE USER 'otopcua'@'%' IDENTIFIED BY '__APP_PASSWORD__';
|
||||
GRANT SELECT ON sqlpoll.* TO 'otopcua'@'%';
|
||||
GRANT EXECUTE ON FUNCTION sqlpoll.bump_counter TO 'otopcua'@'%';
|
||||
GRANT UPDATE ON sqlpoll.setpoints TO 'otopcua'@'%';
|
||||
FLUSH PRIVILEGES;
|
||||
|
||||
@@ -265,6 +265,88 @@ public sealed class MySqlReadTests
|
||||
(await _my.ScalarAsync("SELECT COUNT(*) FROM sqlpoll.side_effects")).ShouldBe(0L);
|
||||
}
|
||||
|
||||
// ---- writes (design §3.4) against a real server ----
|
||||
|
||||
/// <summary>All gates open: the UPDATE lands on exactly the keyed row, and the driver reads it back.</summary>
|
||||
[Fact]
|
||||
public async Task Write_realMySql_updatesTheKeyedRowOnly()
|
||||
{
|
||||
SkipUnlessLive();
|
||||
|
||||
await using var driver = await StartAsync(null, allowWrites: true,
|
||||
Setpoint("Sql/Sp/Speed", "Line1.SpeedSp", writable: true));
|
||||
var target = 10.0 + Random.Shared.Next(1, 1000);
|
||||
|
||||
(await WriteAsync(driver, "Sql/Sp/Speed", target)).ShouldBe(SqlStatusCodes.Good);
|
||||
|
||||
Convert.ToDouble(await _my.ScalarRawAsync("SELECT sp_value FROM sqlpoll.setpoints WHERE tag_name = 'Line1.SpeedSp'"),
|
||||
CultureInfo.InvariantCulture).ShouldBe(target);
|
||||
Convert.ToDouble(await _my.ScalarRawAsync("SELECT sp_value FROM sqlpoll.setpoints WHERE tag_name = 'Line1.TempSp'"),
|
||||
CultureInfo.InvariantCulture).ShouldBe(20.0);
|
||||
Convert.ToDouble((await driver.ReadAsync(["Sql/Sp/Speed"], TestContext.Current.CancellationToken))[0].Value,
|
||||
CultureInfo.InvariantCulture).ShouldBe(target);
|
||||
}
|
||||
|
||||
/// <summary>A key matching two rows is rolled back on InnoDB — neither row changes.</summary>
|
||||
[Fact]
|
||||
public async Task Write_realMySql_aKeyMatchingTwoRowsIsRolledBack()
|
||||
{
|
||||
SkipUnlessLive();
|
||||
|
||||
await using var driver = await StartAsync(null, allowWrites: true, Setpoint("Sql/Sp/Dup", "dup", writable: true));
|
||||
|
||||
(await WriteAsync(driver, "Sql/Sp/Dup", 99.0)).ShouldBe(SqlStatusCodes.BadConfigurationError);
|
||||
(await _my.ScalarAsync("SELECT COUNT(*) FROM sqlpoll.setpoints WHERE tag_name = 'dup' AND sp_value = 99")).ShouldBe(0L);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Defence in depth: with every driver gate open, a table the login holds no UPDATE on is refused by the
|
||||
/// server itself (the provider error surfaces as BadCommunicationError) and the row is unchanged.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Write_realMySql_aTableWithoutAnUpdateGrantIsRefusedByTheServer()
|
||||
{
|
||||
SkipUnlessLive();
|
||||
|
||||
await using var driver = await StartAsync(null, allowWrites: true, Tag("Sql/Kv/Speed", new JsonObject
|
||||
{
|
||||
["model"] = "KeyValue", ["table"] = MySqlFixture.Qualified("tag_values"), ["keyColumn"] = "tag_name",
|
||||
["keyValue"] = MySqlFixture.PresentKey, ["valueColumn"] = "num_value", ["writable"] = true,
|
||||
}));
|
||||
|
||||
(await WriteAsync(driver, "Sql/Kv/Speed", 1.0)).ShouldBe(SqlStatusCodes.BadCommunicationError);
|
||||
Convert.ToDouble(await _my.ScalarRawAsync("SELECT num_value FROM sqlpoll.tag_values WHERE tag_name = 'Line1.Speed'"),
|
||||
CultureInfo.InvariantCulture).ShouldBe(MySqlFixture.PresentValue);
|
||||
}
|
||||
|
||||
/// <summary>The default: no allowWrites ⇒ refused before any connection, whatever the tag says.</summary>
|
||||
[Fact]
|
||||
public async Task Write_realMySql_withoutAllowWritesIsRefused()
|
||||
{
|
||||
SkipUnlessLive();
|
||||
|
||||
await using var driver = await StartAsync(null, allowWrites: false, Setpoint("Sql/Sp/Temp", "Line1.TempSp", writable: true));
|
||||
|
||||
(await WriteAsync(driver, "Sql/Sp/Temp", 77.0)).ShouldBe(SqlStatusCodes.BadNotWritable);
|
||||
Convert.ToDouble(await _my.ScalarRawAsync("SELECT sp_value FROM sqlpoll.setpoints WHERE tag_name = 'Line1.TempSp'"),
|
||||
CultureInfo.InvariantCulture).ShouldBe(20.0);
|
||||
}
|
||||
|
||||
private static RawTagEntry Setpoint(string rawPath, string key, bool writable) => Tag(rawPath, new JsonObject
|
||||
{
|
||||
["model"] = "KeyValue",
|
||||
["table"] = MySqlFixture.Qualified("setpoints"),
|
||||
["keyColumn"] = "tag_name",
|
||||
["keyValue"] = key,
|
||||
["valueColumn"] = "sp_value",
|
||||
["type"] = "Float64",
|
||||
["writable"] = writable,
|
||||
});
|
||||
|
||||
private static async Task<uint> WriteAsync(SqlDriver driver, string reference, object? value)
|
||||
=> (await ((IWritable)driver).WriteAsync([new WriteRequest(reference, value)], TestContext.Current.CancellationToken))
|
||||
.ShouldHaveSingleItem().StatusCode;
|
||||
|
||||
// ---- helpers ----
|
||||
|
||||
private void SkipUnlessLive()
|
||||
@@ -274,13 +356,16 @@ public sealed class MySqlReadTests
|
||||
|
||||
private Task<SqlDriver> StartAsync(params RawTagEntry[] tags) => StartAsync(queriesJson: null, tags);
|
||||
|
||||
private Task<SqlDriver> StartAsync(string? queriesJson, params RawTagEntry[] tags)
|
||||
=> StartAsync(queriesJson, allowWrites: false, tags);
|
||||
|
||||
/// <summary>
|
||||
/// Builds and initializes a driver through the PRODUCTION factory (<c>provider: MySql</c>, the connection
|
||||
/// string resolved from the fixture's <c>connectionStringRef</c> environment variable), so the suite
|
||||
/// exercises <c>MySqlConnectorFactory.Instance</c> and the factory's own named-query validation exactly as a
|
||||
/// deployed config would.
|
||||
/// </summary>
|
||||
private async Task<SqlDriver> StartAsync(string? queriesJson, params RawTagEntry[] tags)
|
||||
private async Task<SqlDriver> StartAsync(string? queriesJson, bool allowWrites, params RawTagEntry[] tags)
|
||||
{
|
||||
var rawTags = new JsonArray();
|
||||
foreach (var tag in tags)
|
||||
@@ -302,6 +387,7 @@ public sealed class MySqlReadTests
|
||||
["rawTags"] = rawTags,
|
||||
};
|
||||
if (queriesJson is not null) config["queries"] = JsonNode.Parse(queriesJson);
|
||||
if (allowWrites) config["allowWrites"] = true;
|
||||
var json = config.ToJsonString();
|
||||
|
||||
var driver = SqlDriverFactoryExtensions.CreateInstance("sql-mysql-integration", json);
|
||||
@@ -433,6 +519,15 @@ public sealed class MySqlFixture : IAsyncLifetime
|
||||
/// <param name="sql">The statement.</param>
|
||||
/// <returns>The scalar, as a 64-bit integer when numeric.</returns>
|
||||
public async Task<object?> ScalarAsync(string sql)
|
||||
{
|
||||
var value = await ScalarRawAsync(sql).ConfigureAwait(false);
|
||||
return value is IConvertible and not string ? Convert.ToInt64(value, CultureInfo.InvariantCulture) : value;
|
||||
}
|
||||
|
||||
/// <summary>Runs a scalar query as the fixture login and returns the provider's value unconverted.</summary>
|
||||
/// <param name="sql">The statement.</param>
|
||||
/// <returns>The scalar.</returns>
|
||||
public async Task<object?> ScalarRawAsync(string sql)
|
||||
{
|
||||
var connection = new MySqlDialect().Factory.CreateConnection()
|
||||
?? throw new InvalidOperationException("MySqlConnector returned no connection object.");
|
||||
@@ -444,8 +539,7 @@ public sealed class MySqlFixture : IAsyncLifetime
|
||||
await using (command.ConfigureAwait(false))
|
||||
{
|
||||
command.CommandText = sql;
|
||||
var value = await command.ExecuteScalarAsync().ConfigureAwait(false);
|
||||
return value is IConvertible and not string ? Convert.ToInt64(value, CultureInfo.InvariantCulture) : value;
|
||||
return await command.ExecuteScalarAsync().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user