diff --git a/.claude/rules/drivers.md b/.claude/rules/drivers.md
index 640e3cc3c..f9a3a5b8d 100644
--- a/.claude/rules/drivers.md
+++ b/.claude/rules/drivers.md
@@ -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
diff --git a/docs/drivers/Sql.md b/docs/drivers/Sql.md
index 8546d0372..65f824130 100644
--- a/docs/drivers/Sql.md
+++ b/docs/drivers/Sql.md
@@ -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
diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql.Contracts/SqlNamedQuery.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql.Contracts/SqlNamedQuery.cs
index f29cbba7b..5cdb4ebc1 100644
--- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql.Contracts/SqlNamedQuery.cs
+++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql.Contracts/SqlNamedQuery.cs
@@ -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 SELECT or WITH … SELECT. Parameter markers are written in
/// the provider's own spelling for each key (@name on SqlServer, Postgres
/// and MySql; :p_name on Oracle; positional ? on Odbc, in authored order). Checked by
- /// .
+ /// .
///
public string? Sql { get; init; }
@@ -62,21 +61,26 @@ public static class SqlNamedQueryRules
}
///
- /// Validates one named query's provider-independent shape — name, statement, parameter names and
- /// values, row ceiling — and returns the first problem, or 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 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.)
+ /// selects the dialect the statement is lexed as
+ /// (). Null — or
+ /// , whose backend is unknown — demands that every supported dialect read
+ /// it identically.
///
/// The queries key.
/// The entry.
+ /// The driver's provider, or null when unknown.
/// An operator-facing error, or null.
- 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;
}
}
-
-///
-/// The authoring-time read-only guard for a named query's SQL (design §5.4). It is a guard, not the
-/// boundary: the driver also runs every named query inside a transaction it always rolls back, and the
-/// connecting principal should hold SELECT only. The guard exists so an operator learns at
-/// construction — not from a database audit — that a statement is not a plain read.
-/// Rules, applied to the text outside string literals, quoted identifiers and comments:
-/// the statement begins with SELECT or WITH; it is a single statement (one trailing
-/// ; is tolerated and removed); and none of the data- or schema-changing keywords appears anywhere
-/// — which also refuses SELECT … INTO, FOR UPDATE and a data-modifying CTE.
-///
-public static class SqlReadOnlyStatement
-{
- ///
- /// Keywords that may not appear outside literals/comments in a named query. Statement-only keywords
- /// (COMMIT, BEGIN, …) are not listed: the single-statement + SELECT-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.
- ///
- private static readonly HashSet Forbidden = new(StringComparer.OrdinalIgnoreCase)
- {
- "INSERT", "UPDATE", "DELETE", "MERGE", "UPSERT", "DROP", "ALTER", "CREATE", "TRUNCATE",
- "EXEC", "EXECUTE", "CALL", "GRANT", "REVOKE", "DENY", "INTO", "COPY", "LOCK", "RENAME",
- };
-
- ///
- /// Checks and returns the problem, or when it is a single
- /// read-only statement. On success is the statement with surrounding
- /// whitespace and one trailing ; removed (ODP.NET refuses a trailing terminator).
- ///
- /// The authored statement.
- /// The statement to execute, when valid.
- /// An operator-facing error, or null.
- 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();
- 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;
- }
-
- /// The marker a positional provider (ODBC) spells every parameter with.
- public const string PositionalMarker = "?";
-
- /// Counts the positional ? markers outside literals and comments.
- /// The statement.
- /// The marker count.
- public static int CountPositionalMarkers(string sql)
- {
- ArgumentNullException.ThrowIfNull(sql);
- return StripLiteralsAndComments(sql).Count(ch => ch == '?');
- }
-
- ///
- /// True when appears in as a parameter token — outside
- /// literals and comments, and not as the prefix of a longer name (@line inside @lineId).
- ///
- /// The statement.
- /// The provider marker, e.g. @line or :p_line.
- /// True when the marker is used.
- 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;
- }
- }
-
- /// Replaces literal, quoted-identifier and comment content with spaces, keeping offsets.
- 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();
- }
-}
diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql.Contracts/SqlReadOnlyStatement.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql.Contracts/SqlReadOnlyStatement.cs
new file mode 100644
index 000000000..2b3d64780
--- /dev/null
+++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql.Contracts/SqlReadOnlyStatement.cs
@@ -0,0 +1,470 @@
+using System.Text;
+
+namespace ZB.MOM.WW.OtOpcUa.Driver.Sql.Contracts;
+
+///
+/// The authoring-time read-only guard for a named query's SQL (design §5.4). It is a guard, not the
+/// boundary: 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 ISqlDialect.BeginNamedQueryAsync) —
+/// and the connecting principal should hold SELECT only. The guard exists so an operator learns at
+/// construction — not from a database audit — that a statement is not a plain read.
+/// Rules, applied to the text outside string literals, quoted identifiers and comments:
+/// the statement begins with SELECT or WITH; it is a single statement (one trailing
+/// ; is tolerated and removed); and none of the data- or schema-changing keywords appears anywhere
+/// — which also refuses SELECT … INTO, FOR UPDATE and a data-modifying CTE.
+/// The lexer is dialect-aware, and refuses what it cannot read exactly as the server does
+/// (lmxopcua#974, review finding S-7). 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 SELECT '\'' ; COMMIT; DELETE … (MySQL backslash escape) and
+/// SELECT $$'$$; COMMIT; DROP … (PostgreSQL dollar quote) passed as one harmless SELECT, and
+/// the embedded COMMIT 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 refused rather than modelled: a backslash inside a MySQL / PostgreSQL literal,
+/// a PostgreSQL dollar quote, Oracle q'…' quoting, MySQL /*! … */ executable comments, a nested
+/// /* /* */ comment (SQL Server and PostgreSQL nest, the others do not), MySQL's -- without a
+/// following space, and a line comment ended by a bare carriage return. A statement whose provider is unknown
+/// (, or no provider at all) must lex identically under every dialect.
+///
+public static class SqlReadOnlyStatement
+{
+ ///
+ /// Keywords that may not appear outside literals/comments in a named query. Statement-only keywords
+ /// (COMMIT, BEGIN, …) are not listed: the single-statement + SELECT-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.
+ ///
+ private static readonly HashSet Forbidden = new(StringComparer.OrdinalIgnoreCase)
+ {
+ "INSERT", "UPDATE", "DELETE", "MERGE", "UPSERT", "DROP", "ALTER", "CREATE", "TRUNCATE",
+ "EXEC", "EXECUTE", "CALL", "GRANT", "REVOKE", "DENY", "INTO", "COPY", "LOCK", "RENAME",
+ };
+
+ /// What a masked literal's characters become: not whitespace, not an identifier character.
+ private const char LiteralMask = '\u0001';
+
+ /// The marker a positional provider (ODBC) spells every parameter with.
+ public const string PositionalMarker = "?";
+
+ ///
+ /// 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.
+ ///
+ 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];
+
+ /// The lexicons a statement must satisfy: its provider's own, or every one when the backend is unknown.
+ private static Lexicon[] LexiconsFor(SqlProvider? provider) => provider switch
+ {
+ SqlProvider.SqlServer => [SqlServer],
+ SqlProvider.Postgres => [Postgres],
+ SqlProvider.MySql => [MySql],
+ SqlProvider.Oracle => [Oracle],
+ _ => EveryDialect,
+ };
+
+ ///
+ /// Checks as every supported dialect reads it — the provider-independent form, used
+ /// when the backend is unknown. See .
+ ///
+ /// The authored statement.
+ /// The statement to execute, when valid.
+ /// An operator-facing error, or null.
+ public static string? Check(string? sql, out string normalised) => Check(sql, null, out normalised);
+
+ ///
+ /// Checks and returns the problem, or when it is a single
+ /// read-only statement as lexes it. On success is
+ /// the statement with surrounding whitespace and one trailing ; removed (ODP.NET refuses a trailing
+ /// terminator). A null provider, or , requires every supported dialect to
+ /// accept the statement and agree on where it ends.
+ ///
+ /// The authored statement.
+ /// The provider the statement runs on, or null when unknown.
+ /// The statement to execute, when valid.
+ /// An operator-facing error, or null.
+ 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";
+
+ /// The single-dialect check behind .
+ 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();
+ 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;
+ }
+
+ ///
+ /// Counts the positional ? markers outside literals and comments, under every dialect (the only
+ /// positional provider is ODBC, whose backend is unknown). Returns -1 when the dialects disagree or
+ /// one cannot lex the statement — never the case for a statement
+ /// accepted.
+ ///
+ /// The statement.
+ /// The marker count, or -1.
+ public static int CountPositionalMarkers(string sql) => CountPositionalMarkers(sql, null);
+
+ /// Counts the positional ? markers as lexes the statement (-1: unlexable / disagreement).
+ /// The statement.
+ /// The provider, or null when unknown.
+ /// The marker count, or -1.
+ 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;
+ }
+
+ ///
+ /// True when appears in as a parameter token under every
+ /// supported dialect — outside literals and comments, and not as the prefix of a longer name
+ /// (@line inside @lineId).
+ ///
+ /// The statement.
+ /// The provider marker, e.g. @line or :p_line.
+ /// True when the marker is used.
+ public static bool UsesMarker(string sql, string marker) => UsesMarker(sql, marker, null);
+
+ ///
+ /// True when appears in as a parameter token as
+ /// lexes it (every dialect, when null).
+ ///
+ /// The statement.
+ /// The provider marker, e.g. @line or :p_line.
+ /// The provider, or null when unknown.
+ /// True when the marker is used.
+ 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;
+ }
+
+ ///
+ /// Rewrites every parameter token of (outside literals and comments, as
+ /// lexes the statement) to the replacement at the same index, matching exactly
+ /// as does. Text inside literals and comments is
+ /// copied unchanged.
+ ///
+ /// The statement — one accepted.
+ /// The provider whose lexicon decides what is code.
+ /// The markers to replace, e.g. @line.
+ /// What each marker becomes, e.g. $1.
+ /// The rewritten statement.
+ /// The statement cannot be lexed as .
+ public static string ReplaceMarkers(
+ string sql, SqlProvider provider, IReadOnlyList markers, IReadOnlyList 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();
+ 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();
+ }
+
+ /// Where occurs in masked code as a whole parameter token.
+ private static List MarkerPositions(string code, string marker)
+ {
+ var positions = new List();
+ 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);
+
+ ///
+ /// Lexes as 's dialect and returns it with every comment
+ /// blanked to spaces and every literal / quoted identifier to (offsets kept) —
+ /// or the problem when the dialect reads a construct the guard will not model.
+ ///
+ 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;
+ }
+}
diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql.Dialect/ISqlDialect.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql.Dialect/ISqlDialect.cs
index 0fbe64710..f375802ca 100644
--- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql.Dialect/ISqlDialect.cs
+++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql.Dialect/ISqlDialect.cs
@@ -244,6 +244,45 @@ public interface ISqlDialect
/// The mapped driver data type, or when unrecognised.
DriverDataType MapColumnType(string sqlDataType);
+ // ---- named queries (lmxopcua#974) ----
+
+ ///
+ /// Opens the transaction an operator-authored named query () runs in. The
+ /// caller always rolls it back and then calls . A dialect makes it
+ /// read-only where its provider can, so the lexical guard (SqlReadOnlyStatement) is not the
+ /// only defence: PostgreSQL and Oracle SET TRANSACTION READ ONLY, MySQL a read-only session as well
+ /// as a read-only transaction (a smuggled COMMIT ends a transaction, not a session). The default —
+ /// SQL Server, Odbc — is a plain transaction, which still discards a transactional side effect.
+ /// Must tolerate any (a substituted factory): a dialect that needs its own
+ /// provider type falls back to the default for anything else.
+ ///
+ /// The open connection.
+ /// The poll's deadline.
+ /// The transaction the named query's command joins.
+ ValueTask BeginNamedQueryAsync(DbConnection connection, CancellationToken cancellationToken)
+ => connection.BeginTransactionAsync(cancellationToken);
+
+ ///
+ /// Last step before a named query's command executes — its text, transaction and parameters are all set.
+ /// A dialect whose provider can refuse a second statement at the protocol level does that here:
+ /// PostgreSQL rewrites the @name markers to positional $n, which makes Npgsql send the text
+ /// unsplit as one extended-protocol statement, so the server itself refuses anything after a ;.
+ /// The default does nothing. Same any-command tolerance as .
+ ///
+ /// The named query's command.
+ void SealNamedQueryCommand(DbCommand command)
+ {
+ }
+
+ ///
+ /// Undoes any session state 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.
+ ///
+ /// The connection the named query ran on.
+ /// A task that completes when the session is restored.
+ ValueTask EndNamedQueryAsync(DbConnection connection) => ValueTask.CompletedTask;
+
// ---- writes (lmxopcua#781 item 2) ----
///
@@ -270,6 +309,19 @@ public interface ISqlDialect
string quotedTable, string quotedKeyColumn, string keyMarker,
IReadOnlyList<(string QuotedColumn, string Marker)> assignments) => null;
+ ///
+ /// A statement appended to a table write (Update / Insert / Upsert) that stores the target statement's
+ /// own row count in the output parameter spelled — or null (the default)
+ /// to trust '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.
+ /// @@ROWCOUNT read right after the statement is the statement's own count (live-verified). PostgreSQL,
+ /// MySQL and Oracle report the target statement only.
+ ///
+ /// The marker of the Int32 output parameter the executor binds.
+ /// The suffix (including its leading separator), or null.
+ string? WriteRowCountCaptureSql(string outputMarker) => null;
+
///
/// The most rows an upsert may report touching for one key. 1 everywhere except MySQL, whose
/// ON DUPLICATE KEY UPDATE reports 2 for "updated an existing row".
diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql.Dialect/MySqlDialect.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql.Dialect/MySqlDialect.cs
index f1b086188..539f0f176 100644
--- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql.Dialect/MySqlDialect.cs
+++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql.Dialect/MySqlDialect.cs
@@ -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.
+ ///
+ // 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 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;
+ }
+ }
+
+ ///
+ // 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.
///
diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql.Dialect/OracleDialect.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql.Dialect/OracleDialect.cs
index f298989d1..5e0d63ec7 100644
--- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql.Dialect/OracleDialect.cs
+++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql.Dialect/OracleDialect.cs
@@ -94,6 +94,33 @@ public sealed class OracleDialect : ISqlDialect
if (command is OracleCommand oracle) oracle.BindByName = true;
}
+ ///
+ // 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 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;
+ }
+ }
+
///
// 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
diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql.Dialect/PostgresDialect.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql.Dialect/PostgresDialect.cs
index 2de193c87..266d4ac8c 100644
--- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql.Dialect/PostgresDialect.cs
+++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql.Dialect/PostgresDialect.cs
@@ -66,6 +66,66 @@ public sealed class PostgresDialect : ISqlDialect
npgsql.NpgsqlDbType = NpgsqlTypes.NpgsqlDbType.Unknown;
}
+ ///
+ // 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 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;
+ }
+ }
+
+ ///
+ // 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
diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql.Dialect/SqlServerDialect.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql.Dialect/SqlServerDialect.cs
index 43fee5306..5c7a53138 100644
--- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql.Dialect/SqlServerDialect.cs
+++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql.Dialect/SqlServerDialect.cs
@@ -225,6 +225,13 @@ public sealed class SqlServerDialect : ISqlDialect
// ---- writes (lmxopcua#781 item 2) ----
+ ///
+ // @@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;";
+
///
// 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
diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql/SqlDriver.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql/SqlDriver.cs
index 207ed3527..5ec4d567a 100644
--- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql/SqlDriver.cs
+++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql/SqlDriver.cs
@@ -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))
diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql/SqlDriverFactoryExtensions.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql/SqlDriverFactoryExtensions.cs
index 445b77fd9..91bbda729 100644
--- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql/SqlDriverFactoryExtensions.cs
+++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql/SqlDriverFactoryExtensions.cs
@@ -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();
var values = new List
- 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.
+ }
}
}
diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql/SqlWritePlanner.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql/SqlWritePlanner.cs
index 5669c0e6d..c3373d3cc 100644
--- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql/SqlWritePlanner.cs
+++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql/SqlWritePlanner.cs
@@ -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
/// , whose row count is the procedure's business.
///
+///
+/// When set, the bind name of an Int32 OUTPUT parameter the statement stores its own row count in
+/// () — read instead of ExecuteNonQuery's count, which on
+/// SQL Server also counts trigger DML (lmxopcua#987). Not one of .
+///
public sealed record SqlWritePlan(
string SqlText,
IReadOnlyList ParameterBindNames,
IReadOnlyList