fix(sql): #1058 deploy gate refuses a named query the Sql driver would refuse at start (SqlNamedQueryInvalid)

The driver runs SqlNamedQueryRules.Describe over every queries entry with its provider at
construction, and one refused query fails the whole driver (every tag BadNodeIdUnknown). Since #974
that includes a T-SQL parse for SqlServer/Odbc/no-provider, so an Odbc query written in another
dialect (LIMIT, ILIKE, 'a'::text) that used to pass is refused after the upgrade. The gate now runs
the same rule over the same merged config (factory-equivalent JSON options), naming the instance.
Noted: a bare col::type PARSES as T-SQL static-member syntax and is accepted by both.
This commit is contained in:
Joseph Doherty
2026-12-03 15:41:21 -05:00
parent 49213e52e4
commit 288ca70c4a
4 changed files with 142 additions and 4 deletions
+10 -4
View File
@@ -223,9 +223,11 @@ row:
`SELECT`**, with no `INTO` and no `OPENQUERY` / `OPENROWSET` / `OPENDATASOURCE` (they run text on another
server or read a file). CTEs, subqueries, window functions, `UNION`, `OPTION (…)` and `@name` parameters
are ordinary `SELECT`s and pass. An Odbc statement's positional `?` markers are read as variables for the
parse; anything else SQL Server's grammar does not accept — a PostgreSQL `::` cast, `LIMIT`, a T-SQL
reserved word used as a bare alias (`AS top`) — is refused on Odbc, so quote or rename it. The lexical
rules remain as a second, independent layer.
parse; anything else SQL Server's grammar does not accept — a PostgreSQL `::` cast of a literal or an
expression (`'a'::text`, `(v)::numeric`), `LIMIT`, `ILIKE`, a T-SQL reserved word used as a bare alias
(`AS top`) — is refused on Odbc, so quote or rename it. (`col::type` between two bare identifiers happens
to PARSE as T-SQL static-member syntax and is accepted.) The lexical rules remain as a second, independent
layer.
- **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
@@ -242,7 +244,11 @@ row:
**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.
driver** instead, because every tag that names it would otherwise go dark unexplained. Since lmxopcua#1058
the **deploy gate refuses it first** (`SqlNamedQueryInvalid`, naming the driver instance): it runs the same
`SqlNamedQueryRules.Describe` over the same merged config with the instance's provider. Before upgrading
a deployment that has Odbc drivers, run the [upgrade preflight](../v2/upgrade-preflight.md), which lists
every stored query the new guard refuses.
- Query tags read no table, so they need **no catalog gate** — a driver serving only named queries skips
the catalog load entirely. Nothing from a Query tag is ever quoted into SQL.
@@ -46,6 +46,7 @@ public static class DraftValidator
ValidateSqlConnectionStringNotPersisted(draft, errors);
errors.AddRange(SqlTagDeployChecks.UndeclaredQueryErrors(draft));
errors.AddRange(SqlTagDeployChecks.WriteBlockErrors(draft));
errors.AddRange(SqlTagDeployChecks.NamedQueryErrors(draft));
ValidateMTConnectSingleDevice(draft, errors);
errors.AddRange(HeidenhainDeployChecks.Errors(draft));
errors.AddRange(CredentialReferenceDeployChecks.Errors(draft));
@@ -106,6 +106,69 @@ public static class SqlTagDeployChecks
return errors;
}
/// <summary>Error code for a named query the Sql driver would refuse at construction (lmxopcua#1058).</summary>
public const string NamedQueryInvalidCode = "SqlNamedQueryInvalid";
/// <summary>
/// The driver factory's config reader options (<c>SqlDriverFactoryExtensions.JsonOptions</c>, which lives in the
/// driver assembly this one does not reference): case-insensitive, comments + trailing commas tolerated, unknown
/// members skipped, enums by name. Keep in step — a looser reader here could pass a blob the driver refuses.
/// </summary>
private static readonly JsonSerializerOptions SqlConfigJson = new()
{
PropertyNameCaseInsensitive = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
ReadCommentHandling = JsonCommentHandling.Skip,
AllowTrailingCommas = true,
UnmappedMemberHandling = System.Text.Json.Serialization.JsonUnmappedMemberHandling.Skip,
Converters = { new System.Text.Json.Serialization.JsonStringEnumConverter() },
};
/// <summary>
/// lmxopcua#1058 (#974 follow-up). The driver checks every <c>queries</c> entry with
/// <see cref="SqlNamedQueryRules.Describe"/> under its provider when it is constructed, and ONE refused query
/// fails the whole driver — every tag on it reads <c>BadNodeIdUnknown</c>. Since #974 that includes a T-SQL
/// ScriptDom parse for SqlServer / Odbc, so an Odbc query written in another dialect (PostgreSQL <c>::</c> casts,
/// <c>LIMIT</c>) that used to pass is refused. This runs the same rule over the same merged config (DriverConfig
/// plus, for a single-device instance, the DeviceConfig) so the deploy refuses what the driver would. A blob that
/// does not parse, or names an unknown provider, is left to the driver's own construction error.
/// </summary>
/// <param name="draft">The snapshot being validated.</param>
/// <returns>One error per refused named query.</returns>
public static IReadOnlyList<ValidationError> NamedQueryErrors(DraftSnapshot draft)
{
var errors = new List<ValidationError>();
foreach (var (driver, devices) in SqlInstances(draft))
{
SqlDriverConfigDto? dto;
try
{
var merged = DriverDeviceConfigMerger.Merge(
driver.DriverConfig, devices.Select(d => new DriverDeviceConfigMerger.DeviceRow(d.Name, d.DeviceConfig)).ToList(), []);
dto = JsonSerializer.Deserialize<SqlDriverConfigDto>(merged, SqlConfigJson);
}
catch (JsonException)
{
continue;
}
if (dto?.Queries is not { Count: > 0 } queries) continue;
foreach (var (name, query) in queries.OrderBy(q => q.Key, StringComparer.Ordinal))
{
if (SqlNamedQueryRules.Describe(name, query, dto.Provider) is not { } problem) continue;
errors.Add(new(NamedQueryInvalidCode,
$"Sql driver instance '{driver.DriverInstanceId}' (provider {dto.Provider}): {problem} — the driver " +
"refuses its whole config at start, so every tag on it would read BadNodeIdUnknown. Rewrite the query " +
(dto.Provider == SqlProvider.Odbc
? "so it parses as a single T-SQL SELECT (an Odbc backend is unknown, so the strictest dialect applies), or use the backend's native provider."
: "as a single read-only SELECT."),
driver.DriverInstanceId));
}
}
return errors;
}
/// <summary>The merged config's <c>provider</c> (default SqlServer), or null when it is not a provider name.</summary>
private static SqlProvider? ReadProvider(DriverInstance driver, List<Device> devices)
{
@@ -0,0 +1,68 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Validation;
namespace ZB.MOM.WW.OtOpcUa.Configuration.Tests;
/// <summary>
/// lmxopcua#1058 (#974 follow-up): a Sql driver's named query is checked by
/// <c>SqlNamedQueryRules.Describe</c> with the instance's provider when the driver is constructed, and ONE refused
/// query fails the whole driver. The deploy gate now runs the same rule over the same merged config, so a config
/// the driver would refuse at start (e.g. an Odbc query written in PostgreSQL that no longer parses as T-SQL) is
/// refused at deploy instead — and the upgrade preflight finds the ones already stored.
/// </summary>
[Trait("Category", "Unit")]
public sealed class DraftValidatorSqlNamedQueryTests
{
private const string Code = SqlTagDeployChecks.NamedQueryInvalidCode;
private static DraftSnapshot Draft(string driverConfig, string deviceConfig = "{}", string driverType = "Sql") => new()
{
GenerationId = 1, ClusterId = "c",
DriverInstances = [new DriverInstance
{ DriverInstanceId = "di", ClusterId = "c", Name = "sql", DriverType = driverType, DriverConfig = driverConfig }],
Devices = [new Device { DeviceId = "dev", DriverInstanceId = "di", Name = "d", DeviceConfig = deviceConfig }],
};
private static string Config(string provider, string sql) =>
"{\"provider\":\"" + provider + "\",\"queries\":{\"line\":{\"sql\":\"" + sql + "\"}}}";
[Theory]
[InlineData("Odbc", "SELECT 'a'::text AS v")] // PostgreSQL cast of a literal: not T-SQL
[InlineData("Odbc", "SELECT (v)::numeric AS v FROM t")] // ... of an expression
[InlineData("Odbc", "SELECT v FROM t WHERE v ILIKE 'a%'")] // ILIKE: not T-SQL
[InlineData("Odbc", "SELECT v FROM t LIMIT 1")] // LIMIT: not T-SQL
[InlineData("SqlServer", "SELECT 1 AS v COMMIT")] // a second statement without ';'
[InlineData("SqlServer", "DELETE FROM t")]
public void A_named_query_the_driver_would_refuse_is_a_deploy_error(string provider, string sql)
{
var errors = DraftValidator.Validate(Draft(Config(provider, sql)));
errors.ShouldContain(e => e.Code == Code && e.Context == "di" && e.Message.Contains("'line'"));
}
[Theory]
[InlineData("Odbc", "SELECT v FROM t WHERE k = ?")]
[InlineData("SqlServer", "SELECT TOP 1 v FROM t")]
[InlineData("Postgres", "SELECT v::int AS v FROM t LIMIT 1")] // native provider: PostgreSQL dialect is fine
// NB: "col::type" (identifier::identifier) PARSES as T-SQL static-member syntax, so the driver accepts it too.
[InlineData("Odbc", "SELECT v::int AS v FROM t")]
public void Positive_control_a_query_the_driver_accepts_is_quiet(string provider, string sql) =>
DraftValidator.Validate(Draft(Config(provider, sql))).ShouldNotContain(e => e.Code == Code);
[Fact]
public void An_absent_provider_reads_as_SqlServer_like_the_driver() =>
DraftValidator.Validate(Draft("""{"queries":{"q":{"sql":"SELECT 1 AS v COMMIT"}}}"""))
.ShouldContain(e => e.Code == Code);
[Fact]
public void Queries_declared_on_the_single_device_config_are_checked() =>
DraftValidator.Validate(Draft("""{"provider":"Odbc"}""", deviceConfig: """{"queries":{"line":{"sql":"SELECT 1 LIMIT 1"}}}"""))
.ShouldContain(e => e.Code == Code);
[Fact]
public void Non_Sql_drivers_are_not_checked() =>
DraftValidator.Validate(Draft(Config("Odbc", "SELECT 1 LIMIT 1"), driverType: "Modbus"))
.ShouldNotContain(e => e.Code == Code);
}