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.
This commit is contained in:
Joseph Doherty
2026-12-03 10:33:45 -05:00
parent 65fd71de7a
commit 65c4330a68
26 changed files with 2067 additions and 298 deletions
+9
View File
@@ -214,6 +214,15 @@ host logger factory (wired in `DriverFactoryBootstrap`; the FOCAS and TwinCAT fa
must add parameters in marker order). Named `Query` tags run inside an always-rolled-back transaction behind the
`SqlReadOnlyStatement` guard; writes are `allowWrites` + tag `"writable": true` + a single-row model, as a
parameterised UPDATE over gate-canonical identifiers that commits only on exactly one row. `docs/drivers/Sql.md`.
- **Sql named-query guard is per-dialect (#974):** `SqlReadOnlyStatement.Check(sql, provider, …)` lexes as the
provider does and REFUSES what dialects disagree on (MySQL/PG backslash in a literal, `$$`, `q'`, `/*!`, nested
comments, MySQL `--x`, bare-CR line comments); Odbc / no provider ⇒ every dialect must agree. Never add a
provider-less call site. Execution: `ISqlDialect.BeginNamedQueryAsync` (PG/Oracle `SET TRANSACTION READ ONLY`,
MySQL read-only session + txn, restored by `EndNamedQueryAsync`) and `SealNamedQueryCommand` (PG rewrites `@name`
to positional `$n` — Npgsql then sends unsplit and the server refuses a 2nd statement; a parameterless query gets
one unused typed `$1`). SQL Server / MySQL still execute batches: the lexer + a SELECT-only login are the line.
Key-value rows attribute by `SqlKeyMatcher` (exact → typed/padding → collation; #987), and SQL Server table
writes count the statement's own `@@ROWCOUNT` via an OUTPUT param (trigger DML no longer counts).
- **FOCAS / AbLegacy:** background loops are joined (≤ 5 s) on shutdown.
- **FOCAS (#257/#266):** `cnc_statinfo` flags are a `Status/` fixed-tree subtree (`FIXED:Status/Run`…, capability-probed);
adjacent PMC tags in one poll batch coalesce into one `pmc_rdpmcrng` (`PmcCoalesce` config, default on) — a refused range
+65 -27
View File
@@ -137,21 +137,30 @@ point the tag at a latest-row view.
Both value-bearing fields — `whereValue` here and `keyValue` on the `KeyValue` model — may be
authored as a JSON string, number or boolean, and are captured as text. They are **bound as
parameters** either way, and matched back as text (the key cell is stringified), so a key column
that holds an INTEGER station id can be authored either `"7"` or `7`. A JSON object, array or `null`
is not a value and is refused. On **PostgreSQL** a string bind is sent untyped (`NpgsqlDbType.Unknown`,
`PostgresDialect.ConfigureParameter`, STAB-24) so the server infers its type from the compared column;
bound as `text`, a `"7"` against an `integer` key fails with `operator does not exist: integer = text`.
parameters** either way, so a key column that holds an INTEGER station id can be authored either `"7"` or
`7`. A JSON object, array or `null` is not a value and is refused. On **PostgreSQL** a string bind is sent
untyped (`NpgsqlDbType.Unknown`, `PostgresDialect.ConfigureParameter`, STAB-24) so the server infers its type
from the compared column; bound as `text`, a `"7"` against an `integer` key fails with
`operator does not exist: integer = text`. (They were read asymmetrically until 2026-08-10, so a numerically
authored `keyValue` refused the tag while the identically-bound `whereValue` was served — and the deploy gate
reported the key as *missing* when it was right there in the blob.)
⚠️ **Known limitation — key normalisation.** Row slice-back matches the returned key cell by its *text* form
(`Convert.ToString`, ordinal), while the server now matches by the column's inferred type. An authored key the
server treats as equal but whose text differs therefore selects a row that the driver then cannot find, and the
tag reads **no-row**: `"007"` against an `integer` column (returns `7`), `"1.50"` against `numeric` (returns
`1.5`), and an upper-case GUID against a `uuid` column (returned lower-case). Author keys in the column's
canonical text form. SQL Server behaves the same way.
(They were read asymmetrically until 2026-08-10, so a numerically
authored `keyValue` refused the tag while the identically-bound `whereValue` was served — and the
deploy gate reported the key as *missing* when it was right there in the blob.)
**Key-value rows are attributed by the server's own equality (#987).** The server picks the rows
(`WHERE key IN (…)`) with the column's type and collation, and the driver attributes each returned row back to
its tag by the same semantics (`SqlKeyMatcher`) — not by an ordinal compare of the stringified cell, which used
to leave a row the server returned attributed to no tag, reading `BadNoData` forever while the driver stayed
Healthy. Per row, the first stage that matches wins:
1. **Exact** text — always first, so on a case-*sensitive* column `pump1` and `PUMP1` stay two keys.
2. **Representational** — a typed compare for numeric, Guid and boolean cells (`"007"` against an `integer`
7, `"1.50"` against `numeric` 1.5, an upper-case GUID against a `uuid` / `uniqueidentifier`) and
trailing-space-insensitive text (a `CHAR(n)` key padded to `"PUMP1 "`).
3. **Collation** — case-insensitive, then accent / width / kana-insensitive: only rows a case- or
accent-insensitive collation returned (SQL Server's and MySQL's defaults) ever reach this stage.
A row equal to several authored keys at its stage is each of theirs; a key that then holds more than one row is
the duplicate-key `BadConfigurationError` — on a case-insensitive column holding both `PUMP1` and `pump1`, the
key `pump1` really is ambiguous. A text cell is never compared numerically (a `varchar` `"007"` is not `"7"`).
### `Query` — a named read-only query (#753)
@@ -174,7 +183,9 @@ row:
```
- **One execution per query per poll**, however many tags read it.
- **`rowKey` picks the row** (matched as text against that result column, like `keyValue`). Without a
- **`rowKey` picks the row** — matched against that result column exactly or representationally (an
`integer` 7 for `"007"`, any GUID casing, `CHAR` padding; #987), but never case-insensitively: the server
did not compare these, so case is the data's own. Without a
`rowKey` the query must return exactly one row. No matching row ⇒ `BadNoData`; two matching rows (or
two rows with no `rowKey`) ⇒ `BadConfigurationError` — never "last row wins".
- **Result column names** (`column`, `rowKey.column`, `timestampColumn`) match exactly first, then by a
@@ -188,14 +199,35 @@ row:
values are JSON scalars or `null`. Write the provider's own marker in the SQL: `@active` on SqlServer,
Postgres and MySql, `:p_active` on Oracle, a positional `?` on Odbc (bound in authored order). The
factory refuses a declared parameter whose marker the statement never uses.
- **Read-only, twice over.** `SqlReadOnlyStatement` refuses at construction (and in the AdminUI form)
anything but a single `SELECT`/`WITH` statement, and any of `INSERT UPDATE DELETE MERGE UPSERT DROP
- **Read-only, in layers (#974).** `SqlReadOnlyStatement` refuses at construction (and in the AdminUI
form) anything but a single `SELECT`/`WITH` statement, and any of `INSERT UPDATE DELETE MERGE UPSERT DROP
ALTER CREATE TRUNCATE EXEC EXECUTE CALL GRANT REVOKE DENY INTO COPY LOCK RENAME` outside a literal or
comment — so `SELECT … INTO`, `FOR UPDATE` and a data-modifying CTE are refused too. Behind that guard
the statement runs **inside a transaction the driver always rolls back**, so a side effect the guard
cannot see (a function that writes) is never committed. A non-transactional side effect (an e-mail
procedure, a sequence, a call out to another system) is outside both — which is why a read-only
driver **must** connect with a `SELECT`-only login (see [Database login](#database-login-required)).
comment — so `SELECT … INTO`, `FOR UPDATE` and a data-modifying CTE are refused too.
- **The guard lexes the statement as the driver's provider does.** It used to have one lexer for five
dialects, and where a provider ends a literal earlier than that lexer did, live SQL hid inside a
"literal": `SELECT '\'' ; COMMIT; DELETE …` on MySQL (backslash escape) and `SELECT $$'$$; COMMIT; DROP …`
on PostgreSQL (dollar quote) passed as one `SELECT`, and the embedded `COMMIT` ended the rolled-back
transaction before the write (reproduced live). Each provider now has its own lexicon, and what dialects
disagree on is **refused**, not modelled: a backslash inside a MySQL / PostgreSQL string literal (spell it
`CHR(92)` / `CHAR(92)`), PostgreSQL dollar quoting, Oracle `q'…'` quoting, MySQL `/*! … */` executable
comments, a nested `/* /* */` comment, MySQL `--` without a following space, a line comment ended by a bare
carriage return. T-SQL's `]]` inside `[ … ]` and MySQL's `#` comments are modelled. An **Odbc** driver's
backend is unknown, so its statement must lex identically under every dialect (so must a statement checked
without a provider). Changing the driver form's **Provider** re-validates the queries.
- **It executes in a read-only transaction where the provider has one** — always rolled back regardless:
PostgreSQL and Oracle `SET TRANSACTION READ ONLY`, MySQL a read-only **session** plus `START TRANSACTION
READ ONLY` (a smuggled `COMMIT` ends a transaction, not a session; the session is restored afterwards). A
function that writes is then refused by the server (the read fails) instead of writing and being rolled
back. SQL Server and Odbc get the plain always-rolled-back transaction.
- **PostgreSQL also refuses a second statement at the protocol level.** The driver sends a named query with
positional `$n` parameters (rewritten from your `@name` markers), which makes Npgsql pass the text unsplit
as one extended-protocol statement; the server rejects anything after a `;` itself. Oracle (ODP.NET)
refuses a second statement anyway. SQL Server and MySQL execute a multi-statement batch — there the
per-dialect guard is the line, and MySQL's read-only session is defence in depth that hidden text could
undo.
- None of this replaces the grant: a non-transactional side effect (an e-mail procedure, a call out to
another system, an autonomous transaction) is outside every layer — which is why a read-only driver
**must** connect with a `SELECT`-only login (see [Database login](#database-login-required)).
- A tag naming a query the driver config does not declare is **skipped** at Initialize (it reads
`BadNodeIdUnknown`, and `/hosts` names the missing query). One unusable `queries` entry **fails the
driver** instead, because every tag that names it would otherwise go dark unexplained.
@@ -420,7 +452,7 @@ both and is rolled back (`BadConfigurationError`).
|---|---|
| Committed | `Good` |
| `Update` (or a non-MySQL `Upsert`) touched no row — the key is absent; nothing is inserted | `BadNoData` |
| More rows than the mode allows — the key is not unique; rolled back | `BadConfigurationError` |
| More rows than the mode allows — the key is not unique; rolled back. The count is the **target statement's own**: on SQL Server the driver reads `@@ROWCOUNT` right after it (an `OUTPUT` parameter), because SqlClient's command-level count also sums trigger DML — an audit trigger that inserts a history row used to make every single-row write "touch 2 rows" and roll back (#987). PostgreSQL, MySQL and Oracle already report the statement alone. Odbc reports whatever its backend's driver does (an ODBC link to SQL Server keeps the trigger-summed count). | `BadConfigurationError` |
| The provider could not report a row count; rolled back | `BadNotSupported` |
| Unique / primary-key violation — e.g. an `Insert` of a key that exists (SQLSTATE 23505, SQL Server 2627/2601, MySQL 1062, ORA-00001) | `BadEntryExists` |
| Another integrity rule — NOT NULL, foreign key, CHECK (SQLSTATE class 23, SQL Server 515/547, ORA-01400/02290/02291) — or a data exception: overflow, truncation, an unconvertible value (SQLSTATE class 22, SQL Server 8115/8152/245, ORA-01438/12899/01722) | `BadOutOfRange` |
@@ -447,7 +479,12 @@ value. Writes never change driver health. Discovery advertises `Operate` only fo
not serve is `SqlWriteModeUnsupported`. The AdminUI tag editor shows the same parser message.
- Live gate: `SqlWriteModesLiveTests` runs the same suite (Update+stamp, absent key, Insert and its
duplicate, NOT NULL, Upsert insert-then-update, Procedure, unknown procedure) against SQL Server,
PostgreSQL, MySQL and Oracle; `OdbcReadTests` covers Odbc's Update/Insert.
PostgreSQL, MySQL and Oracle; `OdbcReadTests` covers Odbc's Update/Insert;
`SqlServerTriggerWriteLiveTests` proves Update / Insert / Upsert commit on a table whose audit trigger writes
two rows per changed row (#987). `NamedQueryBypassLiveTests` proves, per provider, that each smuggled-write
string is a working bypass the old way, that the guard refuses it, and that with the guard bypassed the
write still does not land (PostgreSQL, MySQL) — plus the MySQL session restore and an Oracle read under
`SET TRANSACTION READ ONLY`.
## Database login (required)
@@ -455,9 +492,10 @@ The driver's own guards are not a substitute for the database's grants:
- **A read-only driver (`allowWrites` off) must connect with a `SELECT`-only login** — `SELECT` on
the tables and views its tags and named queries read, and nothing else. The named-query guard is a
keyword check plus an always-rolled-back transaction; neither can stop a **non-transactional** side
effect — a sequence `nextval`, a function that sends mail or calls out, autonomous transactions,
DDL that auto-commits on some backends. Only the grant can.
per-dialect keyword check plus an always-rolled-back (read-only where the provider has one) transaction;
none of that can stop a **non-transactional** side effect — a function that sends mail or calls out,
autonomous transactions — and on SQL Server and MySQL a statement that got past the lexer would run as a
batch. Only the grant is a boundary.
- **A writable driver must connect with a login limited to its write targets** — `SELECT` as above,
plus exactly what its modes need on exactly the tables / procedures its writable tags name:
`UPDATE` (Update), `INSERT` (Insert), `INSERT` + `UPDATE` (Upsert; SQL Server's `MERGE` also needs
@@ -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;
}
@@ -17,7 +17,7 @@
<div class="row g-3">
<div class="col-md-4">
<label for="@FieldId("field-01")" class="form-label">Provider</label>
<InputSelect aria-describedby="@FieldIds("field-01-hint")" id="@FieldId("field-01")" @bind-Value="_form.Provider" @bind-Value:after="EmitAsync" class="form-select form-select-sm">
<InputSelect aria-describedby="@FieldIds("field-01-hint")" id="@FieldId("field-01")" @bind-Value="_form.Provider" @bind-Value:after="OnProviderChangedAsync" class="form-select form-select-sm">
@* Every provider SqlDialects constructs. *@
<option value="@SqlProvider.SqlServer">@SqlProvider.SqlServer</option>
<option value="@SqlProvider.Postgres">@SqlProvider.Postgres</option>
@@ -184,6 +184,14 @@
await DriverConfigJsonChanged.InvokeAsync(json);
}
// The named-query guard lexes the SQL as the provider's own dialect (lmxopcua#974), so a provider change
// re-validates the queries text: what is a plain read under one dialect can be ambiguous under another.
private async Task OnProviderChangedAsync()
{
_form.SetQueriesJson(_form.QueriesJson);
await EmitAsync();
}
private async Task OnResilienceChanged(string? r)
{
ResilienceConfig = r;
@@ -230,17 +238,19 @@
};
/// <summary>Adopts edited queries text when it parses and every entry passes the runtime's own rules
/// (<see cref="SqlNamedQueryRules.Describe"/>); otherwise records why and keeps the last valid set, so a
/// typo never silently drops queries the deployed tags read.</summary>
/// (<see cref="SqlNamedQueryRules.Describe"/>, lexed as <see cref="Provider"/>'s dialect); otherwise records
/// why and keeps the last valid set, so a typo never silently drops queries the deployed tags read.</summary>
public void SetQueriesJson(string? text)
{
QueriesJson = text ?? "";
QueriesError = TryParseQueries(QueriesJson, out var parsed);
QueriesError = TryParseQueries(QueriesJson, Provider, out var parsed);
if (QueriesError is null) { Queries = parsed; }
}
/// <summary>Parses + validates queries text. Blank ⇒ no queries. Returns the problem, or null.</summary>
public static string? TryParseQueries(string? text, out Dictionary<string, SqlNamedQueryDto>? queries)
/// <summary>Parses + validates queries text as <paramref name="provider"/>'s dialect (the factory's own
/// rule). Blank ⇒ no queries. Returns the problem, or null.</summary>
public static string? TryParseQueries(
string? text, SqlProvider provider, out Dictionary<string, SqlNamedQueryDto>? queries)
{
queries = null;
if (string.IsNullOrWhiteSpace(text)) { return null; }
@@ -256,7 +266,7 @@
if (queries is null) { return "named queries must be a JSON object"; }
foreach (var (name, query) in queries)
{
if (SqlNamedQueryRules.Describe(name, query) is { } problem) { queries = null; return problem; }
if (SqlNamedQueryRules.Describe(name, query, provider) is { } problem) { queries = null; return problem; }
}
if (queries.Count == 0) { queries = null; }
@@ -245,12 +245,14 @@ public sealed class MySqlReadTests
/// <summary>
/// The backstop proven against a real side effect: <c>bump_counter()</c> INSERTs a row and returns 1. A
/// <c>SELECT bump_counter()</c> passes the read-only guard (nothing lexical says "write"), the read is Good
/// (positive control: the function really ran), and the row is gone afterwards — the driver's transaction
/// was rolled back, not committed.
/// <c>SELECT bump_counter()</c> passes the read-only guard (nothing lexical says "write"). Since lmxopcua#974
/// the named query runs in a READ-ONLY transaction (and session), so the server refuses the function's INSERT
/// outright — the read is a failure rather than a Good value whose effect was rolled back — and no row
/// survives. The positive control runs the same SELECT as the login in an ordinary (read-write) transaction:
/// the function really writes there — the row is visible inside it — and that transaction is rolled back.
/// </summary>
[Fact]
public async Task NamedQuery_realMySql_aWritingFunctionsEffectIsRolledBack()
public async Task NamedQuery_realMySql_aWritingFunctionIsRefusedByTheReadOnlyTransaction()
{
SkipUnlessLive();
@@ -259,10 +261,25 @@ public sealed class MySqlReadTests
Tag("Sql/Q/Bump", new JsonObject { ["model"] = "Query", ["query"] = "bump", ["column"] = "v" }));
var snapshot = (await driver.ReadAsync(["Sql/Q/Bump"], TestContext.Current.CancellationToken))[0];
snapshot.StatusCode.ShouldBe(SqlStatusCodes.Good);
Convert.ToInt64(snapshot.Value, CultureInfo.InvariantCulture).ShouldBe(1L);
SqlStatusCodes.IsBad(snapshot.StatusCode).ShouldBeTrue();
(await _my.ScalarAsync("SELECT COUNT(*) FROM sqlpoll.side_effects")).ShouldBe(0L);
// Positive control: in a read-write transaction the function does write.
var connection = new MySqlDialect().Factory.CreateConnection()!;
await using (connection)
{
connection.ConnectionString = _my.ConnectionString;
await connection.OpenAsync(TestContext.Current.CancellationToken);
await using var transaction = await connection.BeginTransactionAsync(TestContext.Current.CancellationToken);
await using var command = connection.CreateCommand();
command.Transaction = transaction;
command.CommandText = "SELECT sqlpoll.bump_counter()";
await command.ExecuteScalarAsync(TestContext.Current.CancellationToken);
command.CommandText = "SELECT COUNT(*) FROM sqlpoll.side_effects";
Convert.ToInt64(await command.ExecuteScalarAsync(TestContext.Current.CancellationToken), CultureInfo.InvariantCulture)
.ShouldBe(1L);
await transaction.RollbackAsync(TestContext.Current.CancellationToken);
}
}
// ---- writes (design §3.4) against a real server ----
@@ -0,0 +1,322 @@
using System.Data.Common;
using System.Globalization;
using System.Text.Json.Nodes;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Driver.Sql.Contracts;
namespace ZB.MOM.WW.OtOpcUa.Driver.Sql.IntegrationTests;
/// <summary>
/// lmxopcua#974 (review finding S-7), against real servers: a write smuggled past the named-query guard must not
/// land. Each smuggled statement is one the pre-fix guard ACCEPTED as a single SELECT, and each test proves three
/// things:
/// <list type="number">
/// <item><b>It is a working bypass on this server</b> (positive control) — run the old way, inside an ordinary
/// transaction that is rolled back afterwards, the embedded <c>COMMIT</c> ends that transaction and the UPDATE
/// after it commits. (The control then restores the row.)</item>
/// <item><b>The guard now refuses it</b> as this provider lexes it.</item>
/// <item><b>The execution layer stops it even with the guard bypassed</b> — the statement is handed to the driver
/// as an already-"validated" named query, and the row is unchanged afterwards: PostgreSQL refuses a second
/// statement at the protocol level (positional parameters), MySQL runs the query in a read-only session.</item>
/// </list>
/// A legitimate named query (with and without parameters) still reads Good through the same harness — the
/// sealed / read-only path is not simply failing every query.
/// <para>Each leg writes a target row its login may UPDATE (<c>write_targets.Present</c> /
/// <c>setpoints.Line1.SpeedSp</c>) to a random value, so a pass cannot be a stale coincidence.</para>
/// </summary>
public abstract class NamedQueryBypassLiveSuite
{
protected abstract string? SkipReason { get; }
protected abstract string ConnectionString { get; }
protected abstract ISqlDialect Dialect { get; }
/// <summary>The qualified table + key of the row the smuggled UPDATE targets.</summary>
protected abstract (string Table, string Key) Target { get; }
/// <summary>The smuggled statement; <c>{0}</c> is the value its UPDATE writes.</summary>
protected abstract string SmuggledFormat { get; }
/// <summary>A legitimate parameterised read: (sql, param name, param value, column, expected value).</summary>
protected abstract (string Sql, string Param, object Value, string Column, double Expected) LegitimateRead { get; }
[Fact]
public async Task SmuggledWrite_isAWorkingBypassOnThisServer_theOldWay()
{
SkipUnlessLive();
var original = await ReadTargetAsync();
var smuggled = Random.Shared.Next(1000, 900_000);
try
{
await RunTheOldWayAsync(Smuggled(smuggled));
(await ReadTargetAsync()).ShouldBe(smuggled); // the bypass is real: the UPDATE committed past the rollback
}
finally
{
await WriteTargetAsync(original);
}
}
[Fact]
public void SmuggledWrite_isRefusedByTheGuard()
=> SqlReadOnlyStatement.Check(Smuggled(1), Dialect.Provider, out _).ShouldNotBeNull();
[Fact]
public async Task SmuggledWrite_pastTheGuard_doesNotLand()
{
SkipUnlessLive();
var original = await ReadTargetAsync();
var smuggled = Random.Shared.Next(1000, 900_000);
try
{
await using var driver = await StartAsync(
new SqlNamedQuery("evil", Smuggled(smuggled), [], [], SqlNamedQueryRules.DefaultMaxRows),
Tag("Q/Evil", "evil", "v"));
await driver.ReadAsync(["Q/Evil"], TestContext.Current.CancellationToken);
(await ReadTargetAsync()).ShouldBe(original);
}
finally
{
await WriteTargetAsync(original);
}
}
[Fact]
public async Task LegitimateNamedQueries_stillRead_withAndWithoutParameters()
{
SkipUnlessLive();
var read = LegitimateRead;
await using var driver = await StartAsync(
new SqlNamedQuery("withParam", read.Sql, [read.Param], [read.Value], SqlNamedQueryRules.DefaultMaxRows),
Tag("Q/WithParam", "withParam", read.Column),
new SqlNamedQuery("noParam", $"SELECT COUNT(*) AS n FROM {Target.Table}", [], [], SqlNamedQueryRules.DefaultMaxRows),
Tag("Q/NoParam", "noParam", "n"));
var snapshots = await driver.ReadAsync(["Q/WithParam", "Q/NoParam"], TestContext.Current.CancellationToken);
snapshots[0].StatusCode.ShouldBe(SqlStatusCodes.Good);
Convert.ToDouble(snapshots[0].Value, CultureInfo.InvariantCulture).ShouldBe(read.Expected);
snapshots[1].StatusCode.ShouldBe(SqlStatusCodes.Good);
Convert.ToInt64(snapshots[1].Value, CultureInfo.InvariantCulture).ShouldBeGreaterThan(0);
}
// ---- helpers ----
protected void SkipUnlessLive()
{
if (SkipReason is { } reason) Assert.Skip(reason);
}
private string Smuggled(int value) => string.Format(CultureInfo.InvariantCulture, SmuggledFormat, value);
/// <summary>A driver whose named queries are taken as given — the guard deliberately not consulted.</summary>
protected async Task<SqlDriver> StartAsync(params object[] queriesAndTags)
=> await StartAsync(ConnectionString, queriesAndTags);
protected async Task<SqlDriver> StartAsync(string connectionString, object[] queriesAndTags, bool allowWrites = false)
{
var driver = new SqlDriver(
new SqlDriverOptions
{
RawTags = queriesAndTags.OfType<RawTagEntry>().ToList(),
Queries = queriesAndTags.OfType<SqlNamedQuery>().ToDictionary(q => q.Name, StringComparer.Ordinal),
CommandTimeout = TimeSpan.FromSeconds(30),
OperationTimeout = TimeSpan.FromSeconds(45),
AllowWrites = allowWrites,
},
driverInstanceId: "sql-bypass-" + Dialect.Provider,
dialect: Dialect,
connectionString: connectionString);
try
{
await driver.InitializeAsync("{}", TestContext.Current.CancellationToken);
}
catch
{
await driver.DisposeAsync();
throw;
}
return driver;
}
protected static RawTagEntry Tag(string rawPath, string query, string column)
=> new(rawPath, new JsonObject
{
["driver"] = "Sql", ["model"] = "Query", ["query"] = query, ["column"] = column,
}.ToJsonString(), WriteIdempotent: false);
/// <summary>What the driver did before #974: a plain transaction, the statement, a rollback.</summary>
private async Task RunTheOldWayAsync(string sql)
{
await using var connection = await OpenAsync();
await using var transaction = await connection.BeginTransactionAsync(TestContext.Current.CancellationToken);
await using (var command = connection.CreateCommand())
{
command.Transaction = transaction;
command.CommandText = sql;
await using var reader = await command.ExecuteReaderAsync(TestContext.Current.CancellationToken);
do
{
while (await reader.ReadAsync(TestContext.Current.CancellationToken)) { }
}
while (await reader.NextResultAsync(TestContext.Current.CancellationToken));
}
try
{
await transaction.RollbackAsync(TestContext.Current.CancellationToken);
}
catch (InvalidOperationException)
{
// "This transaction has completed" — the smuggled COMMIT already ended it, which is the point.
}
}
protected async Task<double> ReadTargetAsync()
=> Convert.ToDouble(await ScalarAsync($"SELECT sp_value FROM {Target.Table} WHERE tag_name = '{Target.Key}'"),
CultureInfo.InvariantCulture);
private async Task WriteTargetAsync(double value)
=> await ScalarAsync(string.Create(CultureInfo.InvariantCulture,
$"UPDATE {Target.Table} SET sp_value = {value} WHERE tag_name = '{Target.Key}'"));
private async Task<object?> ScalarAsync(string sql)
{
await using var connection = await OpenAsync();
await using var command = connection.CreateCommand();
command.CommandText = sql;
return await command.ExecuteScalarAsync(TestContext.Current.CancellationToken);
}
private async Task<DbConnection> OpenAsync()
{
var connection = Dialect.Factory.CreateConnection()!;
connection.ConnectionString = ConnectionString;
await connection.OpenAsync(TestContext.Current.CancellationToken);
return connection;
}
}
/// <summary>PostgreSQL: the dollar-quote bypass, sealed by positional parameters (the server refuses a second command).</summary>
[Collection(PostgresCollection.Name)]
public sealed class PostgresNamedQueryBypassTests(PostgresFixture fixture) : NamedQueryBypassLiveSuite
{
protected override string? SkipReason => fixture.SkipReason;
protected override string ConnectionString => fixture.ConnectionString;
protected override ISqlDialect Dialect { get; } = new PostgresDialect();
protected override (string Table, string Key) Target => (PostgresFixture.Qualified("write_targets"), "Present");
protected override string SmuggledFormat =>
"SELECT $$'$$ AS v; COMMIT; UPDATE sqlpoll.write_targets SET sp_value = {0} WHERE tag_name = 'Present'; --'";
// tag_id is INTEGER and the bound value text: the positional rewrite must keep Npgsql's untyped bind working.
protected override (string Sql, string Param, object Value, string Column, double Expected) LegitimateRead =>
("SELECT num_value FROM sqlpoll.int_tag_values WHERE tag_id = @id", "id", "101", "num_value", 77.5);
/// <summary>
/// The read-only transaction, separately from the seal: a single-statement data-modifying CTE (which the guard
/// would refuse, so it is handed over unguarded) is one statement, so only <c>SET TRANSACTION READ ONLY</c> can
/// stop it — and the read FAILS rather than returning a Good value whose effect was merely rolled back.
/// </summary>
[Fact]
public async Task DataModifyingCte_pastTheGuard_isRefusedByTheReadOnlyTransaction()
{
SkipUnlessLive();
var original = await ReadTargetAsync();
await using var driver = await StartAsync(
new SqlNamedQuery("cte",
"WITH u AS (UPDATE sqlpoll.write_targets SET sp_value = sp_value + 1 WHERE tag_name = 'Present' RETURNING sp_value) SELECT sp_value AS v FROM u",
[], [], SqlNamedQueryRules.DefaultMaxRows),
Tag("Q/Cte", "cte", "v"));
var snapshot = (await driver.ReadAsync(["Q/Cte"], TestContext.Current.CancellationToken))[0];
SqlStatusCodes.IsBad(snapshot.StatusCode).ShouldBeTrue();
(await ReadTargetAsync()).ShouldBe(original);
}
}
/// <summary>MySQL: the backslash-escape bypass, stopped by the read-only session.</summary>
[Collection(MySqlCollection.Name)]
public sealed class MySqlNamedQueryBypassTests(MySqlFixture fixture) : NamedQueryBypassLiveSuite
{
protected override string? SkipReason => fixture.SkipReason;
protected override string ConnectionString => fixture.ConnectionString;
protected override ISqlDialect Dialect { get; } = new MySqlDialect();
protected override (string Table, string Key) Target => (MySqlFixture.Qualified("setpoints"), "Line1.SpeedSp");
protected override string SmuggledFormat =>
"SELECT '\\'' AS v; COMMIT; UPDATE sqlpoll.setpoints SET sp_value = {0} WHERE tag_name = 'Line1.SpeedSp'; -- '";
protected override (string Sql, string Param, object Value, string Column, double Expected) LegitimateRead =>
("SELECT num_value FROM sqlpoll.int_tag_values WHERE tag_id = @id", "id", "101", "num_value", 77.5);
/// <summary>
/// The read-only session is restored after the named query, so a pooled connection is not handed to a write
/// still read-only. Pinned on ONE physical connection with the pool's own reset turned off — otherwise the
/// pool's reset would mask a missing restore. A write after a named query on that connection must commit.
/// </summary>
[Fact]
public async Task ReadOnlySession_isRestored_beforeTheConnectionServesAWrite()
{
SkipUnlessLive();
var pinned = ConnectionString + ";Connection Reset=false;Maximum Pool Size=1;Application Name=OtOpcUa.Sql.ITs.pin";
var value = Random.Shared.Next(1000, 900_000);
await using var driver = await StartAsync(pinned,
[
new SqlNamedQuery("count", "SELECT COUNT(*) AS n FROM sqlpoll.setpoints", [], [], SqlNamedQueryRules.DefaultMaxRows),
Tag("Q/Count", "count", "n"),
new RawTagEntry("Sp", new JsonObject
{
["driver"] = "Sql", ["model"] = "KeyValue", ["table"] = "sqlpoll.write_targets", ["keyColumn"] = "tag_name",
["keyValue"] = "Present", ["valueColumn"] = "sp_value", ["type"] = "Float64", ["writable"] = true,
}.ToJsonString(), WriteIdempotent: false),
], allowWrites: true);
(await driver.ReadAsync(["Q/Count"], TestContext.Current.CancellationToken))[0].StatusCode.ShouldBe(SqlStatusCodes.Good);
var written = await ((IWritable)driver).WriteAsync([new WriteRequest("Sp", (double)value)], TestContext.Current.CancellationToken);
written.ShouldHaveSingleItem().StatusCode.ShouldBe(SqlStatusCodes.Good);
}
}
/// <summary>Oracle: ODP.NET already refuses a second statement; the read-only transaction must not break an ordinary read.</summary>
[Collection(OracleCollection.Name)]
public sealed class OracleNamedQueryReadOnlyTests(OracleFixture fixture)
{
[Fact]
public async Task LegitimateNamedQuery_readsInsideTheReadOnlyTransaction_onRepeatedPolls()
{
if (fixture.SkipReason is { } reason) Assert.Skip(reason);
var driver = new SqlDriver(
new SqlDriverOptions
{
RawTags = [new RawTagEntry("Q/One", """{"driver":"Sql","model":"Query","query":"one","column":"V"}""", WriteIdempotent: false)],
Queries = new Dictionary<string, SqlNamedQuery>(StringComparer.Ordinal)
{
["one"] = new("one", "SELECT 41 + :p_x AS v FROM dual", ["x"], [1L], SqlNamedQueryRules.DefaultMaxRows),
},
CommandTimeout = TimeSpan.FromSeconds(60),
OperationTimeout = TimeSpan.FromSeconds(90),
},
driverInstanceId: "sql-oracle-readonly",
dialect: new OracleDialect(),
connectionString: fixture.ConnectionString);
await using (driver)
{
await driver.InitializeAsync("{}", TestContext.Current.CancellationToken);
for (var poll = 0; poll < 3; poll++)
{
var snapshot = (await driver.ReadAsync(["Q/One"], TestContext.Current.CancellationToken))[0];
snapshot.StatusCode.ShouldBe(SqlStatusCodes.Good);
Convert.ToInt64(snapshot.Value, CultureInfo.InvariantCulture).ShouldBe(42L);
}
}
}
}
@@ -383,6 +383,8 @@ public sealed class SqlPollServerFixture : IAsyncLifetime
yield return $"DROP PROCEDURE IF EXISTS [{Schema}].[set_target];";
yield return $"DROP TABLE IF EXISTS [{Schema}].[write_targets];";
yield return $"DROP TABLE IF EXISTS [{Schema}].[proc_calls];";
yield return $"DROP TABLE IF EXISTS [{Schema}].[{AuditedTable}];";
yield return $"DROP TABLE IF EXISTS [{Schema}].[{AuditLogTable}];";
yield return $"DROP TABLE IF EXISTS [{Schema}].[{KeyValueTable}];";
yield return $"DROP TABLE IF EXISTS [{Schema}].[{WideRowTable}];";
yield return $"DROP TABLE IF EXISTS [{Schema}].[{TypeProbeTable}];";
@@ -472,8 +474,37 @@ public sealed class SqlPollServerFixture : IAsyncLifetime
CREATE PROCEDURE [{Schema}].[set_target] @p_value float, @p_key nvarchar(128), @p_ts datetime2(3) AS
INSERT INTO [{Schema}].[proc_calls] ([tag_name], [sp_value], [stamp_ts]) VALUES (@p_key, @p_value, @p_ts);
""";
// lmxopcua#987 (S-10): a write target with an audit trigger that does NOT SET NOCOUNT ON and writes TWO rows
// per changed row — so SqlClient's ExecuteNonQuery reports 1 + 2 = 3 for a single-row UPDATE, and a driver that
// trusted that aggregate rolled every write back.
yield return $"""
CREATE TABLE [{Schema}].[{AuditedTable}] (
[tag_name] nvarchar(128) NOT NULL PRIMARY KEY,
[sp_value] float NOT NULL
);
""";
yield return $"""
CREATE TABLE [{Schema}].[{AuditLogTable}] (
[tag_name] nvarchar(128) NOT NULL,
[sp_value] float NULL,
[copy_no] int NOT NULL
);
""";
yield return $"INSERT INTO [{Schema}].[{AuditedTable}] ([tag_name], [sp_value]) VALUES (N'Present', 1.0);";
yield return $"""
CREATE TRIGGER [{Schema}].[audited_targets_audit] ON [{Schema}].[{AuditedTable}] AFTER INSERT, UPDATE AS
INSERT INTO [{Schema}].[{AuditLogTable}] ([tag_name], [sp_value], [copy_no]) SELECT [tag_name], [sp_value], 1 FROM inserted;
INSERT INTO [{Schema}].[{AuditLogTable}] ([tag_name], [sp_value], [copy_no]) SELECT [tag_name], [sp_value], 2 FROM inserted;
""";
}
/// <summary>A write target carrying an AFTER INSERT/UPDATE audit trigger (lmxopcua#987).</summary>
public const string AuditedTable = "audited_targets";
/// <summary>The table <see cref="AuditedTable"/>'s trigger writes two rows into per changed row.</summary>
public const string AuditLogTable = "audit_log";
private static async Task ExecuteAsync(SqlConnection connection, string sql)
{
var command = connection.CreateCommand();
@@ -0,0 +1,133 @@
using System.Globalization;
using System.Text.Json.Nodes;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Driver.Sql.Contracts;
namespace ZB.MOM.WW.OtOpcUa.Driver.Sql.IntegrationTests;
/// <summary>
/// lmxopcua#987 (review finding S-10): a table write's "exactly one row" commit rule against a SQL Server table
/// whose AFTER INSERT/UPDATE trigger writes two audit rows per changed row and does not <c>SET NOCOUNT ON</c>.
/// SqlClient's <c>ExecuteNonQuery</c> returns the SUM of every DML statement the command caused (1 + 2 = 3), so a
/// driver trusting it rolled every such write back as "touched 3 rows". The dialect now reads the target
/// statement's own <c>@@ROWCOUNT</c>.
/// <para>Positive controls: the audit rows exist (the trigger really fired inside the committed write), and an
/// Update of an absent key is still <c>BadNoData</c> (the count is the target's, not a constant 1).</para>
/// </summary>
[Collection(SqlPollServerCollection.Name)]
public sealed class SqlServerTriggerWriteLiveTests(SqlPollServerFixture fixture)
{
[Theory]
[InlineData("Update")]
[InlineData("Upsert")]
public async Task Write_toATableWithARowWritingTrigger_commitsTheOneTargetRow(string mode)
{
SkipUnlessLive();
var key = mode == "Update" ? "Present" : NewKey();
var value = 100.0 + Random.Shared.Next(1, 1000);
await using var driver = await StartAsync(Target("Sp", key, mode));
(await WriteAsync(driver, "Sp", value)).ShouldBe(SqlStatusCodes.Good);
Convert.ToDouble(await ScalarAsync(
$"SELECT sp_value FROM [{SqlPollServerFixture.Schema}].[{SqlPollServerFixture.AuditedTable}] WHERE tag_name = N'{key}'"),
CultureInfo.InvariantCulture).ShouldBe(value);
Convert.ToInt32(await ScalarAsync(
$"SELECT COUNT(*) FROM [{SqlPollServerFixture.Schema}].[{SqlPollServerFixture.AuditLogTable}] " +
$"WHERE tag_name = N'{key}' AND sp_value = {value.ToString(CultureInfo.InvariantCulture)}"),
CultureInfo.InvariantCulture).ShouldBe(2);
}
[Fact]
public async Task Insert_intoATableWithARowWritingTrigger_commitsTheOneNewRow()
{
SkipUnlessLive();
var key = NewKey();
await using var driver = await StartAsync(Target("Sp", key, "Insert"));
(await WriteAsync(driver, "Sp", 4.5)).ShouldBe(SqlStatusCodes.Good);
Convert.ToInt32(await ScalarAsync(
$"SELECT COUNT(*) FROM [{SqlPollServerFixture.Schema}].[{SqlPollServerFixture.AuditedTable}] WHERE tag_name = N'{key}'"),
CultureInfo.InvariantCulture).ShouldBe(1);
}
[Fact]
public async Task Update_ofAnAbsentKey_onATriggeredTable_isStillBadNoData()
{
SkipUnlessLive();
await using var driver = await StartAsync(Target("Sp", NewKey(), "Update"));
(await WriteAsync(driver, "Sp", 1.0)).ShouldBe(SqlStatusCodes.BadNoData);
}
private void SkipUnlessLive()
{
if (fixture.SkipReason is { } reason) Assert.Skip(reason);
}
private static string NewKey() => "T-" + Guid.NewGuid().ToString("N")[..12];
private static RawTagEntry Target(string rawPath, string key, string mode)
{
var config = new JsonObject
{
["driver"] = "Sql",
["model"] = "KeyValue",
["table"] = SqlPollServerFixture.Schema + "." + SqlPollServerFixture.AuditedTable,
["keyColumn"] = "tag_name",
["keyValue"] = key,
["valueColumn"] = "sp_value",
["type"] = "Float64",
["writable"] = true,
["write"] = new JsonObject { ["mode"] = mode },
};
return new RawTagEntry(rawPath, config.ToJsonString(), WriteIdempotent: false);
}
private async Task<SqlDriver> StartAsync(params RawTagEntry[] tags)
{
var driver = new SqlDriver(
new SqlDriverOptions
{
RawTags = tags,
CommandTimeout = TimeSpan.FromSeconds(30),
OperationTimeout = TimeSpan.FromSeconds(45),
AllowWrites = true,
},
driverInstanceId: "sql-trigger-writes",
dialect: new SqlServerDialect(),
connectionString: fixture.ConnectionString);
try
{
await driver.InitializeAsync("{}", TestContext.Current.CancellationToken);
}
catch
{
await driver.DisposeAsync();
throw;
}
return driver;
}
private static async Task<uint> WriteAsync(SqlDriver driver, string reference, object? value)
=> (await ((IWritable)driver).WriteAsync([new WriteRequest(reference, value)], TestContext.Current.CancellationToken))
.ShouldHaveSingleItem().StatusCode;
private async Task<object?> ScalarAsync(string sql)
{
var connection = await fixture.OpenInspectionConnectionAsync();
await using (connection)
{
var command = connection.CreateCommand();
await using (command)
{
command.CommandText = sql;
return await command.ExecuteScalarAsync(TestContext.Current.CancellationToken);
}
}
}
}
@@ -294,4 +294,51 @@ public class PostgresDialectTests
command.Parameters[0].ParameterName.ShouldBe("@k0");
command.Parameters[0].Value.ShouldBe(7);
}
// ---- named-query seal (lmxopcua#974) ----
/// <summary>
/// Positional parameters are what make Npgsql send the text unsplit, so the server refuses a second statement.
/// Every @name marker outside a literal/comment becomes its parameter's $n (repeats included), the names are
/// cleared, and the literal that spells the marker is left alone.
/// </summary>
[Fact]
public void SealNamedQueryCommand_rewritesNamedMarkersToPositional_andClearsTheNames()
{
using var command = new Npgsql.NpgsqlCommand(
"SELECT a FROM t WHERE x = @line AND y = @lineId AND z = @line AND note = '@line'");
command.Parameters.Add(new Npgsql.NpgsqlParameter("@line", 7));
command.Parameters.Add(new Npgsql.NpgsqlParameter("@lineId", "L"));
new PostgresDialect().SealNamedQueryCommand(command);
command.CommandText.ShouldBe("SELECT a FROM t WHERE x = $1 AND y = $2 AND z = $1 AND note = '@line'");
command.Parameters.Select(p => p.ParameterName).ShouldBe(["", ""]);
command.Parameters.Select(p => p.Value).ShouldBe([7, (object)"L"]);
}
/// <summary>A parameterless statement would take Npgsql's parsing (splitting) path, so it gets one unused typed positional parameter.</summary>
[Fact]
public void SealNamedQueryCommand_givesAParameterlessStatementOneUnusedPositionalParameter()
{
using var command = new Npgsql.NpgsqlCommand("SELECT 1 AS v");
new PostgresDialect().SealNamedQueryCommand(command);
command.CommandText.ShouldBe("SELECT 1 AS v");
command.Parameters.ShouldHaveSingleItem().ParameterName.ShouldBe("");
command.Parameters[0].NpgsqlDbType.ShouldBe(NpgsqlTypes.NpgsqlDbType.Integer);
}
[Fact]
public void SealNamedQueryCommand_leavesAForeignCommandUntouched()
{
using var command = new SqliteCommand("SELECT @k0");
command.Parameters.AddWithValue("@k0", 7);
new PostgresDialect().SealNamedQueryCommand(command);
command.CommandText.ShouldBe("SELECT @k0");
command.Parameters[0].ParameterName.ShouldBe("@k0");
}
}
@@ -0,0 +1,137 @@
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));
}
}
@@ -69,11 +69,15 @@ public sealed class SqlNamedQueryTests
[InlineData("WITH latest AS (SELECT a FROM t) SELECT a FROM latest")]
[InlineData("SELECT 'DELETE FROM t; DROP TABLE t' AS note FROM t")] // keywords inside a literal
[InlineData("SELECT a /* UPDATE t */ FROM t -- INSERT INTO t\n WHERE 1 = 1")] // …and inside comments
[InlineData("SELECT [update] FROM t")] // a quoted identifier
[InlineData("SELECT \"delete\" FROM t")]
[InlineData("SELECT \"delete\" FROM t")] // a quoted identifier (a string on MySQL)
public void ReadOnlyStatement_acceptsASingleRead(string sql)
=> SqlReadOnlyStatement.Check(sql, out _).ShouldBeNull();
/// <summary>A T-SQL bracket identifier quotes a keyword on SQL Server only (lmxopcua#974: lexed per dialect).</summary>
[Fact]
public void ReadOnlyStatement_aBracketIdentifier_quotesOnSqlServer()
=> SqlReadOnlyStatement.Check("SELECT [update] FROM t", SqlProvider.SqlServer, out _).ShouldBeNull();
[Theory]
[InlineData("UPDATE t SET a = 1")]
[InlineData("DELETE FROM t")]
@@ -308,6 +312,112 @@ public sealed class SqlNamedQueryTests
factory.TransactionsBegun.ShouldBe(0);
}
/// <summary>
/// lmxopcua#987 (S-6): a named query's rowKey is matched to the cell's VALUE, not to its stringification — an
/// INTEGER station 7 is the row an author who wrote "007" meant. Before the fix this read BadNoData forever.
/// </summary>
[Fact]
public async Task Read_aRowKey_matchesAnIntegerCellAuthoredWithLeadingZeros()
{
using var fixture = new SqlitePollFixture();
await using var driver = await StartAsync(fixture,
"""{"stations":{"sql":"SELECT station_id AS Station, oven_temp AS Temp FROM LatestStatus"}}""",
Tag("Q/Seven", """{"model":"Query","query":"stations","column":"Temp","rowKey":{"column":"Station","value":"007"},"type":"Float64"}"""));
var snapshot = (await driver.ReadAsync(["Q/Seven"], CancellationToken.None))[0];
snapshot.StatusCode.ShouldBe(SqlStatusCodes.Good);
Convert.ToDouble(snapshot.Value, CultureInfo.InvariantCulture).ShouldBe(SqlitePollFixture.PresentStationOvenTemp);
}
/// <summary>
/// lmxopcua#974 (S-7): a named query opens its transaction through the dialect (read-only where the provider can),
/// seals its command through the dialect (single-statement where the provider can), and lets the dialect restore
/// session state afterwards. A key-value read does none of the three — the positive/negative pair.
/// </summary>
[Fact]
public async Task Read_aNamedQuery_goesThroughTheDialectsReadOnlyHooks_andAKeyValueReadDoesNot()
{
using var fixture = new SqlitePollFixture();
var dialect = new NamedQueryHookDialect();
var dto = Dto("""{"one":{"sql":"SELECT MAX(num_value) AS top FROM TagValues WHERE num_value > @min","params":{"min":0}}}""");
var options = new SqlDriverOptions
{
RawTags =
[
Tag("Q/One", """{"model":"Query","query":"one","column":"top"}"""),
Tag("Kv", $$"""{"model":"KeyValue","table":"TagValues","keyColumn":"tag_name","keyValue":"{{SqlitePollFixture.PresentKey}}","valueColumn":"num_value"}"""),
],
OperationTimeout = TimeSpan.FromSeconds(15),
CommandTimeout = TimeSpan.FromSeconds(10),
Queries = SqlDriverFactoryExtensions.BuildOptions(dto, DriverInstanceId, dialect).Queries,
};
await using var driver = new SqlDriver(options, DriverInstanceId, dialect, fixture.ConnectionString, fixture.Factory);
await driver.InitializeAsync("{}", CancellationToken.None);
(await driver.ReadAsync(["Kv"], CancellationToken.None))[0].StatusCode.ShouldBe(SqlStatusCodes.Good);
dialect.Begun.ShouldBe(0);
dialect.Sealed.ShouldBeEmpty();
dialect.Ended.ShouldBe(0);
(await driver.ReadAsync(["Q/One"], CancellationToken.None))[0].StatusCode.ShouldBe(SqlStatusCodes.Good);
dialect.Begun.ShouldBe(1);
dialect.Sealed.ShouldHaveSingleItem().ShouldBe(("SELECT MAX(num_value) AS top FROM TagValues WHERE num_value > @min", 1));
dialect.Ended.ShouldBe(1);
}
/// <summary>
/// A SQLite dialect recording the named-query hooks. The seal sees the command fully built — its text and its
/// bound parameters — which is what a provider-level rewrite (Postgres' positional markers) needs.
/// </summary>
private sealed class NamedQueryHookDialect : ISqlDialect
{
private static readonly SqliteDialect Inner = new();
private int _begun;
private int _ended;
public int Begun => Volatile.Read(ref _begun);
public int Ended => Volatile.Read(ref _ended);
public List<(string Text, int Parameters)> Sealed { get; } = [];
public SqlProvider Provider => Inner.Provider;
public DbProviderFactory Factory => Inner.Factory;
public int MaxBindParameters => Inner.MaxBindParameters;
public string LivenessSql => Inner.LivenessSql;
public string SingleRowLimitPrefix => Inner.SingleRowLimitPrefix;
public string SingleRowLimitSuffix => Inner.SingleRowLimitSuffix;
public string RowLimitPrefix(int rows) => Inner.RowLimitPrefix(rows);
public string RowLimitSuffix(int rows) => Inner.RowLimitSuffix(rows);
public string ListSchemasSql => Inner.ListSchemasSql;
public string DefaultSchemaSql => Inner.DefaultSchemaSql;
public string ListTablesSql => Inner.ListTablesSql;
public string ListColumnsSql => Inner.ListColumnsSql;
public string ParameterMarker(string baseName) => Inner.ParameterMarker(baseName);
public string ParameterBindName(string baseName) => Inner.ParameterBindName(baseName);
public void ConfigureCommand(DbCommand command) => Inner.ConfigureCommand(command);
public string QuoteIdentifier(string ident) => Inner.QuoteIdentifier(ident);
public DriverDataType MapColumnType(string sqlDataType) => Inner.MapColumnType(sqlDataType);
public ValueTask<DbTransaction> BeginNamedQueryAsync(DbConnection connection, CancellationToken cancellationToken)
{
Interlocked.Increment(ref _begun);
return connection.BeginTransactionAsync(cancellationToken);
}
public void SealNamedQueryCommand(DbCommand command)
{
lock (Sealed) Sealed.Add((command.CommandText, command.Parameters.Count));
}
public ValueTask EndNamedQueryAsync(DbConnection connection)
{
Interlocked.Increment(ref _ended);
return ValueTask.CompletedTask;
}
}
// ---- helpers ----
private static SqlDriverConfigDto Dto(string queriesJson) => System.Text.Json.JsonSerializer.Deserialize<SqlDriverConfigDto>(
@@ -0,0 +1,128 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Driver.Sql.Contracts;
namespace ZB.MOM.WW.OtOpcUa.Driver.Sql.Tests;
/// <summary>
/// lmxopcua#974 (review finding S-7): the named-query guard must read a literal / comment boundary exactly as the
/// provider does, or refuse. Each bypass string below was accepted by the single shared lexer as one harmless
/// <c>SELECT</c> while the named provider reads a second statement — <c>COMMIT</c> (ending the driver's
/// always-rolled-back transaction) followed by a write. The Postgres and MySQL strings were executed against the
/// live fixtures before the fix and committed their UPDATE (see <c>NamedQueryBypassLiveTests</c>).
/// </summary>
public sealed class SqlReadOnlyStatementDialectTests
{
/// <summary>(provider the string is a bypass on, the statement).</summary>
public static TheoryData<SqlProvider, string> Bypasses => new()
{
// MySQL: backslash escapes in '…' and "…", # comments, and -- that is NOT a comment without a space.
{ SqlProvider.MySql, "SELECT '\\'' ; COMMIT; DELETE FROM t; -- '" },
{ SqlProvider.MySql, "SELECT \"\\\"\" ; COMMIT; DELETE FROM t; -- \"" },
{ SqlProvider.MySql, "SELECT 1 #'\n; COMMIT; DELETE FROM t; -- '" },
{ SqlProvider.MySql, "SELECT 1--'\n' ; COMMIT; DELETE FROM t; -- '" },
{ SqlProvider.MySql, "SELECT 1 /*! ; COMMIT; DELETE FROM t */" },
// PostgreSQL: dollar quoting (anonymous and tagged), E'' backslash escapes, [ as a subscript, nested comments,
// and a line comment that a bare carriage return ends.
{ SqlProvider.Postgres, "SELECT $$'$$; COMMIT; DROP TABLE t; --'" },
{ SqlProvider.Postgres, "SELECT $q$'$q$; COMMIT; DROP TABLE t; --'" },
{ SqlProvider.Postgres, "SELECT E'\\''; COMMIT; DELETE FROM t; --'" },
{ SqlProvider.Postgres, "SELECT a[']'] ; COMMIT; DELETE FROM t; --'" },
{ SqlProvider.Postgres, "SELECT 1 /* /* */ ' */ ; COMMIT; DELETE FROM t; --'" },
{ SqlProvider.Postgres, "SELECT 1 --x\r; COMMIT; DELETE FROM t\n" },
// SQL Server: ]] is an escaped ] inside [ … ], and comments nest.
{ SqlProvider.SqlServer, "SELECT [a]]'] ; COMMIT; DELETE FROM t; --'" },
{ SqlProvider.SqlServer, "SELECT 1 /* /* */ ' */ ; COMMIT; DELETE FROM t; --'" },
// Oracle: q'[…]' ends at "]'", not at the next quote.
{ SqlProvider.Oracle, "SELECT q'[ ' ]' FROM dual; DELETE FROM t --'" },
};
[Theory]
[MemberData(nameof(Bypasses))]
public void Check_refusesTheBypass_asItsOwnProvider(SqlProvider provider, string sql)
=> SqlReadOnlyStatement.Check(sql, provider, out _).ShouldNotBeNull();
[Theory]
[MemberData(nameof(Bypasses))]
public void Check_refusesTheBypass_withoutAProvider_andForOdbc(SqlProvider provider, string sql)
{
_ = provider;
SqlReadOnlyStatement.Check(sql, out _).ShouldNotBeNull();
SqlReadOnlyStatement.Check(sql, SqlProvider.Odbc, out _).ShouldNotBeNull();
}
/// <summary>Positive controls: plain reads each dialect writes every day still pass — the guard did not just get stricter everywhere.</summary>
[Theory]
[InlineData(SqlProvider.SqlServer, "SELECT [it's], [a]]b], [update] FROM t WHERE x = @x")]
[InlineData(SqlProvider.SqlServer, "SELECT 'C:\\temp\\' AS path FROM t")] // no backslash escapes in T-SQL
[InlineData(SqlProvider.SqlServer, "SELECT a FROM #staging -- note\r\nWHERE 1 = 1")]
[InlineData(SqlProvider.Postgres, "SELECT a::text, arr[1], a$b FROM t WHERE x = @x AND y = $1")]
[InlineData(SqlProvider.Postgres, "SELECT 'it''s' AS v, \"Mixed Case\" FROM t /* note */")]
[InlineData(SqlProvider.MySql, "SELECT `delete`, `a``b` FROM t -- note\nWHERE x = @x # trailing")]
[InlineData(SqlProvider.MySql, "SELECT 'it''s', \"x\" FROM t;")]
[InlineData(SqlProvider.Oracle, "SELECT serial#, sid FROM v$session WHERE username = :p_user")]
[InlineData(SqlProvider.Oracle, "SELECT /*+ INDEX(t) */ 'C:\\temp' FROM t")]
public void Check_acceptsAnOrdinaryRead_inItsDialect(SqlProvider provider, string sql)
=> SqlReadOnlyStatement.Check(sql, provider, out _).ShouldBeNull();
[Theory]
[InlineData(SqlProvider.MySql, "SELECT 'C:\\temp' AS path")]
[InlineData(SqlProvider.Postgres, "SELECT 'C:\\temp' AS path")]
[InlineData(SqlProvider.Postgres, "SELECT $$text$$ AS v")]
[InlineData(SqlProvider.MySql, "SELECT 1 --comment")]
public void Check_refusesWhatItWillNotModel_withAReasonNamingTheConstruct(SqlProvider provider, string sql)
{
var problem = SqlReadOnlyStatement.Check(sql, provider, out _).ShouldNotBeNull();
problem.ShouldNotContain("more than one statement"); // the reason is the construct, not a downstream symptom
}
[Fact]
public void Check_withoutAProvider_requiresEveryDialectToAgree()
{
// A T-SQL bracket identifier is not a quote to PostgreSQL / MySQL / Oracle, which then read UPDATE as a keyword.
SqlReadOnlyStatement.Check("SELECT [update] FROM t", SqlProvider.SqlServer, out _).ShouldBeNull();
var problem = SqlReadOnlyStatement.Check("SELECT [update] FROM t", out _).ShouldNotBeNull();
problem.ShouldContain("every supported dialect");
SqlReadOnlyStatement.Check("SELECT a FROM t WHERE x = ?", SqlProvider.Odbc, out var normalised).ShouldBeNull();
normalised.ShouldBe("SELECT a FROM t WHERE x = ?");
}
[Theory]
[InlineData(SqlProvider.Postgres, "SELECT a FROM t WHERE x = @line", "@line", true)]
[InlineData(SqlProvider.Postgres, "SELECT a FROM t WHERE x = $$@line$$", "@line", false)] // unlexable ⇒ not "used"
[InlineData(SqlProvider.MySql, "SELECT a FROM t # @line\nWHERE 1 = 1", "@line", false)] // inside a MySQL comment
[InlineData(SqlProvider.SqlServer, "SELECT a FROM t # @line\nWHERE 1 = 1", "@line", true)] // # is not a comment there
public void UsesMarker_lexesAsTheProvider(SqlProvider provider, string sql, string marker, bool expected)
=> SqlReadOnlyStatement.UsesMarker(sql, marker, provider).ShouldBe(expected);
[Fact]
public void ReplaceMarkers_rewritesOnlyRealTokens_andLeavesLiteralsAndCommentsAlone()
{
const string sql = "SELECT a, '@x' AS lit FROM t WHERE x = @x AND y = @xy AND z = @X -- @x\n AND w = @x";
var rewritten = SqlReadOnlyStatement.ReplaceMarkers(sql, SqlProvider.Postgres, ["@x", "@xy"], ["$1", "$2"]);
rewritten.ShouldBe("SELECT a, '@x' AS lit FROM t WHERE x = $1 AND y = $2 AND z = $1 -- @x\n AND w = $1");
}
[Fact]
public void ReplaceMarkers_refusesAStatementItCannotLex()
=> Should.Throw<InvalidOperationException>(() =>
SqlReadOnlyStatement.ReplaceMarkers("SELECT $$x$$ WHERE a = @a", SqlProvider.Postgres, ["@a"], ["$1"]));
[Fact]
public void CountPositionalMarkers_isMinusOne_whenDialectsDisagree()
{
SqlReadOnlyStatement.CountPositionalMarkers("SELECT a FROM t WHERE x = ? AND y = '?'").ShouldBe(1);
// MySQL reads "# ?" as a comment; SQL Server reads a marker.
SqlReadOnlyStatement.CountPositionalMarkers("SELECT a FROM t WHERE x = ? # ?\n").ShouldBe(-1);
}
[Fact]
public void Describe_usesTheProvidersLexicon()
{
var query = new SqlNamedQueryDto { Sql = "SELECT 'C:\\temp' AS p" };
SqlNamedQueryRules.Describe("q", query, SqlProvider.SqlServer).ShouldBeNull();
SqlNamedQueryRules.Describe("q", query, SqlProvider.MySql).ShouldNotBeNull().ShouldContain("backslash");
}
}
@@ -173,9 +173,40 @@ public sealed class SqlWriteModeTests
}
[Fact]
public void Update_withoutStamp_isByteIdenticalToTheOriginalStatement()
public void Update_withoutStamp_isTheOriginalStatement_plusTheOwnRowCountCapture()
=> Plan(KvTag(null, ts: "ts"), new SqlServerDialect()).SqlText
.ShouldBe("UPDATE [plant].[sp] SET [val] = @v WHERE [tag] = @k");
.ShouldBe("UPDATE [plant].[sp] SET [val] = @v WHERE [tag] = @k; SET @rc = @@ROWCOUNT;");
/// <summary>
/// lmxopcua#987 (S-10): SQL Server table writes read the target statement's own @@ROWCOUNT through an output
/// parameter, because SqlClient's ExecuteNonQuery count also sums trigger DML. A procedure keeps its own count
/// (none is captured), and the dialects whose count is already the statement's capture nothing.
/// </summary>
[Theory]
[InlineData(SqlWriteMode.Update)]
[InlineData(SqlWriteMode.Insert)]
[InlineData(SqlWriteMode.Upsert)]
public void TableWrites_onSqlServer_captureTheStatementsOwnRowCount(SqlWriteMode mode)
{
var plan = Plan(KvTag(new SqlWriteSpec(mode)), new SqlServerDialect());
plan.SqlText.ShouldEndWith("; SET @rc = @@ROWCOUNT;");
plan.SqlText.ShouldNotContain(";;");
plan.RowCountBindName.ShouldBe("@rc");
plan.ParameterBindNames.ShouldNotContain("@rc"); // an OUTPUT parameter, bound by the executor, not a value
}
[Theory]
[InlineData(SqlProvider.Postgres)]
[InlineData(SqlProvider.MySql)]
[InlineData(SqlProvider.Oracle)]
[InlineData(SqlProvider.Odbc)]
public void TableWrites_elsewhere_trustTheProvidersCount(SqlProvider provider)
=> Plan(KvTag(new SqlWriteSpec(SqlWriteMode.Update)), SqlDialects.TryCreate(provider)!).RowCountBindName.ShouldBeNull();
[Fact]
public void Procedure_onSqlServer_capturesNoRowCount()
=> Plan(ProcTag(), new SqlServerDialect()).RowCountBindName.ShouldBeNull();
[Fact]
public void Insert_keyValue_insertsKeyValueAndStamp_inColumnOrder()
@@ -194,7 +225,7 @@ public sealed class SqlWriteModeTests
var plan = Plan(tag, new SqlServerDialect());
plan.SqlText.ShouldBe("INSERT INTO [hist] ([temp], [sample_ts]) VALUES (@v, @t)");
plan.SqlText.ShouldBe("INSERT INTO [hist] ([temp], [sample_ts]) VALUES (@v, @t); SET @rc = @@ROWCOUNT;");
plan.ParameterBindNames.ShouldBe(["@v", "@t"]);
}
@@ -206,7 +237,7 @@ public sealed class SqlWriteModeTests
plan.SqlText.ShouldBe(
"MERGE INTO [plant].[sp] WITH (HOLDLOCK) AS tgt USING (SELECT 1 AS one) AS src ON tgt.[tag] = @k " +
"WHEN MATCHED THEN UPDATE SET [val] = @v, [ts] = @t " +
"WHEN NOT MATCHED THEN INSERT ([tag], [val], [ts]) VALUES (@k, @v, @t);");
"WHEN NOT MATCHED THEN INSERT ([tag], [val], [ts]) VALUES (@k, @v, @t); SET @rc = @@ROWCOUNT;");
plan.ParameterBindNames.ShouldBe(["@k", "@v", "@t"]);
plan.Parameters.ShouldBe(["L1", 5.5, Now]);
plan.MaxRowsAffected.ShouldBe(1);
@@ -48,8 +48,10 @@ public sealed class SqlWriteTests
SqlWritePlanner.TryPlan(tag, 12.5, new SqlServerDialect(), out var plan).ShouldBe(SqlStatusCodes.Good);
plan!.SqlText.ShouldBe("UPDATE [dbo].[TagValues] SET [num_value] = @v WHERE [tag_name] = @k");
// The trailing capture is SQL Server's own-statement row count (#987): the command-level count includes trigger DML.
plan!.SqlText.ShouldBe("UPDATE [dbo].[TagValues] SET [num_value] = @v WHERE [tag_name] = @k; SET @rc = @@ROWCOUNT;");
plan.ParameterBindNames.ShouldBe(["@v", "@k"]);
plan.RowCountBindName.ShouldBe("@rc");
plan.Parameters.ShouldBe([12.5, "Line1.Speed"]);
}
@@ -137,25 +137,38 @@ public sealed class SqlDriverFormContractTests
/// on one side only breaks this test.
/// </summary>
[Theory]
[InlineData("""{"q":{"sql":"SELECT a FROM t WHERE x = @x","params":{"x":1}}}""", true)]
[InlineData("""{"q":{"sql":"WITH l AS (SELECT a FROM t) SELECT a FROM l;","maxRows":10}}""", true)]
[InlineData("""{"q":{"sql":"UPDATE t SET a = 1"}}""", false)]
[InlineData("""{"q":{"sql":"SELECT a INTO t2 FROM t"}}""", false)]
[InlineData("""{"q":{"sql":"SELECT 1; SELECT 2"}}""", false)]
[InlineData("""{"q":{"sql":"SELECT a FROM t","maxRows":0}}""", false)]
[InlineData("""{"q":{"sql":"SELECT a FROM t WHERE x = @x","params":{"x":{"nested":1}}}}""", false)]
[InlineData("""{"q":{"sql":""}}""", false)]
public void Form_queries_editor_and_factory_agree(string queriesJson, bool accepted)
[InlineData(SqlProvider.SqlServer, """{"q":{"sql":"SELECT a FROM t WHERE x = @x","params":{"x":1}}}""", true)]
[InlineData(SqlProvider.SqlServer, """{"q":{"sql":"WITH l AS (SELECT a FROM t) SELECT a FROM l;","maxRows":10}}""", true)]
[InlineData(SqlProvider.SqlServer, """{"q":{"sql":"UPDATE t SET a = 1"}}""", false)]
[InlineData(SqlProvider.SqlServer, """{"q":{"sql":"SELECT a INTO t2 FROM t"}}""", false)]
[InlineData(SqlProvider.SqlServer, """{"q":{"sql":"SELECT 1; SELECT 2"}}""", false)]
[InlineData(SqlProvider.SqlServer, """{"q":{"sql":"SELECT a FROM t","maxRows":0}}""", false)]
[InlineData(SqlProvider.SqlServer, """{"q":{"sql":"SELECT a FROM t WHERE x = @x","params":{"x":{"nested":1}}}}""", false)]
[InlineData(SqlProvider.SqlServer, """{"q":{"sql":""}}""", false)]
// lmxopcua#974: the statement is lexed as the provider's own dialect — on both sides.
[InlineData(SqlProvider.SqlServer, """{"q":{"sql":"SELECT 'C:\\temp' AS p"}}""", true)]
[InlineData(SqlProvider.MySql, """{"q":{"sql":"SELECT 'C:\\temp' AS p"}}""", false)]
[InlineData(SqlProvider.MySql, """{"q":{"sql":"SELECT '\\'' ; COMMIT; DELETE FROM t; -- '"}}""", false)]
[InlineData(SqlProvider.Postgres, """{"q":{"sql":"SELECT $$'$$; COMMIT; DROP TABLE t; --'"}}""", false)]
[InlineData(SqlProvider.Postgres, """{"q":{"sql":"SELECT a::text FROM t WHERE x = @x","params":{"x":1}}}""", true)]
[InlineData(SqlProvider.SqlServer, """{"q":{"sql":"SELECT [update] FROM t"}}""", true)]
[InlineData(SqlProvider.Postgres, """{"q":{"sql":"SELECT [update] FROM t"}}""", false)]
public void Form_queries_editor_and_factory_agree(SqlProvider provider, string queriesJson, bool accepted)
{
var formError = SqlDriverForm.FormModel.TryParseQueries(queriesJson, out _);
var formError = SqlDriverForm.FormModel.TryParseQueries(queriesJson, provider, out _);
(formError is null).ShouldBe(accepted, formError);
var envVar = SqlConnectionStringResolver.EnvironmentVariableFor("AdminUiFormTest");
var previous = Environment.GetEnvironmentVariable(envVar);
Environment.SetEnvironmentVariable(envVar, "Server=localhost;Database=Test;Trusted_Connection=True;");
Environment.SetEnvironmentVariable(envVar, provider switch
{
SqlProvider.Postgres => "Host=localhost;Database=Test;Username=u;Password=p",
SqlProvider.MySql => "Server=localhost;Database=Test;User ID=u;Password=p",
_ => "Server=localhost;Database=Test;Trusted_Connection=True;",
});
try
{
var blob = $$"""{"provider":"SqlServer","connectionStringRef":"AdminUiFormTest","queries":{{queriesJson}}}""";
var blob = $$"""{"provider":"{{provider}}","connectionStringRef":"AdminUiFormTest","queries":{{queriesJson}}}""";
if (accepted) { SqlDriverFactoryExtensions.CreateInstance("adminui-form-test", blob).ShouldNotBeNull(); }
else
{
@@ -208,4 +221,21 @@ public sealed class SqlDriverFormContractTests
var json = JsonSerializer.Serialize(form.ToDto(), FormOptions);
json.ShouldContain("\"queries\":{\"q\":{\"sql\":\"SELECT a FROM t\"}}");
}
/// <summary>
/// lmxopcua#974: a statement can be a plain read in one dialect and ambiguous in another, so re-validating the
/// queries text under the newly chosen provider (what the Provider dropdown's change handler does) surfaces it.
/// </summary>
[Fact]
public void Queries_are_revalidated_for_the_newly_chosen_provider()
{
var form = new SqlDriverForm.FormModel { Provider = SqlProvider.SqlServer, ConnectionStringRef = "R" };
form.SetQueriesJson("""{"q":{"sql":"SELECT 'C:\\temp' AS p"}}""");
form.QueriesError.ShouldBeNull();
form.Provider = SqlProvider.MySql;
form.SetQueriesJson(form.QueriesJson);
form.QueriesError.ShouldNotBeNull().ShouldContain("backslash");
}
}