Merge #974 + #987: dialect-aware Sql read-only guard + read-only execution (13 bypasses closed), provider-semantics key matching, trigger-safe SQL Server rowcount

This commit is contained in:
Joseph Doherty
2026-12-03 10:34:08 -05:00
26 changed files with 2067 additions and 298 deletions
@@ -1,4 +1,3 @@
using System.Text;
using System.Text.Json;
namespace ZB.MOM.WW.OtOpcUa.Driver.Sql.Contracts;
@@ -16,7 +15,7 @@ public sealed class SqlNamedQueryDto
/// The statement — exactly one <c>SELECT</c> or <c>WITH … SELECT</c>. Parameter markers are written in
/// the provider's own spelling for each <see cref="Params"/> key (<c>@name</c> on SqlServer, Postgres
/// and MySql; <c>:p_name</c> on Oracle; positional <c>?</c> on Odbc, in authored order). Checked by
/// <see cref="SqlReadOnlyStatement.Check"/>.
/// <see cref="SqlReadOnlyStatement.Check(string?, SqlProvider?, out string)"/>.
/// </summary>
public string? Sql { get; init; }
@@ -62,21 +61,26 @@ public static class SqlNamedQueryRules
}
/// <summary>
/// Validates one named query's provider-independent shape — name, statement, parameter names and
/// values, row ceiling — and returns the first problem, or <see langword="null"/> when it is usable.
/// The runtime factory and the AdminUI driver form both call this, so what the form accepts is what
/// the driver constructs. (The factory additionally checks each parameter's marker appears in the
/// Validates one named query's shape — name, statement, parameter names and values, row ceiling — and
/// returns the first problem, or <see langword="null"/> when it is usable. The runtime factory and the
/// AdminUI driver form both call this with the driver's provider, so what the form accepts is what the
/// driver constructs. (The factory additionally checks each parameter's marker appears in the
/// statement, which needs the provider's dialect.)
/// <para><paramref name="provider"/> selects the dialect the statement is lexed as
/// (<see cref="SqlReadOnlyStatement.Check(string?, SqlProvider?, out string)"/>). Null — or
/// <see cref="SqlProvider.Odbc"/>, whose backend is unknown — demands that every supported dialect read
/// it identically.</para>
/// </summary>
/// <param name="name">The <c>queries</c> key.</param>
/// <param name="query">The entry.</param>
/// <param name="provider">The driver's provider, or null when unknown.</param>
/// <returns>An operator-facing error, or null.</returns>
public static string? Describe(string name, SqlNamedQueryDto? query)
public static string? Describe(string name, SqlNamedQueryDto? query, SqlProvider? provider = null)
{
if (string.IsNullOrWhiteSpace(name)) return "a named query has a blank name";
if (query is null) return $"named query '{name}' is null";
var statement = SqlReadOnlyStatement.Check(query.Sql, out _);
var statement = SqlReadOnlyStatement.Check(query.Sql, provider, out _);
if (statement is not null) return $"named query '{name}': {statement}";
if (query.MaxRows is { } maxRows && (maxRows < 1 || maxRows > MaxMaxRows))
@@ -102,209 +106,3 @@ public static class SqlNamedQueryRules
return null;
}
}
/// <summary>
/// The authoring-time read-only guard for a named query's SQL (design §5.4). It is a <b>guard, not the
/// boundary</b>: the driver also runs every named query inside a transaction it always rolls back, and the
/// connecting principal should hold <c>SELECT</c> only. The guard exists so an operator learns at
/// construction — not from a database audit — that a statement is not a plain read.
/// <para>Rules, applied to the text <em>outside</em> string literals, quoted identifiers and comments:
/// the statement begins with <c>SELECT</c> or <c>WITH</c>; it is a single statement (one trailing
/// <c>;</c> is tolerated and removed); and none of the data- or schema-changing keywords appears anywhere
/// — which also refuses <c>SELECT … INTO</c>, <c>FOR UPDATE</c> and a data-modifying CTE.</para>
/// </summary>
public static class SqlReadOnlyStatement
{
/// <summary>
/// Keywords that may not appear outside literals/comments in a named query. Statement-only keywords
/// (<c>COMMIT</c>, <c>BEGIN</c>, …) are not listed: the single-statement + <c>SELECT</c>-first rules
/// already exclude them, and listing them would refuse a column that merely shares the name. A column
/// named like a listed keyword can still be read by quoting it.
/// </summary>
private static readonly HashSet<string> Forbidden = new(StringComparer.OrdinalIgnoreCase)
{
"INSERT", "UPDATE", "DELETE", "MERGE", "UPSERT", "DROP", "ALTER", "CREATE", "TRUNCATE",
"EXEC", "EXECUTE", "CALL", "GRANT", "REVOKE", "DENY", "INTO", "COPY", "LOCK", "RENAME",
};
/// <summary>
/// Checks <paramref name="sql"/> and returns the problem, or <see langword="null"/> when it is a single
/// read-only statement. On success <paramref name="normalised"/> is the statement with surrounding
/// whitespace and one trailing <c>;</c> removed (ODP.NET refuses a trailing terminator).
/// </summary>
/// <param name="sql">The authored statement.</param>
/// <param name="normalised">The statement to execute, when valid.</param>
/// <returns>An operator-facing error, or null.</returns>
public static string? Check(string? sql, out string normalised)
{
normalised = string.Empty;
if (string.IsNullOrWhiteSpace(sql)) return "the statement is empty";
var words = new List<string>();
var terminatorAt = -1;
var i = 0;
while (i < sql.Length)
{
var ch = sql[i];
var next = i + 1 < sql.Length ? sql[i + 1] : '\0';
if (ch == '-' && next == '-')
{
while (i < sql.Length && sql[i] != '\n') i++;
continue;
}
if (ch == '/' && next == '*')
{
var end = sql.IndexOf("*/", i + 2, StringComparison.Ordinal);
if (end < 0) return "the statement has an unterminated /* comment";
i = end + 2;
continue;
}
if (ch is '\'' or '"' or '`' or '[')
{
var close = ch == '[' ? ']' : ch;
var j = i + 1;
while (true)
{
if (j >= sql.Length) return "the statement has an unterminated quoted literal or identifier";
if (sql[j] == close)
{
// A doubled closing character is an escaped one inside the literal.
if (j + 1 < sql.Length && sql[j + 1] == close && close != ']') { j += 2; continue; }
break;
}
j++;
}
if (terminatorAt >= 0) return "the statement carries more than one statement (text after ';')";
i = j + 1;
continue;
}
if (ch == ';')
{
if (terminatorAt >= 0) return "the statement carries more than one statement (';' repeated)";
terminatorAt = i;
i++;
continue;
}
if (char.IsLetter(ch) || ch == '_')
{
var start = i;
while (i < sql.Length && (char.IsLetterOrDigit(sql[i]) || sql[i] is '_' or '$' or '#')) i++;
if (terminatorAt >= 0) return "the statement carries more than one statement (text after ';')";
words.Add(sql[start..i]);
continue;
}
if (!char.IsWhiteSpace(ch) && terminatorAt >= 0)
return "the statement carries more than one statement (text after ';')";
i++;
}
if (words.Count == 0) return "the statement is empty";
if (!words[0].Equals("SELECT", StringComparison.OrdinalIgnoreCase)
&& !words[0].Equals("WITH", StringComparison.OrdinalIgnoreCase))
return "a named query must be a single SELECT (or WITH … SELECT) statement";
foreach (var word in words)
{
if (Forbidden.Contains(word))
return $"a named query must be read-only, and '{word.ToUpperInvariant()}' is not allowed outside a " +
"string literal or comment";
}
var body = terminatorAt >= 0 ? sql[..terminatorAt] : sql;
normalised = body.Trim();
return null;
}
/// <summary>The marker a positional provider (ODBC) spells every parameter with.</summary>
public const string PositionalMarker = "?";
/// <summary>Counts the positional <c>?</c> markers outside literals and comments.</summary>
/// <param name="sql">The statement.</param>
/// <returns>The marker count.</returns>
public static int CountPositionalMarkers(string sql)
{
ArgumentNullException.ThrowIfNull(sql);
return StripLiteralsAndComments(sql).Count(ch => ch == '?');
}
/// <summary>
/// True when <paramref name="marker"/> appears in <paramref name="sql"/> as a parameter token — outside
/// literals and comments, and not as the prefix of a longer name (<c>@line</c> inside <c>@lineId</c>).
/// </summary>
/// <param name="sql">The statement.</param>
/// <param name="marker">The provider marker, e.g. <c>@line</c> or <c>:p_line</c>.</param>
/// <returns>True when the marker is used.</returns>
public static bool UsesMarker(string sql, string marker)
{
ArgumentNullException.ThrowIfNull(sql);
ArgumentException.ThrowIfNullOrEmpty(marker);
var code = StripLiteralsAndComments(sql);
var from = 0;
while (true)
{
var at = code.IndexOf(marker, from, StringComparison.OrdinalIgnoreCase);
if (at < 0) return false;
var after = at + marker.Length;
if (after >= code.Length || !(char.IsLetterOrDigit(code[after]) || code[after] == '_')) return true;
from = after;
}
}
/// <summary>Replaces literal, quoted-identifier and comment content with spaces, keeping offsets.</summary>
private static string StripLiteralsAndComments(string sql)
{
var builder = new StringBuilder(sql);
var i = 0;
while (i < sql.Length)
{
var ch = sql[i];
var next = i + 1 < sql.Length ? sql[i + 1] : '\0';
int end;
if (ch == '-' && next == '-')
{
end = sql.IndexOf('\n', i);
end = end < 0 ? sql.Length : end;
}
else if (ch == '/' && next == '*')
{
end = sql.IndexOf("*/", i + 2, StringComparison.Ordinal);
end = end < 0 ? sql.Length : end + 2;
}
else if (ch is '\'' or '"' or '`' or '[')
{
var close = ch == '[' ? ']' : ch;
end = i + 1;
while (end < sql.Length)
{
if (sql[end] == close)
{
if (end + 1 < sql.Length && sql[end + 1] == close && close != ']') { end += 2; continue; }
end++;
break;
}
end++;
}
}
else
{
i++;
continue;
}
for (var k = i; k < end; k++) builder[k] = ' ';
i = end;
}
return builder.ToString();
}
}
@@ -0,0 +1,470 @@
using System.Text;
namespace ZB.MOM.WW.OtOpcUa.Driver.Sql.Contracts;
/// <summary>
/// The authoring-time read-only guard for a named query's SQL (design §5.4). It is a <b>guard, not the
/// boundary</b>: the driver also runs every named query inside a transaction it always rolls back — read-only,
/// and single-statement, where the provider can enforce that (see <c>ISqlDialect.BeginNamedQueryAsync</c>) —
/// and the connecting principal should hold <c>SELECT</c> only. The guard exists so an operator learns at
/// construction — not from a database audit — that a statement is not a plain read.
/// <para>Rules, applied to the text <em>outside</em> string literals, quoted identifiers and comments:
/// the statement begins with <c>SELECT</c> or <c>WITH</c>; it is a single statement (one trailing
/// <c>;</c> is tolerated and removed); and none of the data- or schema-changing keywords appears anywhere
/// — which also refuses <c>SELECT … INTO</c>, <c>FOR UPDATE</c> and a data-modifying CTE.</para>
/// <para><b>The lexer is dialect-aware, and refuses what it cannot read exactly as the server does
/// (lmxopcua#974, review finding S-7).</b> Everything above depends on knowing where a literal or comment ends.
/// One lexer for five dialects got that wrong in the direction that matters — it took live SQL for literal
/// text — so <c>SELECT '\'' ; COMMIT; DELETE …</c> (MySQL backslash escape) and
/// <c>SELECT $$'$$; COMMIT; DROP …</c> (PostgreSQL dollar quote) passed as one harmless <c>SELECT</c>, and
/// the embedded <c>COMMIT</c> ended the rolled-back transaction before the write. Each provider now has its
/// own lexicon (which characters quote, which escapes exist, which comments exist), and the constructs on which
/// dialects disagree are <b>refused</b> rather than modelled: a backslash inside a MySQL / PostgreSQL literal,
/// a PostgreSQL dollar quote, Oracle <c>q'…'</c> quoting, MySQL <c>/*! … */</c> executable comments, a nested
/// <c>/* /* */</c> comment (SQL Server and PostgreSQL nest, the others do not), MySQL's <c>--</c> without a
/// following space, and a line comment ended by a bare carriage return. A statement whose provider is unknown
/// (<see cref="SqlProvider.Odbc"/>, or no provider at all) must lex identically under every dialect.</para>
/// </summary>
public static class SqlReadOnlyStatement
{
/// <summary>
/// Keywords that may not appear outside literals/comments in a named query. Statement-only keywords
/// (<c>COMMIT</c>, <c>BEGIN</c>, …) are not listed: the single-statement + <c>SELECT</c>-first rules
/// already exclude them, and listing them would refuse a column that merely shares the name. A column
/// named like a listed keyword can still be read by quoting it.
/// </summary>
private static readonly HashSet<string> Forbidden = new(StringComparer.OrdinalIgnoreCase)
{
"INSERT", "UPDATE", "DELETE", "MERGE", "UPSERT", "DROP", "ALTER", "CREATE", "TRUNCATE",
"EXEC", "EXECUTE", "CALL", "GRANT", "REVOKE", "DENY", "INTO", "COPY", "LOCK", "RENAME",
};
/// <summary>What a masked literal's characters become: not whitespace, not an identifier character.</summary>
private const char LiteralMask = '\u0001';
/// <summary>The marker a positional provider (ODBC) spells every parameter with.</summary>
public const string PositionalMarker = "?";
/// <summary>
/// One dialect's lexical rules — only the ones that decide where a literal, quoted identifier or comment
/// ends. Anything a dialect reads differently from the others is either modelled exactly here or refused.
/// </summary>
private sealed record Lexicon(
SqlProvider Provider,
bool BracketIdentifiers,
bool BacktickIdentifiers,
bool HashComments,
bool DashDashNeedsSpace,
bool BackslashInSingleQuotes,
bool BackslashInDoubleQuotes,
bool DollarQuotes,
bool AlternativeQuoting,
string ExtraIdentifierChars);
// T-SQL: [ident] with ]] escaping, "ident" (or a string under QUOTED_IDENTIFIER OFF — same boundaries), and
// identifiers may carry @ $ #. No backslash escapes.
private static readonly Lexicon SqlServer = new(
SqlProvider.SqlServer, BracketIdentifiers: true, BacktickIdentifiers: false, HashComments: false,
DashDashNeedsSpace: false, BackslashInSingleQuotes: false, BackslashInDoubleQuotes: false,
DollarQuotes: false, AlternativeQuoting: false, ExtraIdentifierChars: "@$#");
// PostgreSQL: E'…' strings (and any string under standard_conforming_strings = off) take backslash escapes;
// $$…$$ / $tag$…$tag$ dollar quoting; $ continues an identifier; [ and ` are operator/subscript characters.
private static readonly Lexicon Postgres = new(
SqlProvider.Postgres, BracketIdentifiers: false, BacktickIdentifiers: false, HashComments: false,
DashDashNeedsSpace: false, BackslashInSingleQuotes: true, BackslashInDoubleQuotes: false,
DollarQuotes: true, AlternativeQuoting: false, ExtraIdentifierChars: "$");
// MySQL / MariaDB: '…' and "…" are strings with backslash escapes (unless NO_BACKSLASH_ESCAPES — refusing the
// backslash makes the mode irrelevant), `ident` is the identifier quote, # starts a line comment, and -- is a
// comment only when followed by whitespace.
private static readonly Lexicon MySql = new(
SqlProvider.MySql, BracketIdentifiers: false, BacktickIdentifiers: true, HashComments: true,
DashDashNeedsSpace: true, BackslashInSingleQuotes: true, BackslashInDoubleQuotes: true,
DollarQuotes: false, AlternativeQuoting: false, ExtraIdentifierChars: "$");
// Oracle: q'[…]' alternative quoting ends at a delimiter + quote, not at the next quote; $ and # continue an
// identifier. ODP.NET also refuses more than one statement per command.
private static readonly Lexicon Oracle = new(
SqlProvider.Oracle, BracketIdentifiers: false, BacktickIdentifiers: false, HashComments: false,
DashDashNeedsSpace: false, BackslashInSingleQuotes: false, BackslashInDoubleQuotes: false,
DollarQuotes: false, AlternativeQuoting: true, ExtraIdentifierChars: "$#");
private static readonly Lexicon[] EveryDialect = [SqlServer, Postgres, MySql, Oracle];
/// <summary>The lexicons a statement must satisfy: its provider's own, or every one when the backend is unknown.</summary>
private static Lexicon[] LexiconsFor(SqlProvider? provider) => provider switch
{
SqlProvider.SqlServer => [SqlServer],
SqlProvider.Postgres => [Postgres],
SqlProvider.MySql => [MySql],
SqlProvider.Oracle => [Oracle],
_ => EveryDialect,
};
/// <summary>
/// Checks <paramref name="sql"/> as every supported dialect reads it — the provider-independent form, used
/// when the backend is unknown. See <see cref="Check(string?, SqlProvider?, out string)"/>.
/// </summary>
/// <param name="sql">The authored statement.</param>
/// <param name="normalised">The statement to execute, when valid.</param>
/// <returns>An operator-facing error, or null.</returns>
public static string? Check(string? sql, out string normalised) => Check(sql, null, out normalised);
/// <summary>
/// Checks <paramref name="sql"/> and returns the problem, or <see langword="null"/> when it is a single
/// read-only statement as <paramref name="provider"/> lexes it. On success <paramref name="normalised"/> is
/// the statement with surrounding whitespace and one trailing <c>;</c> removed (ODP.NET refuses a trailing
/// terminator). A null provider, or <see cref="SqlProvider.Odbc"/>, requires every supported dialect to
/// accept the statement and agree on where it ends.
/// </summary>
/// <param name="sql">The authored statement.</param>
/// <param name="provider">The provider the statement runs on, or null when unknown.</param>
/// <param name="normalised">The statement to execute, when valid.</param>
/// <returns>An operator-facing error, or null.</returns>
public static string? Check(string? sql, SqlProvider? provider, out string normalised)
{
normalised = string.Empty;
if (string.IsNullOrWhiteSpace(sql)) return "the statement is empty";
var lexicons = LexiconsFor(provider);
string? agreed = null;
foreach (var lexicon in lexicons)
{
if (CheckAs(sql, lexicon, out var one) is { } problem)
{
return lexicons.Length == 1
? problem
: $"{problem} (as {lexicon.Provider} reads it — {DescribeUnknownBackend(provider)} must read the " +
"same under every supported dialect)";
}
if (agreed is null) agreed = one;
else if (!string.Equals(agreed, one, StringComparison.Ordinal))
return $"the statement ends in a different place under different SQL dialects, and {DescribeUnknownBackend(provider)} " +
"must read the same under every one";
}
normalised = agreed!;
return null;
}
private static string DescribeUnknownBackend(SqlProvider? provider) => provider == SqlProvider.Odbc
? "an Odbc driver's backend is unknown, so its statement"
: "a statement checked without a provider";
/// <summary>The single-dialect check behind <see cref="Check(string?, SqlProvider?, out string)"/>.</summary>
private static string? CheckAs(string sql, Lexicon lexicon, out string normalised)
{
normalised = string.Empty;
if (Mask(sql, lexicon, out var code) is { } lexProblem) return lexProblem;
var words = new List<string>();
var terminatorAt = -1;
var i = 0;
while (i < code.Length)
{
var ch = code[i];
if (ch == ';')
{
if (terminatorAt >= 0) return "the statement carries more than one statement (';' repeated)";
terminatorAt = i;
i++;
continue;
}
if (IsIdentifierStart(ch))
{
var start = i;
i++;
while (i < code.Length && IsIdentifierPart(code[i], lexicon)) i++;
if (terminatorAt >= 0) return "the statement carries more than one statement (text after ';')";
words.Add(code[start..i]);
continue;
}
if (!char.IsWhiteSpace(ch) && terminatorAt >= 0)
return "the statement carries more than one statement (text after ';')";
i++;
}
if (words.Count == 0) return "the statement is empty";
if (!words[0].Equals("SELECT", StringComparison.OrdinalIgnoreCase)
&& !words[0].Equals("WITH", StringComparison.OrdinalIgnoreCase))
return "a named query must be a single SELECT (or WITH … SELECT) statement";
foreach (var word in words)
{
if (Forbidden.Contains(word))
return $"a named query must be read-only, and '{word.ToUpperInvariant()}' is not allowed outside a " +
"string literal or comment";
}
var body = terminatorAt >= 0 ? sql[..terminatorAt] : sql;
normalised = body.Trim();
return null;
}
/// <summary>
/// Counts the positional <c>?</c> markers outside literals and comments, under every dialect (the only
/// positional provider is ODBC, whose backend is unknown). Returns <c>-1</c> when the dialects disagree or
/// one cannot lex the statement — never the case for a statement <see cref="Check(string?, out string)"/>
/// accepted.
/// </summary>
/// <param name="sql">The statement.</param>
/// <returns>The marker count, or -1.</returns>
public static int CountPositionalMarkers(string sql) => CountPositionalMarkers(sql, null);
/// <summary>Counts the positional <c>?</c> markers as <paramref name="provider"/> lexes the statement (-1: unlexable / disagreement).</summary>
/// <param name="sql">The statement.</param>
/// <param name="provider">The provider, or null when unknown.</param>
/// <returns>The marker count, or -1.</returns>
public static int CountPositionalMarkers(string sql, SqlProvider? provider)
{
ArgumentNullException.ThrowIfNull(sql);
var count = -1;
foreach (var lexicon in LexiconsFor(provider))
{
if (Mask(sql, lexicon, out var code) is not null) return -1;
var one = code.Count(ch => ch == '?');
if (count >= 0 && count != one) return -1;
count = one;
}
return count;
}
/// <summary>
/// True when <paramref name="marker"/> appears in <paramref name="sql"/> as a parameter token under every
/// supported dialect — outside literals and comments, and not as the prefix of a longer name
/// (<c>@line</c> inside <c>@lineId</c>).
/// </summary>
/// <param name="sql">The statement.</param>
/// <param name="marker">The provider marker, e.g. <c>@line</c> or <c>:p_line</c>.</param>
/// <returns>True when the marker is used.</returns>
public static bool UsesMarker(string sql, string marker) => UsesMarker(sql, marker, null);
/// <summary>
/// True when <paramref name="marker"/> appears in <paramref name="sql"/> as a parameter token as
/// <paramref name="provider"/> lexes it (every dialect, when null).
/// </summary>
/// <param name="sql">The statement.</param>
/// <param name="marker">The provider marker, e.g. <c>@line</c> or <c>:p_line</c>.</param>
/// <param name="provider">The provider, or null when unknown.</param>
/// <returns>True when the marker is used.</returns>
public static bool UsesMarker(string sql, string marker, SqlProvider? provider)
{
ArgumentNullException.ThrowIfNull(sql);
ArgumentException.ThrowIfNullOrEmpty(marker);
foreach (var lexicon in LexiconsFor(provider))
{
if (Mask(sql, lexicon, out var code) is not null) return false;
if (MarkerPositions(code, marker).Count == 0) return false;
}
return true;
}
/// <summary>
/// Rewrites every parameter token of <paramref name="markers"/> (outside literals and comments, as
/// <paramref name="provider"/> lexes the statement) to the replacement at the same index, matching exactly
/// as <see cref="UsesMarker(string, string, SqlProvider?)"/> does. Text inside literals and comments is
/// copied unchanged.
/// </summary>
/// <param name="sql">The statement — one <see cref="Check(string?, SqlProvider?, out string)"/> accepted.</param>
/// <param name="provider">The provider whose lexicon decides what is code.</param>
/// <param name="markers">The markers to replace, e.g. <c>@line</c>.</param>
/// <param name="replacements">What each marker becomes, e.g. <c>$1</c>.</param>
/// <returns>The rewritten statement.</returns>
/// <exception cref="InvalidOperationException">The statement cannot be lexed as <paramref name="provider"/>.</exception>
public static string ReplaceMarkers(
string sql, SqlProvider provider, IReadOnlyList<string> markers, IReadOnlyList<string> replacements)
{
ArgumentNullException.ThrowIfNull(sql);
ArgumentNullException.ThrowIfNull(markers);
ArgumentNullException.ThrowIfNull(replacements);
if (markers.Count != replacements.Count)
throw new ArgumentException("every marker needs exactly one replacement", nameof(replacements));
var lexicons = LexiconsFor(provider);
if (lexicons.Length != 1)
throw new ArgumentException($"{provider} has no single lexicon to rewrite markers under", nameof(provider));
if (Mask(sql, lexicons[0], out var code) is { } problem)
throw new InvalidOperationException($"the statement cannot be lexed as {provider}: {problem}");
// Every (position, length, replacement); a position claimed by a longer marker is not re-claimed by a
// shorter one (the "not followed by an identifier character" rule already keeps @line out of @lineId).
var edits = new SortedDictionary<int, (int Length, string With)>();
for (var m = 0; m < markers.Count; m++)
{
ArgumentException.ThrowIfNullOrEmpty(markers[m]);
foreach (var at in MarkerPositions(code, markers[m]))
{
if (!edits.TryGetValue(at, out var existing) || existing.Length < markers[m].Length)
edits[at] = (markers[m].Length, replacements[m]);
}
}
var builder = new StringBuilder(sql.Length);
var copied = 0;
foreach (var (at, (length, with)) in edits)
{
if (at < copied) continue;
builder.Append(sql, copied, at - copied).Append(with);
copied = at + length;
}
return builder.Append(sql, copied, sql.Length - copied).ToString();
}
/// <summary>Where <paramref name="marker"/> occurs in masked code as a whole parameter token.</summary>
private static List<int> MarkerPositions(string code, string marker)
{
var positions = new List<int>();
var from = 0;
while (true)
{
var at = code.IndexOf(marker, from, StringComparison.OrdinalIgnoreCase);
if (at < 0) return positions;
var after = at + marker.Length;
if (after >= code.Length || !(char.IsLetterOrDigit(code[after]) || code[after] == '_')) positions.Add(at);
from = after;
}
}
private static bool IsIdentifierStart(char ch) => char.IsLetter(ch) || ch == '_';
private static bool IsIdentifierPart(char ch, Lexicon lexicon)
=> char.IsLetterOrDigit(ch) || ch == '_' || lexicon.ExtraIdentifierChars.Contains(ch);
/// <summary>
/// Lexes <paramref name="sql"/> as <paramref name="lexicon"/>'s dialect and returns it with every comment
/// blanked to spaces and every literal / quoted identifier to <see cref="LiteralMask"/> (offsets kept) —
/// or the problem when the dialect reads a construct the guard will not model.
/// </summary>
private static string? Mask(string sql, Lexicon lexicon, out string code)
{
code = string.Empty;
var builder = new StringBuilder(sql);
var i = 0;
while (i < sql.Length)
{
var ch = sql[i];
var next = i + 1 < sql.Length ? sql[i + 1] : '\0';
if ((ch == '-' && next == '-') || (ch == '#' && lexicon.HashComments))
{
if (ch == '-' && lexicon.DashDashNeedsSpace && i + 2 < sql.Length
&& !char.IsWhiteSpace(sql[i + 2]) && !char.IsControl(sql[i + 2]))
{
return "'--' must be followed by a space to be a comment on MySQL (it is two minus signs " +
"otherwise, and a comment everywhere else); add the space";
}
var end = i;
while (end < sql.Length && sql[end] is not ('\n' or '\r')) end++;
if (end < sql.Length && sql[end] == '\r' && (end + 1 >= sql.Length || sql[end + 1] != '\n'))
{
return "a line comment ends in a carriage return without a line feed, and dialects disagree on " +
"whether that ends it; use a line feed";
}
Blank(builder, i, end, ' ');
i = end;
continue;
}
if (ch == '/' && next == '*')
{
if (i + 2 < sql.Length && (sql[i + 2] == '!'
|| (sql[i + 2] is 'M' or 'm' && i + 3 < sql.Length && sql[i + 3] == '!')))
{
return "an executable comment (/*! … */ or /*M! … */) is code on MySQL/MariaDB and a comment " +
"elsewhere, so it is not allowed in a named query";
}
var end = sql.IndexOf("*/", i + 2, StringComparison.Ordinal);
if (end < 0) return "the statement has an unterminated /* comment";
if (sql.IndexOf("/*", i + 2, end - (i + 2), StringComparison.Ordinal) >= 0)
{
return "a /* comment contains another '/*'; SQL Server and PostgreSQL nest comments and other " +
"dialects do not, so where it ends is ambiguous";
}
Blank(builder, i, end + 2, ' ');
i = end + 2;
continue;
}
if (ch is '\'' or '"' || (ch == '`' && lexicon.BacktickIdentifiers) || (ch == '[' && lexicon.BracketIdentifiers))
{
if (ch == '\'' && lexicon.AlternativeQuoting && i > 0 && sql[i - 1] is 'q' or 'Q')
{
return "Oracle alternative quoting (q'…') ends at its own delimiter, not at the next quote, so it " +
"is not allowed in a named query; use an ordinary '…' literal";
}
var close = ch == '[' ? ']' : ch;
var backslashEscapes = (ch == '\'' && lexicon.BackslashInSingleQuotes)
|| (ch == '"' && lexicon.BackslashInDoubleQuotes);
var j = i + 1;
while (true)
{
if (j >= sql.Length) return "the statement has an unterminated quoted literal or identifier";
if (backslashEscapes && sql[j] == '\\')
{
return $"a backslash inside a quoted literal is an escape character on {lexicon.Provider} " +
"(and plain text elsewhere), so where the literal ends is ambiguous; remove it " +
"(spell it CHR(92) / CHAR(92) if the value needs one)";
}
if (sql[j] == close)
{
// A doubled closing character is an escaped one — including T-SQL's ]] inside [ … ].
if (j + 1 < sql.Length && sql[j + 1] == close) { j += 2; continue; }
break;
}
j++;
}
Blank(builder, i, j + 1, LiteralMask);
i = j + 1;
continue;
}
if (ch == '$' && lexicon.DollarQuotes)
{
// Reached only OUTSIDE an identifier (an identifier consumes its own '$' below). $1 is a
// positional parameter; anything else opens a dollar-quoted string.
if (char.IsAsciiDigit(next))
{
i++;
while (i < sql.Length && char.IsAsciiDigit(sql[i])) i++;
continue;
}
return "a dollar-quoted string ($$…$$ or $tag$…$tag$) is not allowed in a named query; use an " +
"ordinary '…' literal";
}
if (IsIdentifierStart(ch))
{
i++;
while (i < sql.Length && IsIdentifierPart(sql[i], lexicon)) i++;
continue;
}
i++;
}
code = builder.ToString();
return null;
}
private static void Blank(StringBuilder builder, int from, int to, char with)
{
for (var k = from; k < to; k++) builder[k] = with;
}
}
@@ -244,6 +244,45 @@ public interface ISqlDialect
/// <returns>The mapped driver data type, or <see cref="DriverDataType.String"/> when unrecognised.</returns>
DriverDataType MapColumnType(string sqlDataType);
// ---- named queries (lmxopcua#974) ----
/// <summary>
/// Opens the transaction an operator-authored named query (<see cref="SqlTagModel.Query"/>) runs in. The
/// caller <b>always rolls it back</b> and then calls <see cref="EndNamedQueryAsync"/>. A dialect makes it
/// <b>read-only</b> where its provider can, so the lexical guard (<c>SqlReadOnlyStatement</c>) is not the
/// only defence: PostgreSQL and Oracle <c>SET TRANSACTION READ ONLY</c>, MySQL a read-only session as well
/// as a read-only transaction (a smuggled <c>COMMIT</c> ends a transaction, not a session). The default —
/// SQL Server, Odbc — is a plain transaction, which still discards a transactional side effect.
/// <para>Must tolerate any <see cref="DbConnection"/> (a substituted factory): a dialect that needs its own
/// provider type falls back to the default for anything else.</para>
/// </summary>
/// <param name="connection">The open connection.</param>
/// <param name="cancellationToken">The poll's deadline.</param>
/// <returns>The transaction the named query's command joins.</returns>
ValueTask<DbTransaction> BeginNamedQueryAsync(DbConnection connection, CancellationToken cancellationToken)
=> connection.BeginTransactionAsync(cancellationToken);
/// <summary>
/// Last step before a named query's command executes — its text, transaction and parameters are all set.
/// A dialect whose provider can refuse a <b>second statement</b> at the protocol level does that here:
/// PostgreSQL rewrites the <c>@name</c> markers to positional <c>$n</c>, which makes Npgsql send the text
/// unsplit as one extended-protocol statement, so the server itself refuses anything after a <c>;</c>.
/// The default does nothing. Same any-command tolerance as <see cref="ConfigureCommand"/>.
/// </summary>
/// <param name="command">The named query's command.</param>
void SealNamedQueryCommand(DbCommand command)
{
}
/// <summary>
/// Undoes any <b>session</b> state <see cref="BeginNamedQueryAsync"/> set, after the transaction was rolled
/// back, so a pooled connection is not handed to a write still read-only. Best effort: the caller swallows a
/// provider failure (the connection is being returned anyway). The default does nothing.
/// </summary>
/// <param name="connection">The connection the named query ran on.</param>
/// <returns>A task that completes when the session is restored.</returns>
ValueTask EndNamedQueryAsync(DbConnection connection) => ValueTask.CompletedTask;
// ---- writes (lmxopcua#781 item 2) ----
/// <summary>
@@ -270,6 +309,19 @@ public interface ISqlDialect
string quotedTable, string quotedKeyColumn, string keyMarker,
IReadOnlyList<(string QuotedColumn, string Marker)> assignments) => null;
/// <summary>
/// A statement appended to a table write (Update / Insert / Upsert) that stores the <b>target statement's
/// own</b> row count in the output parameter spelled <paramref name="outputMarker"/> — or null (the default)
/// to trust <see cref="DbCommand.ExecuteNonQuery"/>'s count. SQL Server needs it (lmxopcua#987): SqlClient's
/// count is the SUM over every DML statement the command caused, trigger DML included, so a single-row
/// UPDATE on a table whose audit trigger inserts a history row reported 2 and the one-row rule rolled it back.
/// <c>@@ROWCOUNT</c> read right after the statement is the statement's own count (live-verified). PostgreSQL,
/// MySQL and Oracle report the target statement only.
/// </summary>
/// <param name="outputMarker">The marker of the Int32 output parameter the executor binds.</param>
/// <returns>The suffix (including its leading separator), or null.</returns>
string? WriteRowCountCaptureSql(string outputMarker) => null;
/// <summary>
/// The most rows an upsert may report touching for one key. 1 everywhere except MySQL, whose
/// <c>ON DUPLICATE KEY UPDATE</c> reports 2 for "updated an existing row".
@@ -47,6 +47,55 @@ public sealed class MySqlDialect : ISqlDialect
// MySQL compares a string bind against a numeric column by converting, so an authored "7" matches an INT
// key column with no per-parameter typing (unlike Npgsql). The interface default (no-op) is right.
/// <inheritdoc />
// A read-only SESSION as well as a read-only transaction (#974). MySqlConnector always negotiates
// multi-statement support and splits even a prepared command, so a statement smuggled past the guard
// (`SELECT '\'' ; COMMIT; UPDATE …`) reaches the server as three statements; the COMMIT ends a read-only
// TRANSACTION and the UPDATE would autocommit. With the session read-only every transaction after that COMMIT is
// read-only too, so the UPDATE/DDL fails ("Cannot execute statement in a READ ONLY transaction") — live-verified
// against the fixture. It is defence in depth, not a boundary: hidden text could change the session back, so the
// guard and a SELECT-only principal remain the controls. EndNamedQueryAsync restores the session.
public async ValueTask<DbTransaction> BeginNamedQueryAsync(DbConnection connection, CancellationToken cancellationToken)
{
if (connection is not MySqlConnection mySql)
return await connection.BeginTransactionAsync(cancellationToken).ConfigureAwait(false);
var command = mySql.CreateCommand();
await using (command.ConfigureAwait(false))
{
command.CommandText = "SET SESSION TRANSACTION READ ONLY";
await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false);
}
try
{
return await mySql.BeginTransactionAsync(System.Data.IsolationLevel.Unspecified, isReadOnly: true, cancellationToken)
.ConfigureAwait(false);
}
catch
{
// No transaction ⇒ the caller never reaches EndNamedQueryAsync; restore the session here.
try { await EndNamedQueryAsync(mySql).ConfigureAwait(false); }
catch (Exception ex) when (ex is DbException or InvalidOperationException) { /* the pool reset covers it */ }
throw;
}
}
/// <inheritdoc />
// Back to the server's own default (not a hard-coded READ WRITE: a replica may default to read-only). The pool's
// ConnectionReset would also clear it, but a connection string may turn that off.
public async ValueTask EndNamedQueryAsync(DbConnection connection)
{
if (connection is not MySqlConnection mySql || mySql.State != System.Data.ConnectionState.Open) return;
var command = mySql.CreateCommand();
await using (command.ConfigureAwait(false))
{
command.CommandText = "SET @@SESSION.transaction_read_only = DEFAULT";
await command.ExecuteNonQueryAsync(CancellationToken.None).ConfigureAwait(false);
}
}
// 65535 — the prepared-statement protocol carries the parameter count in two bytes. MySqlConnector
// substitutes parameters client-side for unprepared commands and so has no lower ceiling of its own.
/// <inheritdoc />
@@ -94,6 +94,33 @@ public sealed class OracleDialect : ISqlDialect
if (command is OracleCommand oracle) oracle.BindByName = true;
}
/// <inheritdoc />
// SET TRANSACTION READ ONLY must be the transaction's first statement; ODP.NET's BeginTransaction sends nothing at
// the default isolation level, so it is (live-verified against the fixture, repeatedly on one connection, #974).
// A function that writes then fails (ORA-01456) instead of writing and being rolled back. ODP.NET already refuses
// a second statement in one command (ORA-03405), so there is no seal to add.
public async ValueTask<DbTransaction> BeginNamedQueryAsync(DbConnection connection, CancellationToken cancellationToken)
{
var transaction = await connection.BeginTransactionAsync(cancellationToken).ConfigureAwait(false);
try
{
var command = connection.CreateCommand();
await using (command.ConfigureAwait(false))
{
command.Transaction = transaction;
command.CommandText = "SET TRANSACTION READ ONLY";
await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false);
}
return transaction;
}
catch
{
await transaction.DisposeAsync().ConfigureAwait(false);
throw;
}
}
/// <inheritdoc />
// 1000 — the tightest of the three ceilings, and the one that actually binds. Oracle allows
// 64k bind variables per statement, but an IN expression list is limited to 1000
@@ -66,6 +66,66 @@ public sealed class PostgresDialect : ISqlDialect
npgsql.NpgsqlDbType = NpgsqlTypes.NpgsqlDbType.Unknown;
}
/// <inheritdoc />
// SET TRANSACTION READ ONLY as the transaction's first statement: a function or data-modifying construct the
// guard cannot see fails ("cannot execute … in a read-only transaction") instead of writing and being rolled
// back — and a non-transactional effect (nextval) is refused rather than leaking. It does NOT stop a smuggled
// second statement after a COMMIT; SealNamedQueryCommand does (live-verified against the fixture, #974).
public async ValueTask<DbTransaction> BeginNamedQueryAsync(DbConnection connection, CancellationToken cancellationToken)
{
var transaction = await connection.BeginTransactionAsync(cancellationToken).ConfigureAwait(false);
try
{
var command = connection.CreateCommand();
await using (command.ConfigureAwait(false))
{
command.Transaction = transaction;
command.CommandText = "SET TRANSACTION READ ONLY";
await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false);
}
return transaction;
}
catch
{
await transaction.DisposeAsync().ConfigureAwait(false);
throw;
}
}
/// <inheritdoc />
// The protocol-level single-statement seal. With NAMED parameters (or none) Npgsql parses the text itself and
// splits it on ';' into a batch — so `SELECT $$'$$; COMMIT; UPDATE …` ran all three statements and the UPDATE
// committed (reproduced live, #974). With POSITIONAL parameters Npgsql sends the text unparsed as ONE
// extended-protocol Parse, and PostgreSQL refuses a second command in it ("cannot insert multiple commands into
// a prepared statement") — whatever any lexer thinks. So: rewrite each @name marker to $n (as this dialect's
// lexicon reads the text — the same one the guard accepted it under), clear the parameter names, and give a
// parameterless statement one unused, explicitly typed positional parameter (a declared-but-unreferenced
// parameter is legal) so it also takes the unparsed path.
public void SealNamedQueryCommand(DbCommand command)
{
if (command is not NpgsqlCommand npgsql) return;
var parameters = npgsql.Parameters;
if (parameters.Count == 0)
{
parameters.Add(new NpgsqlParameter { Value = 0, NpgsqlDbType = NpgsqlTypes.NpgsqlDbType.Integer });
return;
}
var markers = new string[parameters.Count];
var positions = new string[parameters.Count];
for (var i = 0; i < parameters.Count; i++)
{
markers[i] = ParameterMarker(parameters[i].ParameterName.TrimStart('@', ':'));
positions[i] = "$" + (i + 1).ToString(CultureInfo.InvariantCulture);
}
npgsql.CommandText = SqlReadOnlyStatement.ReplaceMarkers(
npgsql.CommandText, SqlProvider.Postgres, markers, positions);
foreach (NpgsqlParameter parameter in parameters) parameter.ParameterName = string.Empty;
}
// 65535 - the extended-query protocol carries the parameter count as a signed/unsigned 16-bit field
// in Bind, so that is a protocol ceiling rather than a server setting, and Npgsql raises it
// client-side before a round-trip. Far above anything a poll group reaches in practice; it is here
@@ -225,6 +225,13 @@ public sealed class SqlServerDialect : ISqlDialect
// ---- writes (lmxopcua#781 item 2) ----
/// <inheritdoc />
// @@ROWCOUNT immediately after the write is that statement's own count: a trigger's DML does not leak into it
// (live-verified, #987), whereas ExecuteNonQuery sums every DONE token the batch produced — trigger statements
// without SET NOCOUNT ON included. An OUTPUT parameter rather than a trailing SELECT, so a trigger that returns a
// result set cannot be mistaken for the count.
public string? WriteRowCountCaptureSql(string outputMarker) => "; SET " + outputMarker + " = @@ROWCOUNT;";
/// <inheritdoc />
// MERGE … WITH (HOLDLOCK): the key-range lock HOLDLOCK takes is what makes the matched/not-matched decision and
// the insert one atomic step under concurrency — a bare MERGE (or UPDATE-then-INSERT) can race two writers into a
@@ -1,5 +1,7 @@
using System.Data;
using System.Data.Common;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using ZB.MOM.WW.OtOpcUa.Commons.Observability;
@@ -751,7 +753,27 @@ public sealed class SqlDriver
command.Parameters.Add(parameter);
}
DbParameter? rowCount = null;
if (plan.RowCountBindName is { } rowCountName)
{
rowCount = command.CreateParameter();
rowCount.ParameterName = rowCountName;
rowCount.DbType = DbType.Int32;
rowCount.Direction = ParameterDirection.Output;
command.Parameters.Add(rowCount);
}
rows = await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false);
// The target statement's own count when the dialect captured it (#987): ExecuteNonQuery's also
// counts trigger DML on SQL Server. A capture that came back empty is not trusted as success —
// -1 falls through to the rollback below.
if (rowCount is not null)
{
rows = rowCount.Value is null or DBNull
? -1
: Convert.ToInt32(rowCount.Value, CultureInfo.InvariantCulture);
}
}
if (plan.Mode == SqlWriteMode.Procedure || (rows >= 1 && rows <= plan.MaxRowsAffected))
@@ -285,10 +285,10 @@ public static class SqlDriverFactoryExtensions
foreach (var (name, query) in authored)
{
if (SqlNamedQueryRules.Describe(name, query) is { } problem)
if (SqlNamedQueryRules.Describe(name, query, dialect?.Provider) is { } problem)
throw new InvalidOperationException($"Sql driver config for '{driverInstanceId}': {problem}.");
SqlReadOnlyStatement.Check(query.Sql, out var sql);
SqlReadOnlyStatement.Check(query.Sql, dialect?.Provider, out var sql);
var names = new List<string>();
var values = new List<object?>();
foreach (var (key, value) in query.Params ?? [])
@@ -297,7 +297,7 @@ public static class SqlDriverFactoryExtensions
if (dialect is not null)
{
var marker = dialect.ParameterMarker(bare);
if (marker != SqlReadOnlyStatement.PositionalMarker && !SqlReadOnlyStatement.UsesMarker(sql, marker))
if (marker != SqlReadOnlyStatement.PositionalMarker && !SqlReadOnlyStatement.UsesMarker(sql, marker, dialect.Provider))
{
throw new InvalidOperationException(
$"Sql driver config for '{driverInstanceId}': named query '{name}' declares parameter " +
@@ -313,11 +313,11 @@ public static class SqlDriverFactoryExtensions
// matters: one '?' too few binds every later value to the wrong marker.
if (dialect is not null
&& dialect.ParameterMarker("p") == SqlReadOnlyStatement.PositionalMarker
&& SqlReadOnlyStatement.CountPositionalMarkers(sql) != names.Count)
&& SqlReadOnlyStatement.CountPositionalMarkers(sql, dialect.Provider) != names.Count)
{
throw new InvalidOperationException(
$"Sql driver config for '{driverInstanceId}': named query '{name}' declares {names.Count} " +
$"parameter(s), but its statement has {SqlReadOnlyStatement.CountPositionalMarkers(sql)} " +
$"parameter(s), but its statement has {SqlReadOnlyStatement.CountPositionalMarkers(sql, dialect.Provider)} " +
$"positional '?' marker(s); {dialect.Provider} binds them in authored order, so the two must match.");
}
@@ -0,0 +1,202 @@
using System.Globalization;
namespace ZB.MOM.WW.OtOpcUa.Driver.Sql;
/// <summary>
/// Attributes a result row's key cell back to the authored key text it answers (lmxopcua#987, review finding S-6).
/// <para><b>Why an ordinal string compare was wrong.</b> The key-value plan selects rows with
/// <c>WHERE key IN (@k0, …)</c>, so the <em>server</em> decides equality — with the column's type and collation.
/// The reader then re-matched each row to a tag by comparing <c>Convert.ToString(cell)</c> to the authored text
/// ordinally. Wherever the database considers two values equal that are not byte-identical strings — a
/// <c>CHAR(10)</c> key padded to <c>"PUMP1 "</c>, a case-insensitive collation (SQL Server's and MySQL's
/// defaults), a <c>uniqueidentifier</c> that .NET prints lower-case, an <c>INT</c> key authored <c>007</c>, a
/// decimal <c>1.0</c> vs <c>1.00</c> — the row came back and was attributed to no tag, which published
/// <c>BadNoData</c> forever while health stayed Healthy.</para>
/// <para><b>The rule: exact first, then the loosest stage that matches anything.</b> Per row:</para>
/// <list type="number">
/// <item><b>Exact</b> — the stringified cell equals an authored key ordinally. Always wins: on a
/// case-sensitive database two keys differing only in case are distinct rows, and must stay distinct.</item>
/// <item><b>Representational</b> — the same value in another spelling: a typed compare for Guid, integral,
/// decimal, floating and boolean cells (<c>"007"</c> = 7, <c>"1.0"</c> = 1.00, any Guid casing), and
/// trailing-space-insensitive for text (fixed-width <c>CHAR</c> padding; SQL Server, MySQL PAD SPACE and
/// PostgreSQL <c>bpchar</c> all compare that way).</item>
/// <item><b>Collation</b> (key-value only) — case-insensitive, then also accent/width/kana-insensitive. Safe
/// only because the server already matched this row against <em>some</em> authored key: a row a
/// case-sensitive server returned matched exactly (stage 1), so these stages only ever resolve rows a
/// case- or accent-insensitive collation returned.</item>
/// </list>
/// <para>A row matching several authored keys at its stage is attributed to each of them — the server, by the
/// same collation, matched each. A key that then holds more than one row is the existing duplicate-key
/// <c>BadConfigurationError</c>, which is exactly what the server's own semantics say: the selector is
/// ambiguous.</para>
/// </summary>
internal sealed class SqlKeyMatcher
{
private const CompareOptions AccentInsensitive =
CompareOptions.IgnoreCase | CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth;
private readonly bool _collationStages;
private readonly HashSet<string> _exact = new(StringComparer.Ordinal);
private readonly Dictionary<string, List<string>> _trimmed = new(StringComparer.Ordinal);
private readonly Dictionary<string, List<string>> _caseInsensitive = new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, List<string>>? _accentInsensitive;
private readonly Dictionary<decimal, List<string>> _numeric = new();
private readonly Dictionary<Guid, List<string>> _guids = new();
private readonly Dictionary<bool, List<string>> _booleans = new();
/// <summary>Indexes the authored keys.</summary>
/// <param name="authoredKeys">The keys the tags were authored with (nulls ignored; duplicates collapse).</param>
/// <param name="collationStages">
/// True for a key the SERVER matched (the key-value <c>IN</c> list), enabling the case/accent stages; false
/// for a client-side pick (a named query's <c>rowKey</c>), where only exact and representational equality hold.
/// </param>
public SqlKeyMatcher(IEnumerable<string?> authoredKeys, bool collationStages)
{
_collationStages = collationStages;
if (collationStages)
{
try
{
_accentInsensitive = new Dictionary<string, List<string>>(
StringComparer.Create(CultureInfo.InvariantCulture, AccentInsensitive));
}
catch (PlatformNotSupportedException)
{
// Globalization-invariant mode has no linguistic comparer; the case-insensitive stage still runs.
_accentInsensitive = null;
}
}
foreach (var key in authoredKeys)
{
if (key is null || !_exact.Add(key)) continue;
var trimmed = TrimPadding(key);
Add(_trimmed, trimmed, key);
if (_collationStages)
{
Add(_caseInsensitive, trimmed, key);
if (_accentInsensitive is not null) TryAdd(_accentInsensitive, trimmed, key);
}
if (TryParseNumber(key, out var number)) Add(_numeric, number, key);
if (Guid.TryParse(key.Trim(), out var guid)) Add(_guids, guid, key);
if (TryParseBoolean(key, out var boolean)) Add(_booleans, boolean, key);
}
}
/// <summary>
/// The authored keys a non-null key cell answers, at the first stage that matches any — empty when none does.
/// </summary>
/// <param name="cell">The row's key cell, as the provider returned it.</param>
/// <returns>The matched authored keys.</returns>
public IReadOnlyList<string> Match(object cell)
{
var text = cell is char[] chars ? new string(chars) : Convert.ToString(cell, CultureInfo.InvariantCulture);
if (text is not null && _exact.Contains(text)) return [text];
switch (cell)
{
case Guid guid:
return _guids.GetValueOrDefault(guid) ?? (IReadOnlyList<string>)[];
case bool boolean:
return _booleans.GetValueOrDefault(boolean) ?? (IReadOnlyList<string>)[];
case string or char[] or char:
break;
default:
return TryToDecimal(cell, out var number)
? _numeric.GetValueOrDefault(number) ?? (IReadOnlyList<string>)[]
: [];
}
if (text is null) return [];
var trimmed = TrimPadding(text);
if (_trimmed.TryGetValue(trimmed, out var padded)) return padded;
if (!_collationStages) return [];
if (_caseInsensitive.TryGetValue(trimmed, out var cased)) return cased;
return _accentInsensitive is not null && TryGet(_accentInsensitive, trimmed, out var accented) ? accented : [];
}
/// <summary>Fixed-width text is space-padded; every supported backend compares ignoring trailing spaces.</summary>
private static string TrimPadding(string text) => text.TrimEnd(' ');
private static bool TryParseNumber(string text, out decimal number)
=> decimal.TryParse(text.Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out number);
private static bool TryParseBoolean(string text, out bool value)
{
switch (text.Trim().ToLowerInvariant())
{
case "1" or "true":
value = true;
return true;
case "0" or "false":
value = false;
return true;
default:
value = false;
return false;
}
}
/// <summary>A numeric cell as a decimal (float/double through their own precision, so a REAL 1.1 is 1.1).</summary>
private static bool TryToDecimal(object cell, out decimal number)
{
number = 0m;
try
{
switch (cell)
{
case decimal d:
number = d;
return true;
case double d when double.IsFinite(d):
number = (decimal)d;
return true;
case float f when float.IsFinite(f):
number = (decimal)f;
return true;
case sbyte or byte or short or ushort or int or uint or long or ulong:
number = Convert.ToDecimal(cell, CultureInfo.InvariantCulture);
return true;
default:
return false;
}
}
catch (OverflowException)
{
return false;
}
}
private static void Add<TKey>(Dictionary<TKey, List<string>> index, TKey key, string authored) where TKey : notnull
{
if (!index.TryGetValue(key, out var list)) index[key] = list = [];
if (!list.Contains(authored, StringComparer.Ordinal)) list.Add(authored);
}
private static void TryAdd(Dictionary<string, List<string>> index, string key, string authored)
{
try
{
Add(index, key, authored);
}
catch (Exception ex) when (ex is ArgumentException or PlatformNotSupportedException)
{
// A string the linguistic comparer cannot hash is simply not offered to the accent stage.
}
}
private static bool TryGet(Dictionary<string, List<string>> index, string key, out List<string> found)
{
try
{
return index.TryGetValue(key, out found!);
}
catch (Exception ex) when (ex is ArgumentException or PlatformNotSupportedException)
{
found = [];
return false;
}
}
}
@@ -557,16 +557,18 @@ public sealed class SqlPollReader : IDisposable
try
{
// A named query is operator-authored SQL. The authoring guard (SqlReadOnlyStatement) already
// refused anything that is not a single SELECT, and this is the backstop behind it: the
// statement runs inside a transaction that is ALWAYS rolled back, so a side effect the guard
// could not see (a function that writes) is never committed. Disposing the transaction without
// a commit rolls it back, including on the timeout/abandon path.
// refused anything that is not a single SELECT as this provider lexes it, and this is the backstop
// behind it (lmxopcua#974): the statement runs inside a transaction that is ALWAYS rolled back and
// that the dialect makes read-only where its provider can, and the dialect seals the command to one
// statement where its provider can (SealNamedQueryCommand), so neither a side effect the guard could
// not see (a function that writes) nor a statement smuggled past it commits. Disposing the
// transaction without a commit rolls it back, including on the timeout/abandon path.
var transaction = plan.Model == SqlTagModel.Query
? await connection.BeginTransactionAsync(cancellationToken).ConfigureAwait(false)
? await _dialect.BeginNamedQueryAsync(connection, cancellationToken).ConfigureAwait(false)
: null;
await using var rollback = transaction is null
? null
: new RollbackOnDispose(transaction);
: new RollbackOnDispose(transaction, connection, _dialect);
var command = connection.CreateCommand();
await using (command.ConfigureAwait(false))
@@ -588,6 +590,8 @@ public sealed class SqlPollReader : IDisposable
command.Parameters.Add(parameter);
}
if (plan.Model == SqlTagModel.Query) _dialect.SealNamedQueryCommand(command);
var reader = await command.ExecuteReaderAsync(cancellationToken).ConfigureAwait(false);
await using (reader.ConfigureAwait(false))
{
@@ -771,17 +775,21 @@ public sealed class SqlPollReader : IDisposable
if (plan.KeyColumn is null || !outcome.ColumnIndex.TryGetValue(plan.KeyColumn, out var keyAt))
return index;
// The server matched these rows with the column's own type and collation (WHERE key IN (…)), so a row is
// attributed back by the same semantics, not by an ordinal compare of its stringified cell (#987, S-6):
// exact first, then typed / padding-insensitive, then case- and accent-insensitive — see SqlKeyMatcher.
var matcher = new SqlKeyMatcher(plan.Members.Select(m => m.KeyValue), collationStages: true);
foreach (var row in outcome.Rows)
{
// A NULL key cell indexes nothing: Convert.ToString would fold it to "", which would then be
// matched by a tag whose keyValue is legitimately the empty string.
if (row[keyAt] is not { } keyCell) continue;
// Stringified because the bound keyValue is authored text while the column may be any type
// (an INTEGER station id, say) — the provider coerces on the way in, so match on the way out.
var key = Convert.ToString(keyCell, CultureInfo.InvariantCulture);
if (key is null) continue;
if (!index.TryAdd(key, row)) (duplicatedKeys ??= new HashSet<string>(StringComparer.Ordinal)).Add(key);
foreach (var key in matcher.Match(keyCell))
{
if (!index.TryAdd(key, row))
(duplicatedKeys ??= new HashSet<string>(StringComparer.Ordinal)).Add(key);
}
}
if (duplicatedKeys is not null && ShouldWarn("dupkey:" + plan.SqlText))
@@ -913,12 +921,13 @@ public sealed class SqlPollReader : IDisposable
var keyAt = outcome.ColumnIndex[resolvedKey];
row = null;
var matches = 0;
// The authored value is configuration text; the cell is whatever type the query projects. Matched
// exactly or representationally (an INT 7 for "007", any Guid casing, CHAR padding — #987, S-6), but
// never by collation: the server did not compare these, so case is the data's own.
var matcher = new SqlKeyMatcher([member.RowKeyValue], collationStages: false);
foreach (var candidate in outcome.Rows)
{
// Matched as text, exactly as a key-value key is: the authored value is configuration text.
if (candidate[keyAt] is not { } cell
|| !string.Equals(Convert.ToString(cell, CultureInfo.InvariantCulture), member.RowKeyValue,
StringComparison.Ordinal))
if (candidate[keyAt] is not { } cell || matcher.Match(cell).Count == 0)
continue;
row = candidate;
matches++;
@@ -1087,7 +1096,8 @@ public sealed class SqlPollReader : IDisposable
/// nothing it did may be committed. A rollback that fails (the connection already broke) is swallowed:
/// the uncommitted work dies with the connection either way.
/// </summary>
private sealed class RollbackOnDispose(DbTransaction transaction) : IAsyncDisposable
private sealed class RollbackOnDispose(DbTransaction transaction, DbConnection connection, ISqlDialect dialect)
: IAsyncDisposable
{
public async ValueTask DisposeAsync()
{
@@ -1097,12 +1107,24 @@ public sealed class SqlPollReader : IDisposable
}
catch (Exception ex) when (ex is DbException or InvalidOperationException)
{
// Nothing was committed; the transaction ends with its connection.
// Nothing was committed by the driver; the transaction ends with its connection. (A statement that
// ended it itself — a smuggled COMMIT — also lands here: "this transaction has completed".)
}
finally
{
await transaction.DisposeAsync().ConfigureAwait(false);
}
try
{
// Restore any session state the dialect set for the named query (MySQL's read-only session), so
// the pooled connection is not handed to a write still read-only.
await dialect.EndNamedQueryAsync(connection).ConfigureAwait(false);
}
catch (Exception ex) when (ex is DbException or InvalidOperationException)
{
// Best effort: the connection is being returned, and the pool's own reset covers the default case.
}
}
}
@@ -18,12 +18,18 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Sql;
/// 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);
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
@@ -49,6 +55,7 @@ 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>
@@ -197,7 +204,15 @@ public static class SqlWritePlanner
return SqlStatusCodes.BadNotWritable;
}
plan = new SqlWritePlan(sql, binds.Names, binds.Values, write.Mode, maxRows);
// 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;
}