Files
lmxopcua/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql/SqlWritePlanner.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

295 lines
15 KiB
C#

using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Driver.Sql.Contracts;
namespace ZB.MOM.WW.OtOpcUa.Driver.Sql;
/// <summary>
/// One compiled write (lmxopcua#753, #781): a parameterised statement whose identifiers are the tag's
/// catalog-validated ones and whose values are all bound.
/// </summary>
/// <param name="SqlText">The statement — dialect-quoted identifiers and parameter markers only.</param>
/// <param name="ParameterBindNames">
/// The distinct bind names, in first-marker order (a positional provider binds in this order, and only the modes
/// it supports — Update and Insert — are planned for it, where every marker appears exactly once).
/// </param>
/// <param name="Parameters">The bound values, aligned with <paramref name="ParameterBindNames"/>.</param>
/// <param name="Mode">The statement shape — decides how the executor reads the affected-row count.</param>
/// <param name="MaxRowsAffected">
/// The most rows the statement may report for a success: 1, or 2 for a MySQL upsert. Ignored for
/// <see cref="SqlWriteMode.Procedure"/>, whose row count is the procedure's business.
/// </param>
/// <param name="RowCountBindName">
/// When set, the bind name of an Int32 OUTPUT parameter the statement stores its own row count in
/// (<see cref="ISqlDialect.WriteRowCountCaptureSql"/>) — read instead of <c>ExecuteNonQuery</c>'s count, which on
/// SQL Server also counts trigger DML (lmxopcua#987). Not one of <paramref name="ParameterBindNames"/>.
/// </param>
public sealed record SqlWritePlan(
string SqlText,
IReadOnlyList<string> ParameterBindNames,
IReadOnlyList<object?> Parameters,
SqlWriteMode Mode = SqlWriteMode.Update,
int MaxRowsAffected = 1,
string? RowCountBindName = null);
/// <summary>
/// Turns one OPC UA write into one parameterised statement (design §3.4, lmxopcua#753 / #781 item 2) — pure, no
/// I/O. The tag's <c>write</c> block picks the shape; there is no authored write SQL:
/// <list type="bullet">
/// <item><see cref="SqlWriteMode.Update"/> (the default): <c>UPDATE t SET value [, stamp] WHERE key = @k</c>
/// on a KeyValue tag or a WideRow where-pair.</item>
/// <item><see cref="SqlWriteMode.Insert"/>: <c>INSERT INTO t (key, value [, stamp]) VALUES (…)</c> — no key
/// column for a WideRow <c>topByTimestamp</c> tag (an append).</item>
/// <item><see cref="SqlWriteMode.Upsert"/>: the dialect's single-statement upsert
/// (<see cref="ISqlDialect.UpsertSql"/>).</item>
/// <item><see cref="SqlWriteMode.Procedure"/>: the dialect's call of the catalog-validated procedure
/// (<see cref="ISqlDialect.ProcedureCallSql"/>) with the value, and optionally the key and write time, bound.</item>
/// </list>
/// <para><b>Injection boundary.</b> Every identifier is one the catalog gate resolved and substituted (the driver
/// plans writes only for gate-accepted definitions) and reaches the text through
/// <see cref="ISqlDialect.QuoteIdentifier"/>; procedure parameter names are restricted to a plain identifier
/// charset by the tag parser; the value, the key and the stamp are bound parameters. Nothing an OPC UA client
/// sends reaches the command text.</para>
/// </summary>
public static class SqlWritePlanner
{
private const string ValueBaseName = "v";
private const string KeyBaseName = "k";
private const string TimestampBaseName = "t";
private const string RowCountBaseName = "rc";
/// <summary>Plans a write of <paramref name="value"/> to <paramref name="tag"/>, stamping the current UTC time.</summary>
/// <param name="tag">The catalog-validated definition.</param>
/// <param name="value">The value the client wrote.</param>
/// <param name="dialect">Quoting, markers, bind names and the dialect-specific statements.</param>
/// <param name="plan">The plan, when this returns <see cref="SqlStatusCodes.Good"/>.</param>
/// <returns><see cref="SqlStatusCodes.Good"/>, or the status the write publishes.</returns>
public static uint TryPlan(SqlTagDefinition tag, object? value, ISqlDialect dialect, out SqlWritePlan? plan)
=> TryPlan(tag, value, dialect, DateTime.UtcNow, out plan);
/// <summary>
/// Plans a write of <paramref name="value"/> to <paramref name="tag"/>, or explains why it is refused.
/// <see cref="SqlStatusCodes.BadNotWritable"/>: the model has no target for the mode (a Query tag outside
/// Procedure, a <c>topByTimestamp</c> row for Update/Upsert). <see cref="SqlStatusCodes.BadNotSupported"/>: the
/// dialect does not serve the mode. <see cref="SqlStatusCodes.BadTypeMismatch"/>: the value will not coerce.
/// </summary>
/// <param name="tag">The catalog-validated definition.</param>
/// <param name="value">The value the client wrote.</param>
/// <param name="dialect">Quoting, markers, bind names and the dialect-specific statements.</param>
/// <param name="utcNow">The write time bound to a stamp column or <c>timestampParam</c> (UTC).</param>
/// <param name="plan">The plan, when this returns <see cref="SqlStatusCodes.Good"/>.</param>
/// <returns><see cref="SqlStatusCodes.Good"/>, or the status the write publishes.</returns>
public static uint TryPlan(
SqlTagDefinition tag, object? value, ISqlDialect dialect, DateTime utcNow, out SqlWritePlan? plan)
{
ArgumentNullException.ThrowIfNull(tag);
ArgumentNullException.ThrowIfNull(dialect);
plan = null;
var write = tag.EffectiveWrite;
if (!dialect.SupportsWriteMode(write.Mode)) return SqlStatusCodes.BadNotSupported;
if (!TryConvert(value, tag.DeclaredType, out var bound)) return SqlStatusCodes.BadTypeMismatch;
var stamp = DateTime.SpecifyKind(utcNow, DateTimeKind.Utc);
try
{
return write.Mode == SqlWriteMode.Procedure
? PlanProcedure(tag, write, bound, stamp, dialect, out plan)
: PlanTableWrite(tag, write, bound, stamp, dialect, out plan);
}
catch (ArgumentException)
{
// Unreachable for a gate-accepted definition (its identifiers came from the catalog); refuse rather
// than build a statement around a name the dialect would not quote.
plan = null;
return SqlStatusCodes.BadConfigurationError;
}
}
/// <summary>Update / Insert / Upsert against the tag's own table.</summary>
private static uint PlanTableWrite(
SqlTagDefinition tag, SqlWriteSpec write, object? bound, DateTime stamp, ISqlDialect dialect, out SqlWritePlan? plan)
{
plan = null;
string valueColumn;
string? keyColumn;
string? keyValue;
switch (tag.Model)
{
case SqlTagModel.KeyValue when !Blank(tag.ValueColumn) && !Blank(tag.KeyColumn) && tag.KeyValue is not null:
valueColumn = tag.ValueColumn!;
keyColumn = tag.KeyColumn!;
keyValue = tag.KeyValue;
break;
case SqlTagModel.WideRow when !Blank(tag.ColumnName) && !Blank(tag.RowSelectorColumn)
&& tag.RowSelectorValue is not null:
valueColumn = tag.ColumnName!;
keyColumn = tag.RowSelectorColumn!;
keyValue = tag.RowSelectorValue;
break;
// Newest-row selector: an Insert appends a row (no key); Update/Upsert have no row to aim at — "the
// newest row" moves under a concurrent insert.
case SqlTagModel.WideRow when write.Mode == SqlWriteMode.Insert && !Blank(tag.ColumnName):
valueColumn = tag.ColumnName!;
keyColumn = null;
keyValue = null;
break;
default:
return SqlStatusCodes.BadNotWritable;
}
var stampColumn = write.StampTimestamp ? SqlWriteSpecParser.StampColumn(tag) : null;
if (write.StampTimestamp && stampColumn is null) return SqlStatusCodes.BadConfigurationError;
var table = QuoteQualifiedName(tag.Table, dialect);
var valueMarker = dialect.ParameterMarker(ValueBaseName);
var keyMarker = dialect.ParameterMarker(KeyBaseName);
var stampMarker = dialect.ParameterMarker(TimestampBaseName);
// The value first, then the stamp: the order of the SET list and of the insert's non-key columns.
var assignments = new List<(string QuotedColumn, string Marker)> { (dialect.QuoteIdentifier(valueColumn), valueMarker) };
if (stampColumn is not null) assignments.Add((dialect.QuoteIdentifier(stampColumn), stampMarker));
var binds = new Binds(dialect);
string sql;
var maxRows = 1;
switch (write.Mode)
{
case SqlWriteMode.Update:
// Marker order: SET's value [and stamp], then WHERE's key — a positional provider binds in this order.
sql = string.Concat(
"UPDATE ", table,
" SET ", string.Join(", ", assignments.Select(a => a.QuotedColumn + " = " + a.Marker)),
" WHERE ", dialect.QuoteIdentifier(keyColumn!), " = ", keyMarker);
binds.Add(ValueBaseName, bound);
if (stampColumn is not null) binds.Add(TimestampBaseName, stamp);
binds.Add(KeyBaseName, keyValue);
break;
case SqlWriteMode.Insert:
{
var columns = new List<string>();
var markers = new List<string>();
if (keyColumn is not null)
{
columns.Add(dialect.QuoteIdentifier(keyColumn));
markers.Add(keyMarker);
binds.Add(KeyBaseName, keyValue);
}
columns.AddRange(assignments.Select(a => a.QuotedColumn));
markers.AddRange(assignments.Select(a => a.Marker));
binds.Add(ValueBaseName, bound);
if (stampColumn is not null) binds.Add(TimestampBaseName, stamp);
sql = string.Concat(
"INSERT INTO ", table, " (", string.Join(", ", columns), ") VALUES (", string.Join(", ", markers), ")");
break;
}
case SqlWriteMode.Upsert:
{
var upsert = dialect.UpsertSql(table, dialect.QuoteIdentifier(keyColumn!), keyMarker, assignments);
if (upsert is null) return SqlStatusCodes.BadNotSupported;
sql = upsert;
// A named-marker dialect (the only kind with an upsert) binds by name, so first-appearance order is
// documentation rather than load-bearing here.
binds.Add(KeyBaseName, keyValue);
binds.Add(ValueBaseName, bound);
if (stampColumn is not null) binds.Add(TimestampBaseName, stamp);
maxRows = Math.Max(1, dialect.UpsertMaxRowsAffected);
break;
}
default:
return SqlStatusCodes.BadNotWritable;
}
// The target statement's own row count, where the command-level one is polluted by trigger DML (#987).
string? rowCountBindName = null;
if (dialect.WriteRowCountCaptureSql(dialect.ParameterMarker(RowCountBaseName)) is { } capture)
{
sql = sql.TrimEnd().TrimEnd(';') + capture;
rowCountBindName = dialect.ParameterBindName(RowCountBaseName);
}
plan = new SqlWritePlan(sql, binds.Names, binds.Values, write.Mode, maxRows, rowCountBindName);
return SqlStatusCodes.Good;
}
/// <summary>A call of the tag's catalog-validated procedure: value, then key, then write time — each when bound.</summary>
private static uint PlanProcedure(
SqlTagDefinition tag, SqlWriteSpec write, object? bound, DateTime stamp, ISqlDialect dialect, out SqlWritePlan? plan)
{
plan = null;
if (Blank(write.Procedure)) return SqlStatusCodes.BadConfigurationError;
var binds = new Binds(dialect);
var arguments = new List<(string Parameter, string Marker)>
{
(write.ValueParameter ?? SqlWriteSpecParser.DefaultValueParameter, dialect.ParameterMarker(ValueBaseName)),
};
binds.Add(ValueBaseName, bound);
if (write.KeyParameter is { } keyParameter)
{
var key = SqlWriteSpecParser.KeyValue(tag);
if (key is null) return SqlStatusCodes.BadConfigurationError;
arguments.Add((keyParameter, dialect.ParameterMarker(KeyBaseName)));
binds.Add(KeyBaseName, key);
}
if (write.TimestampParameter is { } timestampParameter)
{
arguments.Add((timestampParameter, dialect.ParameterMarker(TimestampBaseName)));
binds.Add(TimestampBaseName, stamp);
}
var sql = dialect.ProcedureCallSql(QuoteQualifiedName(write.Procedure!, dialect), arguments);
if (sql is null) return SqlStatusCodes.BadNotSupported;
plan = new SqlWritePlan(sql, binds.Names, binds.Values, SqlWriteMode.Procedure);
return SqlStatusCodes.Good;
}
/// <summary>
/// Converts the client's value to what is bound: coerced to the tag's declared <c>type</c> when it has one
/// (the same coercion a read applies), otherwise passed through when it is a scalar a provider can bind.
/// A null writes SQL NULL.
/// </summary>
private static bool TryConvert(object? value, DriverDataType? declared, out object? bound)
{
bound = null;
if (value is null) return true;
if (declared is { } type) return SqlPollReader.TryCoerce(value, type, out bound);
if (value is string or bool or byte or sbyte or short or ushort or int or uint or long or ulong
or float or double or decimal or DateTime or DateTimeOffset or Guid)
{
bound = value is DateTime dt && dt.Kind == DateTimeKind.Local ? dt.ToUniversalTime() : value;
return true;
}
return false;
}
/// <summary>Quotes each part of a (catalog-canonical) <c>schema.name</c>.</summary>
private static string QuoteQualifiedName(string name, ISqlDialect dialect)
=> string.Join('.', name.Split('.').Select(dialect.QuoteIdentifier));
private static bool Blank(string? value) => string.IsNullOrWhiteSpace(value);
/// <summary>The ordered (bind name, value) list a plan carries.</summary>
private sealed class Binds(ISqlDialect dialect)
{
public List<string> Names { get; } = [];
public List<object?> Values { get; } = [];
public void Add(string baseName, object? value)
{
Names.Add(dialect.ParameterBindName(baseName));
Values.Add(value);
}
}
}