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
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:
@@ -243,4 +243,65 @@ public interface ISqlDialect
|
||||
/// <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);
|
||||
|
||||
// ---- 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>
|
||||
/// 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);
|
||||
}
|
||||
|
||||
@@ -177,4 +177,48 @@ public sealed class MySqlDialect : ISqlDialect
|
||||
_ => DriverDataType.String,
|
||||
};
|
||||
}
|
||||
|
||||
// ---- writes (lmxopcua#781 item 2) ----
|
||||
|
||||
/// <inheritdoc />
|
||||
// INSERT … ON DUPLICATE KEY UPDATE — fires on ANY unique key of the table, so the key column must be the table's
|
||||
// primary key or a unique key (and the table should carry no OTHER unique key a write could collide with).
|
||||
// MySqlConnector substitutes parameters client-side, so a marker may repeat.
|
||||
public string? UpsertSql(
|
||||
string quotedTable, string quotedKeyColumn, string keyMarker,
|
||||
IReadOnlyList<(string QuotedColumn, string Marker)> assignments)
|
||||
=> string.Concat(
|
||||
"INSERT INTO ", quotedTable, " (", quotedKeyColumn, ", ", string.Join(", ", assignments.Select(a => a.QuotedColumn)),
|
||||
") VALUES (", keyMarker, ", ", string.Join(", ", assignments.Select(a => a.Marker)),
|
||||
") ON DUPLICATE KEY UPDATE ", string.Join(", ", assignments.Select(a => a.QuotedColumn + " = " + a.Marker)));
|
||||
|
||||
/// <inheritdoc />
|
||||
// 1 for an inserted row, 2 for an updated one (MySQL's documented ON DUPLICATE KEY UPDATE count). MySqlConnector
|
||||
// defaults to found-rows (UseAffectedRows=false), so an update to the same value still reports a row, not 0.
|
||||
public int UpsertMaxRowsAffected => 2;
|
||||
|
||||
/// <inheritdoc />
|
||||
// MySQL has no named-argument notation: arguments are POSITIONAL, in the order the driver lists them — the value,
|
||||
// then the key (keyParam), then the write time (timestampParam). The parameter names are not sent.
|
||||
public string? ProcedureCallSql(string quotedProcedure, IReadOnlyList<(string Parameter, string Marker)> arguments)
|
||||
=> "CALL " + quotedProcedure + "(" + string.Join(", ", arguments.Select(a => a.Marker)) + ")";
|
||||
|
||||
/// <inheritdoc />
|
||||
public string? ListRoutinesSql =>
|
||||
"SELECT ROUTINE_NAME AS ROUTINE_NAME FROM information_schema.ROUTINES " +
|
||||
"WHERE ROUTINE_SCHEMA = @schema AND ROUTINE_TYPE = 'PROCEDURE' ORDER BY ROUTINE_NAME";
|
||||
|
||||
/// <inheritdoc />
|
||||
// 1062 duplicate entry; 3819 CHECK violated (reported as SQLSTATE HY000, so it needs the number); the rest by
|
||||
// SQLSTATE — 23000 covers NOT NULL (1048) and foreign keys (1451/1452), class 22 overflow/truncation.
|
||||
public SqlWriteFailure ClassifyWriteFailure(Exception exception)
|
||||
{
|
||||
if (exception is not MySqlException my) return SqlWriteFailure.Other;
|
||||
return my.Number switch
|
||||
{
|
||||
1062 => SqlWriteFailure.UniqueViolation,
|
||||
3819 => SqlWriteFailure.IntegrityViolation,
|
||||
_ => SqlWriteFailures.FromSqlState(my.SqlState),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -170,4 +170,15 @@ public sealed class OdbcDialect : ISqlDialect
|
||||
_ => DriverDataType.String,
|
||||
};
|
||||
}
|
||||
|
||||
// ---- writes (lmxopcua#781 item 2) ----
|
||||
// Update and Insert only (SqlWriteSupport): no Upsert (positional markers cannot repeat, and MERGE is missing or
|
||||
// partial on several ODBC backends) and no Procedure (no portable routine catalog or calling convention).
|
||||
|
||||
/// <inheritdoc />
|
||||
// The driver manager reports the backend's SQLSTATE on each OdbcError.
|
||||
public SqlWriteFailure ClassifyWriteFailure(Exception exception)
|
||||
=> exception is OdbcException odbc && odbc.Errors.Count > 0
|
||||
? SqlWriteFailures.FromSqlState(odbc.Errors[0].SQLState)
|
||||
: SqlWriteFailure.Other;
|
||||
}
|
||||
|
||||
@@ -325,4 +325,50 @@ public sealed class OracleDialect : ISqlDialect
|
||||
_ => DriverDataType.String,
|
||||
};
|
||||
}
|
||||
|
||||
// ---- writes (lmxopcua#781 item 2) ----
|
||||
|
||||
/// <inheritdoc />
|
||||
// MERGE from a constant one-row DUAL source, matching the target's key to the bound key; BindByName (set in
|
||||
// ConfigureCommand) is what lets the key and value markers appear twice. No trailing semicolon — ODP.NET refuses
|
||||
// one on a SQL statement.
|
||||
public string? UpsertSql(
|
||||
string quotedTable, string quotedKeyColumn, string keyMarker,
|
||||
IReadOnlyList<(string QuotedColumn, string Marker)> assignments)
|
||||
=> string.Concat(
|
||||
"MERGE INTO ", quotedTable, " tgt USING (SELECT 1 AS one FROM dual) src ON (tgt.", quotedKeyColumn, " = ",
|
||||
keyMarker, ") WHEN MATCHED THEN UPDATE SET ",
|
||||
string.Join(", ", assignments.Select(a => "tgt." + a.QuotedColumn + " = " + a.Marker)),
|
||||
" WHEN NOT MATCHED THEN INSERT (", quotedKeyColumn, ", ", string.Join(", ", assignments.Select(a => a.QuotedColumn)),
|
||||
") VALUES (", keyMarker, ", ", string.Join(", ", assignments.Select(a => a.Marker)), ")");
|
||||
|
||||
/// <inheritdoc />
|
||||
// An anonymous PL/SQL block with named notation. Unquoted parameter names fold to upper case, as Oracle's own do.
|
||||
// A standalone procedure only — a package member (pkg.proc) is a three-part name the gate cannot validate.
|
||||
public string? ProcedureCallSql(string quotedProcedure, IReadOnlyList<(string Parameter, string Marker)> arguments)
|
||||
=> "BEGIN " + quotedProcedure
|
||||
+ (arguments.Count == 0 ? string.Empty : "(" + string.Join(", ", arguments.Select(a => a.Parameter + " => " + a.Marker)) + ")")
|
||||
+ "; END;";
|
||||
|
||||
/// <inheritdoc />
|
||||
// ALL_PROCEDURES lists a standalone procedure as OBJECT_TYPE 'PROCEDURE' with OBJECT_NAME its name; it shows only
|
||||
// what the principal may execute or owns.
|
||||
public string? ListRoutinesSql =>
|
||||
"SELECT object_name AS ROUTINE_NAME FROM ALL_PROCEDURES " +
|
||||
"WHERE owner = " + ParameterMarker("schema") + " AND object_type = 'PROCEDURE' ORDER BY object_name";
|
||||
|
||||
/// <inheritdoc />
|
||||
// ODP.NET reports no SQLSTATE; the ORA- number decides. 1 unique; 1400/1407 NULL, 2290 CHECK, 2291/2292 FK;
|
||||
// 1438 precision, 12899 too large, 1722 invalid number, 18xx date conversion.
|
||||
public SqlWriteFailure ClassifyWriteFailure(Exception exception)
|
||||
{
|
||||
if (exception is not OracleException ora) return SqlWriteFailure.Other;
|
||||
return ora.Number switch
|
||||
{
|
||||
1 => SqlWriteFailure.UniqueViolation,
|
||||
1400 or 1407 or 2290 or 2291 or 2292 => SqlWriteFailure.IntegrityViolation,
|
||||
1438 or 12899 or 1722 or 1830 or 1840 or 1841 or 1843 or 1847 or 1858 or 1861 => SqlWriteFailure.DataException,
|
||||
_ => SqlWriteFailure.Other,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -267,4 +267,35 @@ public sealed class PostgresDialect : ISqlDialect
|
||||
_ => DriverDataType.String,
|
||||
};
|
||||
}
|
||||
|
||||
// ---- writes (lmxopcua#781 item 2) ----
|
||||
|
||||
/// <inheritdoc />
|
||||
// INSERT … ON CONFLICT (key) DO UPDATE — atomic under concurrency, but it REQUIRES a unique constraint or unique
|
||||
// index on exactly the key column (the server refuses the statement otherwise: SQLSTATE 42P10, which surfaces as
|
||||
// BadCommunicationError). EXCLUDED is the row the insert proposed, so each value marker appears once in VALUES.
|
||||
// Because a conflict target is unique, the statement touches exactly one row.
|
||||
public string? UpsertSql(
|
||||
string quotedTable, string quotedKeyColumn, string keyMarker,
|
||||
IReadOnlyList<(string QuotedColumn, string Marker)> assignments)
|
||||
=> string.Concat(
|
||||
"INSERT INTO ", quotedTable, " (", quotedKeyColumn, ", ", string.Join(", ", assignments.Select(a => a.QuotedColumn)),
|
||||
") VALUES (", keyMarker, ", ", string.Join(", ", assignments.Select(a => a.Marker)),
|
||||
") ON CONFLICT (", quotedKeyColumn, ") DO UPDATE SET ",
|
||||
string.Join(", ", assignments.Select(a => a.QuotedColumn + " = EXCLUDED." + a.QuotedColumn)));
|
||||
|
||||
/// <inheritdoc />
|
||||
// CALL with named notation (PostgreSQL 11+ procedures). Argument types must resolve by IMPLICIT cast: a Float64
|
||||
// binds as double precision, so declare a numeric parameter as double precision (or cast inside the procedure),
|
||||
// and a write time binds as timestamptz.
|
||||
public string? ProcedureCallSql(string quotedProcedure, IReadOnlyList<(string Parameter, string Marker)> arguments)
|
||||
=> "CALL " + quotedProcedure + "(" + string.Join(", ", arguments.Select(a => a.Parameter + " => " + a.Marker)) + ")";
|
||||
|
||||
/// <inheritdoc />
|
||||
// information_schema.routines shows only routines the current role may execute or owns — the gate's question.
|
||||
public string? ListRoutinesSql =>
|
||||
"SELECT routine_name AS \"ROUTINE_NAME\" FROM information_schema.routines " +
|
||||
"WHERE routine_schema = @schema AND routine_type = 'PROCEDURE' ORDER BY \"ROUTINE_NAME\"";
|
||||
|
||||
// ClassifyWriteFailure: the interface default reads PostgresException.SqlState, which Npgsql always reports.
|
||||
}
|
||||
|
||||
@@ -222,4 +222,52 @@ public sealed class SqlServerDialect : ISqlDialect
|
||||
_ => DriverDataType.String,
|
||||
};
|
||||
}
|
||||
|
||||
// ---- writes (lmxopcua#781 item 2) ----
|
||||
|
||||
/// <inheritdoc />
|
||||
// MERGE … WITH (HOLDLOCK): the key-range lock HOLDLOCK takes is what makes the matched/not-matched decision and
|
||||
// the insert one atomic step under concurrency — a bare MERGE (or UPDATE-then-INSERT) can race two writers into a
|
||||
// duplicate insert. The source is a constant one-row derived table and the ON clause compares the target's key to
|
||||
// the bound key directly, so a key matching several rows updates them all and the driver's row-count rule rolls it
|
||||
// back. The trailing semicolon is mandatory for MERGE.
|
||||
public string? UpsertSql(
|
||||
string quotedTable, string quotedKeyColumn, string keyMarker,
|
||||
IReadOnlyList<(string QuotedColumn, string Marker)> assignments)
|
||||
=> string.Concat(
|
||||
"MERGE INTO ", quotedTable, " WITH (HOLDLOCK) AS tgt USING (SELECT 1 AS one) AS src ON tgt.",
|
||||
quotedKeyColumn, " = ", keyMarker,
|
||||
" WHEN MATCHED THEN UPDATE SET ", string.Join(", ", assignments.Select(a => a.QuotedColumn + " = " + a.Marker)),
|
||||
" WHEN NOT MATCHED THEN INSERT (", quotedKeyColumn, ", ", string.Join(", ", assignments.Select(a => a.QuotedColumn)),
|
||||
") VALUES (", keyMarker, ", ", string.Join(", ", assignments.Select(a => a.Marker)), ");");
|
||||
|
||||
/// <inheritdoc />
|
||||
// EXEC with named arguments: the left-hand @name is the procedure's own parameter, the right-hand marker the bind.
|
||||
public string? ProcedureCallSql(string quotedProcedure, IReadOnlyList<(string Parameter, string Marker)> arguments)
|
||||
=> arguments.Count == 0
|
||||
? "EXEC " + quotedProcedure
|
||||
: "EXEC " + quotedProcedure + " " + string.Join(", ", arguments.Select(a => "@" + a.Parameter + " = " + a.Marker));
|
||||
|
||||
/// <inheritdoc />
|
||||
// INFORMATION_SCHEMA.ROUTINES lists only routines the principal may see (it holds a permission on), which is the
|
||||
// question the gate asks. Procedures only — a function is not callable with EXEC semantics here.
|
||||
public string? ListRoutinesSql =>
|
||||
"SELECT ROUTINE_NAME FROM INFORMATION_SCHEMA.ROUTINES " +
|
||||
"WHERE ROUTINE_SCHEMA = @schema AND ROUTINE_TYPE = 'PROCEDURE' ORDER BY ROUTINE_NAME";
|
||||
|
||||
/// <inheritdoc />
|
||||
// SqlClient reports no SQLSTATE, so the engine error number decides. 2627/2601 duplicate key (constraint /
|
||||
// unique index); 547 FK or CHECK, 515 NULL into NOT NULL; 8115/220/232 arithmetic overflow, 8152/2628 truncation,
|
||||
// 245/8114 conversion, 241/242 date conversion or out of range.
|
||||
public SqlWriteFailure ClassifyWriteFailure(Exception exception)
|
||||
{
|
||||
if (exception is not SqlException sql) return SqlWriteFailure.Other;
|
||||
return sql.Number switch
|
||||
{
|
||||
2627 or 2601 => SqlWriteFailure.UniqueViolation,
|
||||
547 or 515 => SqlWriteFailure.IntegrityViolation,
|
||||
8115 or 220 or 232 or 8152 or 2628 or 245 or 8114 or 241 or 242 => SqlWriteFailure.DataException,
|
||||
_ => SqlWriteFailure.Other,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.Sql;
|
||||
|
||||
/// <summary>Why a write's statement failed, as far as the provider's error says (lmxopcua#781 item 2).</summary>
|
||||
public enum SqlWriteFailure
|
||||
{
|
||||
/// <summary>Anything else — permission denied, a missing object, a broken connection. <c>BadCommunicationError</c>.</summary>
|
||||
Other,
|
||||
|
||||
/// <summary>A unique / primary-key violation (SQLSTATE 23505, SQL Server 2627/2601, MySQL 1062, ORA-00001). <c>BadEntryExists</c>.</summary>
|
||||
UniqueViolation,
|
||||
|
||||
/// <summary>Another integrity constraint — NOT NULL, foreign key, CHECK (SQLSTATE class 23). <c>BadOutOfRange</c>.</summary>
|
||||
IntegrityViolation,
|
||||
|
||||
/// <summary>A data exception — overflow, truncation, an unconvertible value (SQLSTATE class 22). <c>BadOutOfRange</c>.</summary>
|
||||
DataException,
|
||||
}
|
||||
|
||||
/// <summary>SQLSTATE-based classification shared by the dialects.</summary>
|
||||
public static class SqlWriteFailures
|
||||
{
|
||||
/// <summary>Classifies an ANSI SQLSTATE: 23505 unique, class 23 integrity, class 22 data; anything else (or null) other.</summary>
|
||||
/// <param name="sqlState">The five-character SQLSTATE, or null.</param>
|
||||
/// <returns>The failure class.</returns>
|
||||
public static SqlWriteFailure FromSqlState(string? sqlState)
|
||||
{
|
||||
if (string.IsNullOrEmpty(sqlState) || sqlState.Length < 2) return SqlWriteFailure.Other;
|
||||
if (sqlState == "23505") return SqlWriteFailure.UniqueViolation;
|
||||
if (sqlState.StartsWith("23", StringComparison.Ordinal)) return SqlWriteFailure.IntegrityViolation;
|
||||
if (sqlState.StartsWith("22", StringComparison.Ordinal)) return SqlWriteFailure.DataException;
|
||||
return SqlWriteFailure.Other;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user