From 288ca70c4a0e10e7ae3c1b124cf407690895af52 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 15:41:21 -0500 Subject: [PATCH] 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. --- docs/drivers/Sql.md | 14 ++-- .../Validation/DraftValidator.cs | 1 + .../Validation/SqlTagDeployChecks.cs | 63 +++++++++++++++++ .../DraftValidatorSqlNamedQueryTests.cs | 68 +++++++++++++++++++ 4 files changed, 142 insertions(+), 4 deletions(-) create mode 100644 tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DraftValidatorSqlNamedQueryTests.cs diff --git a/docs/drivers/Sql.md b/docs/drivers/Sql.md index d25a5b960..3f80ce098 100644 --- a/docs/drivers/Sql.md +++ b/docs/drivers/Sql.md @@ -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. diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DraftValidator.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DraftValidator.cs index 9d17cb0e9..eaa133a0c 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DraftValidator.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DraftValidator.cs @@ -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)); diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/SqlTagDeployChecks.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/SqlTagDeployChecks.cs index a0a1ad2f9..122c03927 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/SqlTagDeployChecks.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/SqlTagDeployChecks.cs @@ -106,6 +106,69 @@ public static class SqlTagDeployChecks return errors; } + /// Error code for a named query the Sql driver would refuse at construction (lmxopcua#1058). + public const string NamedQueryInvalidCode = "SqlNamedQueryInvalid"; + + /// + /// The driver factory's config reader options (SqlDriverFactoryExtensions.JsonOptions, 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. + /// + 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() }, + }; + + /// + /// lmxopcua#1058 (#974 follow-up). The driver checks every queries entry with + /// under its provider when it is constructed, and ONE refused query + /// fails the whole driver — every tag on it reads BadNodeIdUnknown. Since #974 that includes a T-SQL + /// ScriptDom parse for SqlServer / Odbc, so an Odbc query written in another dialect (PostgreSQL :: casts, + /// LIMIT) 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. + /// + /// The snapshot being validated. + /// One error per refused named query. + public static IReadOnlyList NamedQueryErrors(DraftSnapshot draft) + { + var errors = new List(); + 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(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; + } + /// The merged config's provider (default SqlServer), or null when it is not a provider name. private static SqlProvider? ReadProvider(DriverInstance driver, List devices) { diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DraftValidatorSqlNamedQueryTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DraftValidatorSqlNamedQueryTests.cs new file mode 100644 index 000000000..7611011b4 --- /dev/null +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DraftValidatorSqlNamedQueryTests.cs @@ -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; + +/// +/// lmxopcua#1058 (#974 follow-up): a Sql driver's named query is checked by +/// SqlNamedQueryRules.Describe 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. +/// +[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); +}