Files
lmxopcua/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql.Dialect/ISqlDialect.cs
T
Joseph Doherty 65c4330a68 fix(sql): #974 #987 named queries are lexed per dialect and run read-only + single-statement; key rows attribute by server semantics; SQL Server writes count only the target statement
#974 (S-7) — the named-query guard had one lexer for five dialects and took live SQL for literal text
where a provider ends a literal earlier (MySQL backslash escapes, PostgreSQL dollar quotes, T-SQL ]],
nested comments, MySQL # / "--x", bare-CR line comments, Oracle q'..'). All 13 bypass strings were
accepted; the MySQL and PostgreSQL ones were executed against the live fixtures and the smuggled
UPDATE committed past the always-rolled-back transaction.
- SqlReadOnlyStatement (own file) lexes per provider and REFUSES constructs dialects disagree on;
  Odbc / no provider = every dialect must agree. Factory and AdminUI form pass the provider; the form
  re-validates queries on a provider change.
- ISqlDialect.BeginNamedQueryAsync / SealNamedQueryCommand / EndNamedQueryAsync: PostgreSQL and Oracle
  SET TRANSACTION READ ONLY; MySQL read-only session + transaction (restored after); PostgreSQL rewrites
  @name markers to positional $n (a parameterless query gets one unused typed $1) so Npgsql sends the
  text unsplit and the server refuses a second statement.

#987 (S-6) — key-value rows are attributed by SqlKeyMatcher (exact, then typed / padding-insensitive,
then case/accent-insensitive — only for rows the server matched); a named query's rowKey uses the
exact + representational stages only.
#987 (S-10) — SQL Server table writes read the target statement's own @@ROWCOUNT through an OUTPUT
parameter; SqlClient's ExecuteNonQuery sums trigger DML (reproduced: 1 + 2 audit rows = 3, every write
rolled back BadConfigurationError).

Tests: per-dialect bypass theory + positive controls, matcher + SQLite collation/affinity attribution,
Postgres seal, dialect-hook wiring, SQL Server write-plan capture; live NamedQueryBypassLiveTests
(PG/MySQL/Oracle), SqlServerTriggerWriteLiveTests, MySQL writing-function now refused.
2026-12-03 10:33:45 -05:00

360 lines
24 KiB
C#

