feat(sql): authored write block — Update/Insert/Upsert/Procedure + timestamp stamp; ODBC scope + login docs (lmxopcua#781)
v2-ci / unit-tests (push) Has been cancelled

Item 2: a tag's optional `write` block picks the statement the driver builds from its own
catalog-validated identifiers (no authored SQL; values always bound):
- Update (default, unchanged back-compat UPDATE ... WHERE key; 0 rows = BadNoData)
- Insert (key+value[+stamp]; append for a WideRow topByTimestamp tag)
- Upsert: SQL Server MERGE WITH (HOLDLOCK), PostgreSQL INSERT ... ON CONFLICT, MySQL
  ON DUPLICATE KEY UPDATE (1-or-2 rows), Oracle MERGE from DUAL
- Procedure: named stored procedure resolved against the routine catalog by the catalog gate
  (INFORMATION_SCHEMA.ROUTINES / ALL_PROCEDURES), value/key/timestamp params by name (MySQL positional)
- stampTimestamp sets the tag's timestamp column to the write time (UTC)
Odbc serves Update/Insert only (shared SqlWriteSupport table). Constraint failures map to
BadEntryExists (unique) / BadOutOfRange (other integrity, data exception); everything else,
permission denied included, stays BadCommunicationError. WriteIdempotent stays false.
The parser refuses malformed blocks (strict keys/enums/param charset); DraftValidator emits
blocking SqlWriteBlockInvalid / SqlWriteModeUnsupported from the driver's own parse; the AdminUI
editor surfaces the same message.

Items 1 + 4 (docs/drivers/Sql.md): ODBC stays the ANSI SQL:2008 profile (native providers for
SQL Server/MySQL, DB2 unsupported) with an ops note on driver manager + vendor driver on every
Odbc and AdminUI host; read-only drivers require a SELECT-only login, writable drivers a login
limited to their write targets.

Tests: SqlWriteModeTests (parse, every dialect's SQL, gate, status map, SQLite end-to-end),
DraftValidatorSqlWriteBlockTests, AdminUI round-trip; live SqlWriteModesLiveTests on SQL Server,
PostgreSQL, MySQL, Oracle (seeds gain write_targets + set_target) and an Odbc write leg.

Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV
This commit is contained in:
Joseph Doherty
2026-11-09 22:56:21 -05:00
parent 2da58d0360
commit f5c30ed0ef
33 changed files with 2361 additions and 132 deletions
@@ -23,17 +23,23 @@ public sealed class SqlCatalog
/// <summary>Canonical <c>schema.table</c> → that relation's canonical column names.</summary>
private readonly IReadOnlyDictionary<string, IReadOnlyList<string>> _columnsByTable;
/// <summary>Stored procedures per canonical schema — loaded only for schemas a Procedure-mode tag names (lmxopcua#781).</summary>
private readonly IReadOnlyDictionary<string, IReadOnlyList<string>> _routinesBySchema;
/// <summary>Constructs a catalog snapshot.</summary>
/// <param name="defaultSchema">The schema an unqualified object name resolves to for this connection.</param>
/// <param name="schemas">Every schema the connection can see.</param>
/// <param name="tablesBySchema">Canonical schema → its tables/views.</param>
/// <param name="columnsByTable">Canonical <c>schema.table</c> → its columns.</param>
/// <param name="routinesBySchema">Canonical schema → its stored procedures; null ⇒ none loaded.</param>
internal SqlCatalog(
string defaultSchema,
IReadOnlyList<string> schemas,
IReadOnlyDictionary<string, IReadOnlyList<string>> tablesBySchema,
IReadOnlyDictionary<string, IReadOnlyList<string>> columnsByTable)
IReadOnlyDictionary<string, IReadOnlyList<string>> columnsByTable,
IReadOnlyDictionary<string, IReadOnlyList<string>>? routinesBySchema = null)
{
_routinesBySchema = routinesBySchema ?? new Dictionary<string, IReadOnlyList<string>>(StringComparer.Ordinal);
DefaultSchema = defaultSchema;
_schemas = schemas;
_tablesBySchema = tablesBySchema;
@@ -93,6 +99,21 @@ public sealed class SqlCatalog
&& TryMatch(columns, authored, out canonical);
}
/// <summary>
/// Resolves an authored procedure name in a canonical schema to the catalog's spelling, by the same
/// exact-then-unique-case-insensitive rule as tables and columns.
/// </summary>
/// <param name="canonicalSchema">The schema, as <see cref="TryResolveSchema"/> returned it.</param>
/// <param name="authored">The authored procedure name.</param>
/// <param name="canonical">The catalog spelling, when this returns true.</param>
/// <returns>True when exactly one procedure matches.</returns>
public bool TryResolveRoutine(string canonicalSchema, string authored, out string canonical)
{
canonical = string.Empty;
return _routinesBySchema.TryGetValue(canonicalSchema, out var routines)
&& TryMatch(routines, authored, out canonical);
}
/// <summary>The dictionary key for a canonical relation.</summary>
/// <param name="schema">The canonical schema.</param>
/// <param name="table">The canonical table.</param>
@@ -81,16 +81,29 @@ public static class SqlCatalogGate
// A named-query tag quotes no identifier into SQL: its statement is driver configuration (checked
// read-only at construction) and its column/rowKey/timestamp names are matched against the result
// set by the reader. There is nothing here to allow-list, so it passes through unchanged.
// A Procedure-mode write block (lmxopcua#781) names a routine, which is resolved here like any other
// identifier — for a Query tag too, whose read side needs no catalog.
SqlTagDefinition? canonical;
SqlCatalogRejection? rejection;
if (definition.Model == SqlTagModel.Query)
{
accepted.Add(definition);
canonical = definition;
rejection = null;
}
else if (!TryCanonicalize(definition, catalog, dialect, out canonical, out rejection))
{
rejected.Add(rejection!);
continue;
}
if (TryCanonicalize(definition, catalog, dialect, out var canonical, out var rejection))
accepted.Add(canonical!);
else
if (canonical!.Write is { Mode: SqlWriteMode.Procedure } write
&& !TryResolveProcedure(canonical, write, catalog, dialect, out canonical, out rejection))
{
rejected.Add(rejection!);
continue;
}
accepted.Add(canonical!);
}
return new SqlCatalogGateResult(accepted, rejected);
@@ -162,6 +175,64 @@ public static class SqlCatalogGate
return true;
}
/// <summary>The rejection <see cref="SqlCatalogRejection.Field"/> for a write block's procedure.</summary>
internal const string ProcedureField = "Write.Procedure";
/// <summary>
/// Resolves a Procedure-mode write block's routine against the catalog and substitutes its spelling
/// (lmxopcua#781). Same rules as a table: at most two parts, each renderable, schema then routine by the
/// exact-then-unique-case-insensitive match.
/// </summary>
private static bool TryResolveProcedure(
SqlTagDefinition definition,
SqlWriteSpec write,
SqlCatalog catalog,
ISqlDialect dialect,
out SqlTagDefinition? canonical,
out SqlCatalogRejection? rejection)
{
canonical = null;
rejection = null;
if (dialect.ListRoutinesSql is null)
{
rejection = new SqlCatalogRejection(definition.Name, ProcedureField,
$"the {dialect.Provider} provider has no stored-procedure catalog to validate the procedure against, " +
"so a Procedure-mode write cannot be served on it");
return false;
}
var parts = (write.Procedure ?? string.Empty).Split('.');
if (parts.Length > MaxNameParts || parts.Any(p => !IsRenderableIdentifier(p, dialect)))
{
rejection = new SqlCatalogRejection(definition.Name, ProcedureField,
"the authored procedure name is not a usable one- or two-part identifier (empty, over-long, more than " +
"two parts, or containing control or Unicode format characters); the value is withheld from this " +
"message because it cannot be safely rendered");
return false;
}
var authoredSchema = parts.Length == MaxNameParts ? parts[0] : null;
var authoredRoutine = parts[^1];
if (!catalog.TryResolveSchema(authoredSchema, out var schema))
{
rejection = new SqlCatalogRejection(definition.Name, ProcedureField,
$"schema '{authoredSchema}' does not exist (or matches more than one schema under a case-sensitive collation)");
return false;
}
if (!catalog.TryResolveRoutine(schema, authoredRoutine, out var routine))
{
rejection = new SqlCatalogRejection(definition.Name, ProcedureField,
$"stored procedure '{authoredRoutine}' does not exist in schema '{schema}', or the connecting principal " +
"may not execute it (or the name matches more than one procedure under a case-sensitive collation)");
return false;
}
canonical = definition with { Write = write with { Procedure = SqlCatalog.QualifiedKey(schema, routine) } };
return true;
}
/// <summary>Splits and resolves the authored <c>table</c> to a canonical schema + relation.</summary>
private static bool TryResolveRelation(
SqlTagDefinition definition,
@@ -37,6 +37,8 @@ internal static class SqlCatalogLoader
private const string ColumnNameColumn = "COLUMN_NAME";
/// <summary>Base name of the schema parameter every dialect's catalog SQL carries.</summary>
private const string RoutineNameColumn = "ROUTINE_NAME";
private const string SchemaParameter = "schema";
/// <summary>Base name of the table parameter <see cref="ISqlDialect.ListColumnsSql"/> carries.</summary>
@@ -50,6 +52,7 @@ internal static class SqlCatalogLoader
/// <param name="authoredTables">The distinct authored <c>table</c> strings, as written in the blobs.</param>
/// <param name="commandTimeout">Per-command server-side backstop.</param>
/// <param name="cancellationToken">Cancellation token for the operation.</param>
/// <param name="authoredRoutines">Procedure-mode write targets (lmxopcua#781) whose schemas' procedures to list.</param>
/// <returns>The loaded catalog.</returns>
/// <exception cref="InvalidOperationException">The connection can see no schemas at all.</exception>
internal static async Task<SqlCatalog> LoadAsync(
@@ -57,7 +60,8 @@ internal static class SqlCatalogLoader
ISqlDialect dialect,
IReadOnlyCollection<string> authoredTables,
TimeSpan commandTimeout,
CancellationToken cancellationToken)
CancellationToken cancellationToken,
IReadOnlyCollection<string>? authoredRoutines = null)
{
var timeoutSeconds = Math.Max(1, (int)Math.Ceiling(commandTimeout.TotalSeconds));
@@ -124,7 +128,35 @@ internal static class SqlCatalogLoader
timeoutSeconds, cancellationToken).ConfigureAwait(false);
}
return new SqlCatalog(defaultSchema, schemas, tablesBySchema, columnsByTable);
// Procedure-mode write targets (lmxopcua#781): one routine listing per schema they name. A dialect with no
// routine catalog loads nothing, and the gate then refuses those tags by name.
var routinesBySchema = new Dictionary<string, IReadOnlyList<string>>(StringComparer.Ordinal);
if (dialect.ListRoutinesSql is { } listRoutinesSql)
{
foreach (var authored in authoredRoutines ?? [])
{
if (string.IsNullOrWhiteSpace(authored)) continue;
var parts = authored.Split('.');
if (parts.Length > 2) continue;
string schema;
if (parts.Length == 2)
{
if (!SqlCatalog.TryMatch(schemas, parts[0], out schema)) continue;
}
else
{
schema = defaultSchema;
}
if (routinesBySchema.ContainsKey(schema)) continue;
routinesBySchema[schema] = await QueryColumnAsync(
connection, dialect, listRoutinesSql, RoutineNameColumn,
command => Bind(command, dialect.ParameterBindName(SchemaParameter), schema),
timeoutSeconds, cancellationToken).ConfigureAwait(false);
}
}
return new SqlCatalog(defaultSchema, schemas, tablesBySchema, columnsByTable, routinesBySchema);
}
/// <summary>
@@ -15,11 +15,12 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Sql;
/// connectivity, and the <see cref="PollGroupEngine"/> subscription overlay, while
/// <see cref="SqlPollReader"/> owns the read path.
/// <para><b>Writes are opt-in at two levels and default off</b> (design §3.4, lmxopcua#753). A write needs
/// the driver's <c>allowWrites</c>, the tag's own <c>"writable": true</c>, and a model that names one row
/// (KeyValue, or a WideRow where-pair) — on top of the node's Writable flag and the caller's WriteOperate
/// role, which the server checks first. It is a parameterised single-row <c>UPDATE</c> over the tag's
/// catalog-validated identifiers (<see cref="SqlWritePlanner"/>), run in a transaction that commits only when
/// exactly one row was touched. With <c>allowWrites</c> off every write is
/// the driver's <c>allowWrites</c>, the tag's own <c>"writable": true</c>, and a target its <c>write</c> mode can
/// use (lmxopcua#781: Update / Upsert one keyed row, Insert any table-backed tag, Procedure any tag) — on top of
/// the node's Writable flag and the caller's WriteOperate role, which the server checks first. It is one
/// parameterised statement over the tag's catalog-validated identifiers (<see cref="SqlWritePlanner"/>), run in a
/// transaction that commits only when a table write touched exactly one row (a procedure call commits when it
/// does not throw). With <c>allowWrites</c> off every write is
/// <see cref="SqlStatusCodes.BadNotWritable"/> and every variable discovers as
/// <see cref="SecurityClassification.ViewOnly"/>.</para>
/// <para><b>Health is classified here, because nothing below does it.</b> The reader honours
@@ -626,17 +627,28 @@ public sealed class SqlDriver
/// Writable flag or the caller's role, which the server enforces before a write reaches the driver.
/// </summary>
private bool IsWritePermitted(SqlTagDefinition tag)
=> _options.AllowWrites && tag.Writable
&& (tag.Model == SqlTagModel.KeyValue
|| (tag.Model == SqlTagModel.WideRow && tag.RowSelectorColumn is not null));
=> _options.AllowWrites && tag.Writable && HasWriteTarget(tag) && _dialect.SupportsWriteMode(tag.EffectiveWrite.Mode);
/// <summary>
/// Whether the tag's model gives its write mode something to write (lmxopcua#781): a procedure always; an
/// insert any table-backed tag; an update or upsert one keyed row — KeyValue, or a WideRow where-pair.
/// </summary>
private static bool HasWriteTarget(SqlTagDefinition tag) => tag.EffectiveWrite.Mode switch
{
SqlWriteMode.Procedure => true,
SqlWriteMode.Insert => tag.Model is SqlTagModel.KeyValue or SqlTagModel.WideRow,
_ => tag.Model == SqlTagModel.KeyValue || (tag.Model == SqlTagModel.WideRow && tag.RowSelectorColumn is not null),
};
/// <inheritdoc />
// Each write is a parameterised single-row UPDATE (SqlWritePlanner) over the tag's CATALOG-VALIDATED
// definition — a tag the gate rejected misses here and answers BadNodeIdUnknown, so no unvalidated identifier
// can reach an UPDATE. It runs in a transaction that commits only when exactly one row was touched: zero rows
// is BadNoData (nothing to update — the driver never inserts), more than one is BadConfigurationError (the
// selector is ambiguous, the read-side rule), and both roll back. Bounded by operationTimeout like a poll. A
// write never changes driver health: its outcome is the write's answer, not a statement about the database.
// Each write is one parameterised statement in the tag's write mode (SqlWritePlanner; Update by default) over the
// tag's CATALOG-VALIDATED definition — a tag the gate rejected misses here and answers BadNodeIdUnknown, so no
// unvalidated identifier (table, column or procedure) can reach a statement. It runs in a transaction: a table
// write commits only when it touched one row (two for a MySQL upsert that updated) — zero rows is BadNoData, more
// is BadConfigurationError (the selector is ambiguous, the read-side rule), and both roll back; a procedure call
// commits when it does not throw. A constraint the database enforced maps to BadEntryExists / BadOutOfRange
// (MapWriteFailure). Bounded by operationTimeout like a poll. Never retried (WriteIdempotent=false). A write
// never changes driver health: its outcome is the write's answer, not a statement about the database.
public async Task<IReadOnlyList<WriteResult>> WriteAsync(
IReadOnlyList<WriteRequest> writes, CancellationToken cancellationToken)
{
@@ -656,7 +668,9 @@ public sealed class SqlDriver
if (!_options.AllowWrites) return SqlStatusCodes.BadNotWritable;
if (write.FullReference is null || Lookup(write.FullReference) is not { } tag)
return SqlStatusCodes.BadNodeIdUnknown;
if (!IsWritePermitted(tag)) return SqlStatusCodes.BadNotWritable;
if (!tag.Writable || !HasWriteTarget(tag)) return SqlStatusCodes.BadNotWritable;
// Deploy refuses a mode the provider cannot serve (SqlWriteModeUnsupported); this is the runtime backstop.
if (!_dialect.SupportsWriteMode(tag.EffectiveWrite.Mode)) return SqlStatusCodes.BadNotSupported;
var planned = SqlWritePlanner.TryPlan(tag, write.Value, _dialect, out var plan);
if (planned != SqlStatusCodes.Good) return planned;
@@ -683,14 +697,29 @@ public sealed class SqlDriver
catch (Exception ex)
{
// Open or execute failed. Type only on any surface; the exception (never the connection string) to the
// log sink. Nothing was committed.
_logger.LogWarning(ex, "Sql write to '{Tag}' failed against {Endpoint}: {Type}. Driver={DriverInstanceId}",
tag.Name, Endpoint, ex.GetType().Name, _driverInstanceId);
return SqlStatusCodes.BadCommunicationError;
// log sink. Nothing was committed. A constraint the database enforced is the value's fault, not the
// link's (lmxopcua#781): a duplicate key is BadEntryExists, another integrity or data rule BadOutOfRange.
// Everything else — a missing grant included — stays BadCommunicationError.
var failure = _dialect.ClassifyWriteFailure(ex);
_logger.LogWarning(ex, "Sql write to '{Tag}' failed against {Endpoint}: {Type} ({Failure}). Driver={DriverInstanceId}",
tag.Name, Endpoint, ex.GetType().Name, failure, _driverInstanceId);
return MapWriteFailure(failure);
}
}
/// <summary>Opens a connection and runs one planned UPDATE in a transaction that commits only on one row.</summary>
/// <summary>The status a classified write failure publishes (lmxopcua#781; documented in docs/drivers/Sql.md).</summary>
internal static uint MapWriteFailure(SqlWriteFailure failure) => failure switch
{
SqlWriteFailure.UniqueViolation => SqlStatusCodes.BadEntryExists,
SqlWriteFailure.IntegrityViolation or SqlWriteFailure.DataException => SqlStatusCodes.BadOutOfRange,
_ => SqlStatusCodes.BadCommunicationError,
};
/// <summary>
/// Opens a connection and runs one planned write in a transaction. A table write commits only when it touched
/// between one and <see cref="SqlWritePlan.MaxRowsAffected"/> rows; a procedure call commits whenever it did
/// not throw (its row count is the procedure's own business).
/// </summary>
private async Task<uint> ExecuteWriteAsync(SqlTagDefinition tag, SqlWritePlan plan, CancellationToken cancellationToken)
{
var connection = _factory.CreateConnection()
@@ -725,7 +754,7 @@ public sealed class SqlDriver
rows = await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false);
}
if (rows == 1)
if (plan.Mode == SqlWriteMode.Procedure || (rows >= 1 && rows <= plan.MaxRowsAffected))
{
await transaction.CommitAsync(cancellationToken).ConfigureAwait(false);
return SqlStatusCodes.Good;
@@ -735,9 +764,9 @@ public sealed class SqlDriver
if (rows == 0) return SqlStatusCodes.BadNoData;
_logger.LogWarning(
"Sql write to '{Tag}' matched {Rows} row(s) on '{Table}' and was rolled back: a write must update " +
"Sql {Mode} write to '{Tag}' touched {Rows} row(s) on '{Table}' and was rolled back: a write must touch " +
"exactly one row. Driver={DriverInstanceId}",
tag.Name, rows, tag.Table, _driverInstanceId);
plan.Mode, tag.Name, rows, tag.Table, _driverInstanceId);
return rows > 1 ? SqlStatusCodes.BadConfigurationError : SqlStatusCodes.BadNotSupported;
}
}
@@ -1115,6 +1144,15 @@ public sealed class SqlDriver
continue;
}
if (definition.Write is { } write && !_dialect.SupportsWriteMode(write.Mode))
{
// Deploy refuses this (SqlWriteModeUnsupported); an older artifact still reads, read-only.
_logger.LogWarning(
"Sql tag {RawPath} asks for {Mode} writes, which the {Provider} provider does not serve; it " +
"is published read-only. Driver={DriverInstanceId}",
entry.RawPath, write.Mode, _dialect.Provider, _driverInstanceId);
}
table[entry.RawPath] = definition;
}
else
@@ -1197,10 +1235,17 @@ public sealed class SqlDriver
.Distinct(StringComparer.OrdinalIgnoreCase)
.ToArray();
var catalog = tables.Length == 0
// Procedure-mode write targets (lmxopcua#781) are identifiers too — a Query tag's included.
var routines = authored.Values
.Where(definition => definition.Write is { Mode: SqlWriteMode.Procedure })
.Select(definition => definition.Write!.Procedure!)
.Distinct(StringComparer.OrdinalIgnoreCase)
.ToArray();
var catalog = tables.Length == 0 && routines.Length == 0
? SqlCatalog.Empty
: await RunBoundedAsync(
token => LoadCatalogAsync(tables, token),
token => LoadCatalogAsync(tables, routines, token),
_options.OperationTimeout,
"the catalog queries did not return",
cancellationToken).ConfigureAwait(false);
@@ -1235,7 +1280,8 @@ public sealed class SqlDriver
/// <summary>Opens one connection and reads the catalog slice the authored tables need.</summary>
private async Task<SqlCatalog> LoadCatalogAsync(
IReadOnlyCollection<string> authoredTables, CancellationToken cancellationToken)
IReadOnlyCollection<string> authoredTables, IReadOnlyCollection<string> authoredRoutines,
CancellationToken cancellationToken)
{
var connection = _factory.CreateConnection()
?? throw new InvalidOperationException(
@@ -1246,7 +1292,7 @@ public sealed class SqlDriver
connection.ConnectionString = _connectionString;
await connection.OpenAsync(cancellationToken).ConfigureAwait(false);
return await SqlCatalogLoader
.LoadAsync(connection, _dialect, authoredTables, _options.CommandTimeout, cancellationToken)
.LoadAsync(connection, _dialect, authoredTables, _options.CommandTimeout, cancellationToken, authoredRoutines)
.ConfigureAwait(false);
}
}
@@ -1257,7 +1257,22 @@ public static class SqlStatusCodes
/// </summary>
public const uint BadNotWritable = 0x803B0000u;
/// <summary>The provider could not report how many rows a write touched, so it was rolled back.</summary>
/// <summary>
/// A write the database refused for a unique / primary-key violation (lmxopcua#781) — an Insert of a key that
/// exists, typically. (<c>BadEntryExists</c>, read off <c>Opc.Ua.StatusCodes</c>.)
/// </summary>
public const uint BadEntryExists = 0x809F0000u;
/// <summary>
/// A write the database refused for another integrity rule (NOT NULL, foreign key, CHECK) or a data exception
/// (overflow, truncation, an unconvertible value) — lmxopcua#781. (<c>BadOutOfRange</c>.)
/// </summary>
public const uint BadOutOfRange = 0x803C0000u;
/// <summary>
/// The provider could not report how many rows a write touched, so it was rolled back — or the dialect does not
/// serve the tag's write mode (Upsert / Procedure on Odbc, lmxopcua#781).
/// </summary>
public const uint BadNotSupported = 0x803D0000u;
/// <summary>The quality-class mask — the top two bits of an OPC UA status code.</summary>
@@ -4,94 +4,235 @@ using ZB.MOM.WW.OtOpcUa.Driver.Sql.Contracts;
namespace ZB.MOM.WW.OtOpcUa.Driver.Sql;
/// <summary>
/// One compiled single-row write (lmxopcua#753): a parameterised <c>UPDATE</c> whose identifiers are the
/// tag's catalog-validated ones and whose values are all bound.
/// One compiled write (lmxopcua#753, #781): a parameterised statement whose identifiers are the tag's
/// catalog-validated ones and whose values are all bound.
/// </summary>
/// <param name="SqlText">The statement — dialect-quoted identifiers and parameter markers only.</param>
/// <param name="ParameterBindNames">The bind names, in marker order (positional providers bind in this order).</param>
/// <param name="ParameterBindNames">
/// The distinct bind names, in first-marker order (a positional provider binds in this order, and only the modes
/// it supports — Update and Insert — are planned for it, where every marker appears exactly once).
/// </param>
/// <param name="Parameters">The bound values, aligned with <paramref name="ParameterBindNames"/>.</param>
/// <param name="Mode">The statement shape — decides how the executor reads the affected-row count.</param>
/// <param name="MaxRowsAffected">
/// The most rows the statement may report for a success: 1, or 2 for a MySQL upsert. Ignored for
/// <see cref="SqlWriteMode.Procedure"/>, whose row count is the procedure's business.
/// </param>
public sealed record SqlWritePlan(
string SqlText,
IReadOnlyList<string> ParameterBindNames,
IReadOnlyList<object?> Parameters);
IReadOnlyList<object?> Parameters,
SqlWriteMode Mode = SqlWriteMode.Update,
int MaxRowsAffected = 1);
/// <summary>
/// Turns one OPC UA write into a parameterised single-row <c>UPDATE</c> (design §3.4, lmxopcua#753) — pure, no
/// I/O. <b>The write surface is deliberately narrow:</b> no authored SQL, no INSERT/UPSERT/procedure, only
/// <c>UPDATE &lt;table&gt; SET &lt;value column&gt; = @v WHERE &lt;key column&gt; = @k</c> built from the
/// tag's own identifiers.
/// Turns one OPC UA write into one parameterised statement (design §3.4, lmxopcua#753 / #781 item 2) — pure, no
/// I/O. The tag's <c>write</c> block picks the shape; there is no authored write SQL:
/// <list type="bullet">
/// <item><see cref="SqlTagModel.KeyValue"/>: <c>SET valueColumn = @v WHERE keyColumn = @k</c>.</item>
/// <item><see cref="SqlTagModel.WideRow"/> with a where-pair: <c>SET columnName = @v WHERE whereColumn = @w</c>.</item>
/// <item><see cref="SqlTagModel.WideRow"/> by <c>topByTimestamp</c>, and <see cref="SqlTagModel.Query"/>:
/// refused (<see cref="SqlStatusCodes.BadNotWritable"/>) — "the newest row" moves under a concurrent
/// insert, and a named query's projection names no table to update.</item>
/// <item><see cref="SqlWriteMode.Update"/> (the default): <c>UPDATE t SET value [, stamp] WHERE key = @k</c>
/// on a KeyValue tag or a WideRow where-pair.</item>
/// <item><see cref="SqlWriteMode.Insert"/>: <c>INSERT INTO t (key, value [, stamp]) VALUES (…)</c> — no key
/// column for a WideRow <c>topByTimestamp</c> tag (an append).</item>
/// <item><see cref="SqlWriteMode.Upsert"/>: the dialect's single-statement upsert
/// (<see cref="ISqlDialect.UpsertSql"/>).</item>
/// <item><see cref="SqlWriteMode.Procedure"/>: the dialect's call of the catalog-validated procedure
/// (<see cref="ISqlDialect.ProcedureCallSql"/>) with the value, and optionally the key and write time, bound.</item>
/// </list>
/// <para><b>Injection boundary.</b> Every identifier is one the catalog gate resolved and substituted (the
/// driver plans writes only for <em>polled</em>, i.e. gate-accepted, definitions) and reaches the text through
/// <see cref="ISqlDialect.QuoteIdentifier"/>; the written value and the key are bound parameters. Nothing an
/// OPC UA client sends reaches the command text.</para>
/// <para><b>Injection boundary.</b> Every identifier is one the catalog gate resolved and substituted (the driver
/// plans writes only for gate-accepted definitions) and reaches the text through
/// <see cref="ISqlDialect.QuoteIdentifier"/>; procedure parameter names are restricted to a plain identifier
/// charset by the tag parser; the value, the key and the stamp are bound parameters. Nothing an OPC UA client
/// sends reaches the command text.</para>
/// </summary>
public static class SqlWritePlanner
{
private const string ValueBaseName = "v";
private const string KeyBaseName = "k";
private const string TimestampBaseName = "t";
/// <summary>
/// Plans a write of <paramref name="value"/> to <paramref name="tag"/>, or explains why it is refused.
/// </summary>
/// <summary>Plans a write of <paramref name="value"/> to <paramref name="tag"/>, stamping the current UTC time.</summary>
/// <param name="tag">The catalog-validated definition.</param>
/// <param name="value">The value the client wrote.</param>
/// <param name="dialect">Quoting, markers and bind names.</param>
/// <param name="dialect">Quoting, markers, bind names and the dialect-specific statements.</param>
/// <param name="plan">The plan, when this returns <see cref="SqlStatusCodes.Good"/>.</param>
/// <returns><see cref="SqlStatusCodes.Good"/>, or the status the write publishes.</returns>
public static uint TryPlan(SqlTagDefinition tag, object? value, ISqlDialect dialect, out SqlWritePlan? plan)
=> TryPlan(tag, value, dialect, DateTime.UtcNow, out plan);
/// <summary>
/// Plans a write of <paramref name="value"/> to <paramref name="tag"/>, or explains why it is refused.
/// <see cref="SqlStatusCodes.BadNotWritable"/>: the model has no target for the mode (a Query tag outside
/// Procedure, a <c>topByTimestamp</c> row for Update/Upsert). <see cref="SqlStatusCodes.BadNotSupported"/>: the
/// dialect does not serve the mode. <see cref="SqlStatusCodes.BadTypeMismatch"/>: the value will not coerce.
/// </summary>
/// <param name="tag">The catalog-validated definition.</param>
/// <param name="value">The value the client wrote.</param>
/// <param name="dialect">Quoting, markers, bind names and the dialect-specific statements.</param>
/// <param name="utcNow">The write time bound to a stamp column or <c>timestampParam</c> (UTC).</param>
/// <param name="plan">The plan, when this returns <see cref="SqlStatusCodes.Good"/>.</param>
/// <returns><see cref="SqlStatusCodes.Good"/>, or the status the write publishes.</returns>
public static uint TryPlan(
SqlTagDefinition tag, object? value, ISqlDialect dialect, DateTime utcNow, out SqlWritePlan? plan)
{
ArgumentNullException.ThrowIfNull(tag);
ArgumentNullException.ThrowIfNull(dialect);
plan = null;
string setColumn, keyColumn;
string? keyValue;
switch (tag.Model)
{
case SqlTagModel.KeyValue when !Blank(tag.ValueColumn) && !Blank(tag.KeyColumn) && tag.KeyValue is not null:
setColumn = tag.ValueColumn!;
keyColumn = tag.KeyColumn!;
keyValue = tag.KeyValue;
break;
case SqlTagModel.WideRow when !Blank(tag.ColumnName) && !Blank(tag.RowSelectorColumn)
&& tag.RowSelectorValue is not null:
setColumn = tag.ColumnName!;
keyColumn = tag.RowSelectorColumn!;
keyValue = tag.RowSelectorValue;
break;
default:
return SqlStatusCodes.BadNotWritable;
}
var write = tag.EffectiveWrite;
if (!dialect.SupportsWriteMode(write.Mode)) return SqlStatusCodes.BadNotSupported;
if (!TryConvert(value, tag.DeclaredType, out var bound)) return SqlStatusCodes.BadTypeMismatch;
var stamp = DateTime.SpecifyKind(utcNow, DateTimeKind.Utc);
string sql;
try
{
sql = string.Concat(
"UPDATE ", QuoteQualifiedName(tag.Table, dialect),
" SET ", dialect.QuoteIdentifier(setColumn), " = ", dialect.ParameterMarker(ValueBaseName),
" WHERE ", dialect.QuoteIdentifier(keyColumn), " = ", dialect.ParameterMarker(KeyBaseName));
return write.Mode == SqlWriteMode.Procedure
? PlanProcedure(tag, write, bound, stamp, dialect, out plan)
: PlanTableWrite(tag, write, bound, stamp, dialect, out plan);
}
catch (ArgumentException)
{
// Unreachable for a gate-accepted definition (its identifiers came from the catalog); refuse rather
// than build a statement around a name the dialect would not quote.
plan = null;
return SqlStatusCodes.BadConfigurationError;
}
}
// Marker order: SET's value first, then WHERE's key — a positional provider (ODBC) binds in this order.
plan = new SqlWritePlan(
sql,
[dialect.ParameterBindName(ValueBaseName), dialect.ParameterBindName(KeyBaseName)],
[bound, keyValue]);
/// <summary>Update / Insert / Upsert against the tag's own table.</summary>
private static uint PlanTableWrite(
SqlTagDefinition tag, SqlWriteSpec write, object? bound, DateTime stamp, ISqlDialect dialect, out SqlWritePlan? plan)
{
plan = null;
string valueColumn;
string? keyColumn;
string? keyValue;
switch (tag.Model)
{
case SqlTagModel.KeyValue when !Blank(tag.ValueColumn) && !Blank(tag.KeyColumn) && tag.KeyValue is not null:
valueColumn = tag.ValueColumn!;
keyColumn = tag.KeyColumn!;
keyValue = tag.KeyValue;
break;
case SqlTagModel.WideRow when !Blank(tag.ColumnName) && !Blank(tag.RowSelectorColumn)
&& tag.RowSelectorValue is not null:
valueColumn = tag.ColumnName!;
keyColumn = tag.RowSelectorColumn!;
keyValue = tag.RowSelectorValue;
break;
// Newest-row selector: an Insert appends a row (no key); Update/Upsert have no row to aim at — "the
// newest row" moves under a concurrent insert.
case SqlTagModel.WideRow when write.Mode == SqlWriteMode.Insert && !Blank(tag.ColumnName):
valueColumn = tag.ColumnName!;
keyColumn = null;
keyValue = null;
break;
default:
return SqlStatusCodes.BadNotWritable;
}
var stampColumn = write.StampTimestamp ? SqlWriteSpecParser.StampColumn(tag) : null;
if (write.StampTimestamp && stampColumn is null) return SqlStatusCodes.BadConfigurationError;
var table = QuoteQualifiedName(tag.Table, dialect);
var valueMarker = dialect.ParameterMarker(ValueBaseName);
var keyMarker = dialect.ParameterMarker(KeyBaseName);
var stampMarker = dialect.ParameterMarker(TimestampBaseName);
// The value first, then the stamp: the order of the SET list and of the insert's non-key columns.
var assignments = new List<(string QuotedColumn, string Marker)> { (dialect.QuoteIdentifier(valueColumn), valueMarker) };
if (stampColumn is not null) assignments.Add((dialect.QuoteIdentifier(stampColumn), stampMarker));
var binds = new Binds(dialect);
string sql;
var maxRows = 1;
switch (write.Mode)
{
case SqlWriteMode.Update:
// Marker order: SET's value [and stamp], then WHERE's key — a positional provider binds in this order.
sql = string.Concat(
"UPDATE ", table,
" SET ", string.Join(", ", assignments.Select(a => a.QuotedColumn + " = " + a.Marker)),
" WHERE ", dialect.QuoteIdentifier(keyColumn!), " = ", keyMarker);
binds.Add(ValueBaseName, bound);
if (stampColumn is not null) binds.Add(TimestampBaseName, stamp);
binds.Add(KeyBaseName, keyValue);
break;
case SqlWriteMode.Insert:
{
var columns = new List<string>();
var markers = new List<string>();
if (keyColumn is not null)
{
columns.Add(dialect.QuoteIdentifier(keyColumn));
markers.Add(keyMarker);
binds.Add(KeyBaseName, keyValue);
}
columns.AddRange(assignments.Select(a => a.QuotedColumn));
markers.AddRange(assignments.Select(a => a.Marker));
binds.Add(ValueBaseName, bound);
if (stampColumn is not null) binds.Add(TimestampBaseName, stamp);
sql = string.Concat(
"INSERT INTO ", table, " (", string.Join(", ", columns), ") VALUES (", string.Join(", ", markers), ")");
break;
}
case SqlWriteMode.Upsert:
{
var upsert = dialect.UpsertSql(table, dialect.QuoteIdentifier(keyColumn!), keyMarker, assignments);
if (upsert is null) return SqlStatusCodes.BadNotSupported;
sql = upsert;
// A named-marker dialect (the only kind with an upsert) binds by name, so first-appearance order is
// documentation rather than load-bearing here.
binds.Add(KeyBaseName, keyValue);
binds.Add(ValueBaseName, bound);
if (stampColumn is not null) binds.Add(TimestampBaseName, stamp);
maxRows = Math.Max(1, dialect.UpsertMaxRowsAffected);
break;
}
default:
return SqlStatusCodes.BadNotWritable;
}
plan = new SqlWritePlan(sql, binds.Names, binds.Values, write.Mode, maxRows);
return SqlStatusCodes.Good;
}
/// <summary>A call of the tag's catalog-validated procedure: value, then key, then write time — each when bound.</summary>
private static uint PlanProcedure(
SqlTagDefinition tag, SqlWriteSpec write, object? bound, DateTime stamp, ISqlDialect dialect, out SqlWritePlan? plan)
{
plan = null;
if (Blank(write.Procedure)) return SqlStatusCodes.BadConfigurationError;
var binds = new Binds(dialect);
var arguments = new List<(string Parameter, string Marker)>
{
(write.ValueParameter ?? SqlWriteSpecParser.DefaultValueParameter, dialect.ParameterMarker(ValueBaseName)),
};
binds.Add(ValueBaseName, bound);
if (write.KeyParameter is { } keyParameter)
{
var key = SqlWriteSpecParser.KeyValue(tag);
if (key is null) return SqlStatusCodes.BadConfigurationError;
arguments.Add((keyParameter, dialect.ParameterMarker(KeyBaseName)));
binds.Add(KeyBaseName, key);
}
if (write.TimestampParameter is { } timestampParameter)
{
arguments.Add((timestampParameter, dialect.ParameterMarker(TimestampBaseName)));
binds.Add(TimestampBaseName, stamp);
}
var sql = dialect.ProcedureCallSql(QuoteQualifiedName(write.Procedure!, dialect), arguments);
if (sql is null) return SqlStatusCodes.BadNotSupported;
plan = new SqlWritePlan(sql, binds.Names, binds.Values, SqlWriteMode.Procedure);
return SqlStatusCodes.Good;
}
@@ -116,9 +257,23 @@ public static class SqlWritePlanner
return false;
}
/// <summary>Quotes each part of a (catalog-canonical) <c>schema.table</c> name.</summary>
/// <summary>Quotes each part of a (catalog-canonical) <c>schema.name</c>.</summary>
private static string QuoteQualifiedName(string name, ISqlDialect dialect)
=> string.Join('.', name.Split('.').Select(dialect.QuoteIdentifier));
private static bool Blank(string? value) => string.IsNullOrWhiteSpace(value);
/// <summary>The ordered (bind name, value) list a plan carries.</summary>
private sealed class Binds(ISqlDialect dialect)
{
public List<string> Names { get; } = [];
public List<object?> Values { get; } = [];
public void Add(string baseName, object? value)
{
Names.Add(dialect.ParameterBindName(baseName));
Values.Add(value);
}
}
}