using System.Data.Common;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Driver.Sql.Contracts;
namespace ZB.MOM.WW.OtOpcUa.Driver.Sql;
/// <summary>
/// The provider seam (design §2.2). ADO.NET's <see cref="System.Data.Common"/> base types abstract
/// connections, commands, parameters and readers; they do <b>not</b> abstract the four things that differ
/// per backend — <b>identifier quoting</b>, the <b>metadata-catalog SQL</b>, <b>row-limit syntax</b>, and
/// the <b>per-command bind-parameter ceiling</b>. Those live here, so no dialect assumption leaks into the
/// reader, the poll planner, or the schema browser.
/// <para><b>This interface is the driver's SQL-injection boundary.</b> Every runtime <em>value</em> is
/// bound as a <see cref="DbParameter"/> and never reaches a command text. Identifiers cannot be
/// parameterized in SQL, so the few that must appear as text are emitted through
/// <see cref="QuoteIdentifier"/>. Any code path that builds SQL by concatenating an authored tag field
/// <em>without</em> going through <see cref="QuoteIdentifier"/> is a defect (design §8.1).</para>
/// <para><b>Quoting is the backstop, not the only defence.</b> Design §8.1's catalog gate is
/// implemented: <c>SqlCatalogGate</c> resolves every authored table/column against the live
/// catalog at Initialize and <b>replaces it with the catalog's own spelling</b>, so an identifier
/// reaching <see cref="QuoteIdentifier"/> on the poll path is a string this driver read back out of
/// <see cref="ListSchemasSql"/> / <see cref="ListTablesSql"/> / <see cref="ListColumnsSql"/> — not
/// operator input. An identifier that resolves to nothing rejects its tag (which then publishes
/// <c>BadNodeIdUnknown</c>) rather than being quoted into a query against a nonexistent object.</para>
/// <para>Public because <c>Driver.Sql.Browser</c> consumes it — the catalog SQL <em>is</em> the browse
/// engine, so it is shared rather than duplicated. Implementations own their provider package;
/// <b>no provider-specific type appears in this signature</b> (<see cref="Factory"/> is the abstract
/// <see cref="DbProviderFactory"/>).</para>
/// </summary>
public interface ISqlDialect
{
/// <summary>
/// Which backend this dialect speaks. One implementation ships per constructed
/// <see cref="SqlProvider"/> member — <see cref="SqlProvider.SqlServer"/>,
/// <see cref="SqlProvider.Postgres"/> and <see cref="SqlProvider.Oracle"/>.
/// </summary>
SqlProvider Provider { get; }
/// <summary>
/// The provider's factory singleton, used to create connections/commands/parameters. Deliberately the
/// abstract base type so consumers never bind to a concrete provider package.
/// </summary>
DbProviderFactory Factory { get; }
/// <summary>
/// Quotes <b>one</b> identifier part so it can be safely embedded in a command text, escaping the
/// dialect's own quote character. Rejects anything that cannot be a real catalog identifier rather
/// than emitting it.
/// <para><b>One part only.</b> A multi-part name such as <c>dbo.TagValues</c> must be split by the
/// caller and each part quoted separately; passing the dotted form yields a single (nonexistent)
/// identifier — safe, but not what the caller meant.</para>
/// </summary>
/// <param name="ident">The bare, unquoted identifier — as returned by the catalog, not pre-quoted.</param>
/// <returns>The quoted identifier, ready to concatenate into a command text.</returns>
/// <exception cref="ArgumentException">The value cannot be a valid catalog identifier.</exception>
string QuoteIdentifier(string ident);
/// <summary>
/// The token that stands for a bound parameter <b>in the command text</b> — <c>"@k0"</c> for
/// SqlClient/Npgsql, <c>":p_k0"</c> for ODP.NET — given the caller's bare base name (<c>"k0"</c>,
/// <c>"w"</c>, <c>"schema"</c>).
/// <para><b>Why the marker and the bind name are two members.</b> They are the same string on every
/// provider but Oracle, where the SQL text carries <c>:p_schema</c> while
/// <see cref="DbParameter.ParameterName"/> is the bare <c>schema</c>. Modelling one and deriving the
/// other means a call site guessing at a convention it does not own — the exact defect this seam
/// exists to prevent, and one that surfaces as a runtime bind failure (or, worse under
/// bind-by-position, as a <em>silently mis-bound value</em>) rather than a compile error.</para>
/// <para>The base name is caller-owned and never operator input: the poll planner mints
/// <c>k0…kN</c>/<c>w</c>, the catalog path uses <c>schema</c>/<c>table</c>. Authored <em>values</em>
/// ride the parameter; authored <em>identifiers</em> go through <see cref="QuoteIdentifier"/>. Nothing
/// else reaches a command text.</para>
/// </summary>
/// <param name="baseName">The bare base name, without any provider prefix.</param>
/// <returns>The marker to embed in the SQL text.</returns>
string ParameterMarker(string baseName);
/// <summary>
/// The value to assign to <see cref="DbParameter.ParameterName"/> for the same
/// <paramref name="baseName"/> — <c>"@k0"</c> for SqlClient-style providers (which expect the marker
/// verbatim), the bare <c>"k0"</c> for ODP.NET-style ones (whose documented convention is a
/// prefix-less bind name).
/// <para>Always paired with <see cref="ParameterMarker"/> over the <em>same</em> base name: a plan
/// carries both lists and every binding site <b>copies</b> them index-for-index rather than
/// re-deriving either from the other.</para>
/// </summary>
/// <param name="baseName">The bare base name, without any provider prefix.</param>
/// <returns>The parameter name to bind under.</returns>
string ParameterBindName(string baseName);
/// <summary>
/// Applies provider-specific setup to a freshly created <see cref="DbCommand"/>, <b>before</b> its
/// parameters are added or it is executed. A no-op for providers that need none.
/// <para><b>Oracle uses this to set <c>OracleCommand.BindByName = true</c></b>, and that call is the
/// sharpest correctness edge on this seam: ODP.NET binds <em>by position</em> by default, so a
/// multi-parameter statement (the planner's <c>IN (:p_k0, :p_k1, …)</c> list, the catalog path's
/// <c>schema</c> + <c>table</c> pair) would bind values to the wrong markers whenever the parameter
/// order and the marker order differ — publishing one tag's value onto another tag's node with no
/// error anywhere. Every command that carries parameters — the poll path, the catalog path, the
/// browse path — therefore calls this immediately after <c>CreateCommand()</c> and <b>before</b> the
/// first parameter is added. (Bind mode cannot affect a parameterless statement, so the liveness
/// ones are indifferent: <c>SqlDriverProbe</c> calls it anyway for uniformity,
/// <c>SqlDriver.PingAsync</c> does not.)</para>
/// <para>Implementations must tolerate <em>any</em> <see cref="DbCommand"/> they are handed: the
/// driver can be pointed at an instrumented or substituted factory, so a dialect that casts to its own
/// provider type must do so defensively rather than throwing.</para>
/// </summary>
/// <param name="command">The command to configure.</param>
void ConfigureCommand(DbCommand command);
/// <summary>
/// Gives the dialect a chance to adjust a poll-path parameter after its name and value are set and
/// before it is added to the command. Authored key / row-selector values are CLR strings,
/// because a tag's <c>keyValue</c> is configuration text — which a strictly-typed provider will not
/// compare against a numeric key column (Npgsql sends <c>text</c>, and
/// <c>integer = text</c> has no operator). A dialect that needs the server to infer the type from
/// context overrides this. The default does nothing, which is correct for providers that coerce
/// implicitly (SQL Server, ODP.NET).
/// <para>Implementations must tolerate any <see cref="DbParameter"/> they are handed, for the same
/// substituted-factory reason as <see cref="ConfigureCommand"/>.</para>
/// </summary>
/// <param name="parameter">The parameter, with <see cref="DbParameter.ParameterName"/> and value already set.</param>
/// <param name="value">The authored value being bound (never <see cref="DBNull"/>; may be <c>null</c>).</param>
void ConfigureParameter(DbParameter parameter, object? value) { }
/// <summary>
/// The most bound parameters this backend accepts in <b>one</b> command — 2098 usable of SQL Server's
/// 2100, 1000 entries in an Oracle <c>IN</c> expression list, 65535 on the Postgres wire protocol.
/// Callers that build a variable-length parameter list must chunk at this number.
/// <para><b>Why it belongs on the seam.</b> It differs per backend exactly as quoting, catalog SQL and
/// row-limit syntax do, and a call site that guesses a provider limit it does not own is the defect
/// this interface exists to prevent. Its absence was a shipped one: <c>SqlGroupPlanner</c> emitted one
/// parameter per distinct <c>keyValue</c> with no bound, so a key-value (EAV) group above the cap was
/// rejected by the provider <em>after</em> the connection opened and every tag in it published
/// <c>BadCommunicationError</c> on every poll, permanently.</para>
/// <para><b>The number is a ceiling on what the planner may emit, not the raw provider constant</b> —
/// a dialect whose provider spends parameters of its own subtracts them here, so a caller filling the
/// value exactly always produces an executable command. Must be at least 1; a dialect reporting less
/// is rejected at the call site rather than looping or emitting an empty <c>IN ()</c>.</para>
/// </summary>
int MaxBindParameters { get; }
/// <summary>Cheapest statement that proves the connection is alive (<c>SELECT 1</c>; Oracle needs <c>FROM DUAL</c>).</summary>
string LivenessSql { get; }
/// <summary>
/// The fragment that goes <b>immediately after <c>SELECT</c></b> to limit a statement to one row —
/// T-SQL's <c>"TOP 1 "</c>. Empty for a dialect that spells the limit at the end of the statement (see
/// <see cref="SingleRowLimitSuffix"/>).
/// <para><b>Include the trailing space</b> when non-empty: the planner concatenates
/// <c>"SELECT " + SingleRowLimitPrefix + columns</c> with no separator of its own, so an empty fragment
/// must leave the statement byte-identical to an unlimited one.</para>
/// </summary>
/// <remarks>
/// <para><b>Why a prefix/suffix pair rather than one <c>ApplyRowLimit(sql, n)</c> method.</b> The two
/// spellings sit at opposite ends of the statement — SQL Server writes
/// <c>SELECT TOP 1 … ORDER BY … DESC</c>, while SQLite/Postgres/MySQL write
/// <c>SELECT … ORDER BY … DESC LIMIT 1</c>. A single method taking the SELECT list could only serve the
/// prefix position; a single method taking the whole statement would move statement assembly out of the
/// planner and into every dialect. Two fragments keep the planner the sole author of statement shape
/// and let each dialect fill in the end it uses.</para>
/// <para><b>Why "single row" rather than a row count.</b> The only limit v1 emits is the wide-row
/// <c>topByTimestamp</c> selector's newest-row pick. Modelling an arbitrary <c>n</c> would be untested
/// surface, and <c>FETCH FIRST</c>/<c>ROWNUM</c> dialects need more than a substituted number anyway.
/// Widen this to a method when a feature actually needs <c>n &gt; 1</c>.</para>
/// </remarks>
string SingleRowLimitPrefix { get; }
/// <summary>
/// The fragment appended to the <b>very end</b> of a statement to limit it to one row —
/// <c>" LIMIT 1"</c> for SQLite/Postgres/MySQL. Empty for a dialect that limits after <c>SELECT</c>
/// (see <see cref="SingleRowLimitPrefix"/>).
/// <para><b>Include the leading space</b> when non-empty, for the same reason the prefix carries a
/// trailing one: the planner appends it directly to the finished statement.</para>
/// <para>Exactly one of the two fragments is non-empty in every dialect modelled so far, but the planner
/// emits <b>both</b> unconditionally — a dialect needing both ends (or neither) is expressible without
/// touching the call site.</para>
/// </summary>
string SingleRowLimitSuffix { get; }
/// <summary>
/// The <see cref="SingleRowLimitPrefix"/> position's fragment for an <paramref name="rows"/>-row limit —
/// T-SQL's <c>"TOP (n) "</c>; empty for a dialect that limits at the end. Same trailing-space rule.
/// </summary>
/// <remarks>
/// Added for the key-value / where-pair row cap (R06:S-1): those plans used to carry no limit, so an
/// ambiguous selector against a history table materialised every matching row on every poll. The
/// planner asks for <c>N + 1</c> rows — one more than the plan can use — so ambiguity stays observable
/// (the reader sees the extra row and publishes a configuration error) without unbounded reads.
/// </remarks>
/// <param name="rows">The row limit; at least 1.</param>
/// <returns>The fragment, possibly empty.</returns>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="rows"/> is below 1.</exception>
string RowLimitPrefix(int rows);
/// <summary>
/// The <see cref="SingleRowLimitSuffix"/> position's fragment for an <paramref name="rows"/>-row limit —
/// <c>" LIMIT n"</c> / <c>" FETCH FIRST n ROWS ONLY"</c>; empty for a dialect that limits after
/// <c>SELECT</c>. Same leading-space rule. See <see cref="RowLimitPrefix"/>.
/// </summary>
/// <param name="rows">The row limit; at least 1.</param>
/// <returns>The fragment, possibly empty.</returns>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="rows"/> is below 1.</exception>
string RowLimitSuffix(int rows);
/// <summary>Catalog query listing schemas — the browser's <c>RootAsync</c> level. Takes no parameters.</summary>
string ListSchemasSql { get; }
/// <summary>
/// Scalar query returning the schema an <b>unqualified</b> object name resolves to for the connecting
/// principal — T-SQL's <c>SELECT SCHEMA_NAME()</c>. Takes no parameters.
/// </summary>
/// <remarks>
/// <para>Needed by <c>SqlCatalogGate</c>: a tag authored as <c>TagValues</c> rather than
/// <c>dbo.TagValues</c> has to be looked up in <em>some</em> schema, and guessing <c>dbo</c> would be a
/// silent lie on any estate that maps its service accounts to their own default schema. Asking the
/// server is the only answer that matches how the poll query itself will resolve the name.</para>
/// <para>It is a <em>query</em> rather than a name because the answer is per-connection, not per-dialect
/// — the same dialect resolves differently for two different logins.</para>
/// </remarks>
string DefaultSchemaSql { get; }
/// <summary>
/// Catalog query listing tables + views in one schema — the browser's schema-expand level. Carries one
/// parameter under the base name <c>schema</c>, spelled with this dialect's own
/// <see cref="ParameterMarker"/> (<c>@schema</c> on SqlClient, <c>:p_schema</c> on ODP.NET); callers bind
/// it under <see cref="ParameterBindName"/> of the same base name.
/// </summary>
string ListTablesSql { get; }
/// <summary>
/// Catalog query listing columns of one table — the browser's table-expand / attributes level. Carries
/// parameters under the base names <c>schema</c> and <c>table</c>, spelled and bound exactly as
/// <see cref="ListTablesSql"/> describes.
/// </summary>
string ListColumnsSql { get; }
/// <summary>
/// Folds a catalog data-type family name (as <c>INFORMATION_SCHEMA.COLUMNS.DATA_TYPE</c> reports it —
/// e.g. <c>nvarchar</c>, never <c>nvarchar(50)</c>) onto a <see cref="DriverDataType"/>.
/// <para>Must <b>never throw</b>: a browse over a table holding one exotic column must still render.
/// An unrecognised family falls back to <see cref="DriverDataType.String"/>.</para>
/// </summary>
/// <param name="sqlDataType">The bare SQL type family name; matched case-insensitively.</param>
/// <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>
/// Whether this dialect executes <paramref name="mode"/>. Defaults to the shared
/// <see cref="SqlWriteSupport"/> table for <see cref="Provider"/> — the same table the deploy gate checks, so
/// a mode deploy accepts is a mode the driver serves.
/// </summary>
/// <param name="mode">The tag's write mode.</param>
/// <returns>Whether a write in that mode is executed.</returns>
bool SupportsWriteMode(SqlWriteMode mode) => SqlWriteSupport.IsSupported(Provider, mode);
/// <summary>
/// The single-statement upsert of one keyed row, or null when this dialect has none. Every argument is
/// already dialect-quoted (identifiers) or a parameter marker — the dialect only arranges them, so nothing
/// authored and nothing a client sent reaches the text through here. A marker may appear more than once in
/// the result, so a positional-marker dialect must return null.
/// </summary>
/// <param name="quotedTable">The quoted, catalog-canonical target table.</param>
/// <param name="quotedKeyColumn">The quoted key column.</param>
/// <param name="keyMarker">The key's parameter marker.</param>
/// <param name="assignments">The quoted columns to set and their markers — the value first, then any stamp.</param>
/// <returns>The statement, or null when the dialect cannot upsert.</returns>
string? UpsertSql(
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".
/// </summary>
int UpsertMaxRowsAffected => 1;
/// <summary>
/// The statement that calls one stored procedure, or null when this dialect cannot. Arguments are passed by
/// name (<c>EXEC p @a = @v</c>, <c>CALL p(a => @v)</c>, <c>BEGIN p(a => :p_v); END;</c>) except where the
/// backend has no named notation (MySQL: positional, in list order). Parameter names reach the text
/// unquoted; the parser restricts them to a plain identifier charset.
/// </summary>
/// <param name="quotedProcedure">The quoted, catalog-canonical procedure name.</param>
/// <param name="arguments">Procedure parameter name → marker, in order.</param>
/// <returns>The statement, or null.</returns>
string? ProcedureCallSql(string quotedProcedure, IReadOnlyList<(string Parameter, string Marker)> arguments)
=> null;
/// <summary>
/// Catalog query listing the stored procedures in one schema (column <c>ROUTINE_NAME</c>, bound like
/// <see cref="ListTablesSql"/> under the base name <c>schema</c>), or null when this dialect has no routine
/// catalog — the catalog gate then refuses every Procedure-mode tag rather than quote an unvalidated name.
/// </summary>
string? ListRoutinesSql => null;
/// <summary>
/// Classifies a write's provider exception so a constraint the database enforced reads as an authoring /
/// data fault rather than "the database is unreachable". Must never throw. The default reads the ANSI
/// <see cref="DbException.SqlState"/> when the provider reports one.
/// </summary>
/// <param name="exception">What the write threw.</param>
/// <returns>The failure class.</returns>
SqlWriteFailure ClassifyWriteFailure(Exception exception)
=> SqlWriteFailures.FromSqlState((exception as DbException)?.SqlState);
}