feat(sql): named-query tag model — read-only SELECTs declared on the driver (lmxopcua#753)
SqlTagModel.Query (design §5.4) is now served end to end instead of refused. The driver config declares `queries` (name -> sql, params, maxRows); a tag names the query, the result `column` it reads and optionally a `rowKey` picking its row. - Parser/deploy gate: query + column required, rowKey all-or-nothing; Inspect explains each refusal. Table is not read for this model. - SqlReadOnlyStatement: single SELECT/WITH only, no data/schema-changing keyword outside literals/comments (refuses SELECT INTO, FOR UPDATE, DML CTEs). Shared by the factory and the AdminUI driver form (SqlNamedQueryRules.Describe), so the form refuses what the driver refuses. One bad entry fails the driver. - Parameters are always bound; the factory refuses a declared parameter whose dialect marker the statement never uses. - Reader: one execution per query per poll, inside a transaction that is always rolled back; result columns matched exact-then-unique-CI; no row -> BadNoData, ambiguous row / missing column / over maxRows -> BadConfigurationError. - Catalog gate passes Query tags through (nothing is quoted into SQL); a Query-only driver skips the catalog load. A tag naming an undeclared query is skipped with the reason on /hosts. - AdminUI: typed editor offers Query (query/column/rowKey); driver form edits `queries` as JSON and keeps the last valid set on a typo. (lmxopcua#753) Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV
This commit is contained in:
@@ -40,6 +40,15 @@ public sealed class SqlCatalog
|
||||
_columnsByTable = columnsByTable;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A catalog that resolves nothing — used when no authored tag needs one (a driver serving only named
|
||||
/// queries), so Initialize does not issue catalog queries whose answer nothing reads.
|
||||
/// </summary>
|
||||
internal static SqlCatalog Empty { get; } = new(
|
||||
string.Empty, [],
|
||||
new Dictionary<string, IReadOnlyList<string>>(StringComparer.Ordinal),
|
||||
new Dictionary<string, IReadOnlyList<string>>(StringComparer.Ordinal));
|
||||
|
||||
/// <summary>The schema an unqualified authored object name is resolved in.</summary>
|
||||
public string DefaultSchema { get; }
|
||||
|
||||
|
||||
@@ -77,6 +77,16 @@ public static class SqlCatalogGate
|
||||
foreach (var definition in definitions)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(definition);
|
||||
|
||||
// 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.
|
||||
if (definition.Model == SqlTagModel.Query)
|
||||
{
|
||||
accepted.Add(definition);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (TryCanonicalize(definition, catalog, dialect, out var canonical, out var rejection))
|
||||
accepted.Add(canonical!);
|
||||
else
|
||||
|
||||
@@ -290,7 +290,8 @@ public sealed class SqlDriver
|
||||
maxConcurrentGroups: options.MaxConcurrentGroups,
|
||||
nullIsBad: options.NullIsBad,
|
||||
resolve: rawPath => _resolver.TryResolve(rawPath, out var definition) ? definition : null,
|
||||
logger: _logger);
|
||||
logger: _logger,
|
||||
queries: options.Queries);
|
||||
previous?.Dispose();
|
||||
}
|
||||
|
||||
@@ -966,7 +967,25 @@ public sealed class SqlDriver
|
||||
try
|
||||
{
|
||||
if (SqlEquipmentTagParser.TryParse(entry.TagConfig, entry.RawPath, out var definition))
|
||||
{
|
||||
if (definition.Model == SqlTagModel.Query
|
||||
&& !_options.Queries.ContainsKey(definition.QueryName!))
|
||||
{
|
||||
// The blob is well-formed but names a query this driver's config does not declare — a
|
||||
// fact only the driver can see (the deploy gate inspects one tag blob at a time). Skip
|
||||
// it like any unmappable tag, so it reads BadNodeIdUnknown and /hosts says why.
|
||||
var missing =
|
||||
$"reads named query '{definition.QueryName}', which this driver's config does not " +
|
||||
"declare under 'queries'";
|
||||
blobSkips.Add(new SkippedTag(entry.RawPath, missing));
|
||||
_logger.LogWarning(
|
||||
"Sql tag skipped. Driver={DriverInstanceId} RawPath={RawPath} Reason={Reason}",
|
||||
_driverInstanceId, entry.RawPath, missing);
|
||||
continue;
|
||||
}
|
||||
|
||||
table[entry.RawPath] = definition;
|
||||
}
|
||||
else
|
||||
{
|
||||
// The reason is the DEPLOY GATE's own explanation (R06:S-4) — SqlTagDefinitionFactory.Inspect
|
||||
@@ -1038,17 +1057,22 @@ public sealed class SqlDriver
|
||||
var authored = Tags;
|
||||
if (authored.Count == 0) return;
|
||||
|
||||
// Named-query tags read no table of their own and quote no identifier, so they need no catalog —
|
||||
// SqlCatalogGate passes them through. A driver serving ONLY named queries therefore skips the load.
|
||||
var tables = authored.Values
|
||||
.Where(definition => definition.Model != SqlTagModel.Query)
|
||||
.Select(definition => definition.Table)
|
||||
.Where(table => !string.IsNullOrWhiteSpace(table))
|
||||
.Distinct(StringComparer.OrdinalIgnoreCase)
|
||||
.ToArray();
|
||||
|
||||
var catalog = await RunBoundedAsync(
|
||||
token => LoadCatalogAsync(tables, token),
|
||||
_options.OperationTimeout,
|
||||
"the catalog queries did not return",
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
var catalog = tables.Length == 0
|
||||
? SqlCatalog.Empty
|
||||
: await RunBoundedAsync(
|
||||
token => LoadCatalogAsync(tables, token),
|
||||
_options.OperationTimeout,
|
||||
"the catalog queries did not return",
|
||||
cancellationToken).ConfigureAwait(false);
|
||||
|
||||
var result = SqlCatalogGate.Apply(authored.Values, catalog, _dialect);
|
||||
|
||||
|
||||
@@ -115,7 +115,7 @@ public static class SqlDriverFactoryExtensions
|
||||
// Resolved BEFORE the knob validation in CreateInstance, so that every subsequent throw is a path
|
||||
// that HAS the secret in hand — which is exactly where a careless interpolation would leak it.
|
||||
var connectionString = SqlConnectionStringResolver.Resolve(dto.ConnectionStringRef!);
|
||||
return new SqlDriverBinding(BuildOptions(dto, driverInstanceId), dialect, connectionString, dto);
|
||||
return new SqlDriverBinding(BuildOptions(dto, driverInstanceId, dialect), dialect, connectionString, dto);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -237,9 +237,16 @@ public static class SqlDriverFactoryExtensions
|
||||
/// </summary>
|
||||
/// <param name="dto">The deserialised config blob.</param>
|
||||
/// <param name="driverInstanceId">Named in every rejection message, so a fleet-wide log identifies the row.</param>
|
||||
/// <param name="dialect">
|
||||
/// The provider seam, for the named-query marker check; null skips that one check (unit tests of the
|
||||
/// other knobs).
|
||||
/// </param>
|
||||
/// <returns>The typed options the driver is constructed with.</returns>
|
||||
/// <exception cref="InvalidOperationException">A knob is out of range, or the two deadlines are inverted.</exception>
|
||||
internal static SqlDriverOptions BuildOptions(SqlDriverConfigDto dto, string driverInstanceId)
|
||||
/// <exception cref="InvalidOperationException">
|
||||
/// A knob is out of range, the two deadlines are inverted, or a named query is unusable.
|
||||
/// </exception>
|
||||
internal static SqlDriverOptions BuildOptions(
|
||||
SqlDriverConfigDto dto, string driverInstanceId, ISqlDialect? dialect = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(dto);
|
||||
|
||||
@@ -280,9 +287,71 @@ public static class SqlDriverFactoryExtensions
|
||||
CommandTimeout = commandTimeout,
|
||||
MaxConcurrentGroups = maxConcurrentGroups,
|
||||
NullIsBad = dto.NullIsBad ?? false,
|
||||
Queries = BuildQueries(dto, driverInstanceId, dialect),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Validates and types the config's named queries (design §5.4). <b>One unusable entry fails the
|
||||
/// driver</b>: unlike a tag, a query is shared by every tag that names it, and a driver that silently
|
||||
/// dropped it would turn all of them into an unexplained <c>BadNodeIdUnknown</c>.
|
||||
/// <para>The shape rules are <see cref="SqlNamedQueryRules.Describe"/> — the same call the AdminUI driver
|
||||
/// form makes — so the form refuses what this refuses. The one rule added here needs the dialect: every
|
||||
/// declared parameter's marker (<see cref="ISqlDialect.ParameterMarker"/>) must appear in the statement.
|
||||
/// A provider that binds positionally (<c>?</c>) is exempt, since there is no name to look for.</para>
|
||||
/// </summary>
|
||||
private static IReadOnlyDictionary<string, SqlNamedQuery> BuildQueries(
|
||||
SqlDriverConfigDto dto, string driverInstanceId, ISqlDialect? dialect)
|
||||
{
|
||||
var queries = new Dictionary<string, SqlNamedQuery>(StringComparer.Ordinal);
|
||||
if (dto.Queries is not { Count: > 0 } authored) return queries;
|
||||
|
||||
foreach (var (name, query) in authored)
|
||||
{
|
||||
if (SqlNamedQueryRules.Describe(name, query) is { } problem)
|
||||
throw new InvalidOperationException($"Sql driver config for '{driverInstanceId}': {problem}.");
|
||||
|
||||
SqlReadOnlyStatement.Check(query.Sql, out var sql);
|
||||
var names = new List<string>();
|
||||
var values = new List<object?>();
|
||||
foreach (var (key, value) in query.Params ?? [])
|
||||
{
|
||||
var bare = SqlNamedQueryRules.NormaliseParameterName(key)!;
|
||||
if (dialect is not null)
|
||||
{
|
||||
var marker = dialect.ParameterMarker(bare);
|
||||
if (marker != "?" && !SqlReadOnlyStatement.UsesMarker(sql, marker))
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"Sql driver config for '{driverInstanceId}': named query '{name}' declares parameter " +
|
||||
$"'{bare}', but its statement never uses the {dialect.Provider} marker '{marker}'.");
|
||||
}
|
||||
}
|
||||
|
||||
names.Add(bare);
|
||||
values.Add(ToParameterValue(value));
|
||||
}
|
||||
|
||||
queries[name] = new SqlNamedQuery(
|
||||
name, sql, names, values, query.MaxRows ?? SqlNamedQueryRules.DefaultMaxRows);
|
||||
}
|
||||
|
||||
return queries;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts a validated JSON scalar to the CLR value bound for it: text, a 64-bit integer when the number
|
||||
/// is integral, otherwise a double, a boolean, or null (bound as <c>DBNull</c>).
|
||||
/// </summary>
|
||||
private static object? ToParameterValue(JsonElement value) => value.ValueKind switch
|
||||
{
|
||||
JsonValueKind.String => value.GetString(),
|
||||
JsonValueKind.Number => value.TryGetInt64(out var integral) ? integral : value.GetDouble(),
|
||||
JsonValueKind.True => true,
|
||||
JsonValueKind.False => false,
|
||||
_ => null,
|
||||
};
|
||||
|
||||
/// <summary>Rejects a non-positive duration, naming the authored field.</summary>
|
||||
private static void RequirePositive(TimeSpan value, string field, string driverInstanceId)
|
||||
{
|
||||
|
||||
@@ -53,4 +53,27 @@ public sealed class SqlDriverOptions
|
||||
/// It never governs an absent row, which is always <see cref="SqlStatusCodes.BadNoData"/>.
|
||||
/// </summary>
|
||||
public bool NullIsBad { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// The validated named queries (design §5.4) a <see cref="SqlTagModel.Query"/> tag reads by name, keyed
|
||||
/// ordinally. Empty when the config declares none.
|
||||
/// </summary>
|
||||
public IReadOnlyDictionary<string, SqlNamedQuery> Queries { get; init; } =
|
||||
new Dictionary<string, SqlNamedQuery>(StringComparer.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// One validated named query — what <see cref="SqlNamedQueryDto"/> becomes once the factory has checked it
|
||||
/// (<see cref="SqlNamedQueryRules.Describe"/> plus the dialect's marker check).
|
||||
/// </summary>
|
||||
/// <param name="Name">The <c>queries</c> key tags reference.</param>
|
||||
/// <param name="Sql">The normalised single read-only statement (no trailing terminator).</param>
|
||||
/// <param name="ParameterNames">The bare parameter base names, in authored order.</param>
|
||||
/// <param name="ParameterValues">The values bound under <paramref name="ParameterNames"/>, aligned index-for-index.</param>
|
||||
/// <param name="MaxRows">The per-poll row ceiling; one row more refuses the whole query.</param>
|
||||
public sealed record SqlNamedQuery(
|
||||
string Name,
|
||||
string Sql,
|
||||
IReadOnlyList<string> ParameterNames,
|
||||
IReadOnlyList<object?> ParameterValues,
|
||||
int MaxRows);
|
||||
|
||||
@@ -56,12 +56,18 @@ public static class SqlGroupPlanner
|
||||
/// <see cref="ISqlDialect.QuoteIdentifier"/>). <see cref="SqlEquipmentTagParser"/> rejects all of these
|
||||
/// up front, so reaching one here means a caller built a definition by hand with a broken invariant.
|
||||
/// </exception>
|
||||
/// <exception cref="NotSupportedException">
|
||||
/// A tag carries <see cref="SqlTagModel.Query"/> (design §5.4, deferred to P3).
|
||||
/// <b>Deliberately loud rather than skipped:</b> silently dropping a tag would leave an authored node
|
||||
/// permanently unfed with nothing in the log, and the parser makes this branch unreachable in practice.
|
||||
/// </exception>
|
||||
public static IReadOnlyList<SqlQueryPlan> Plan(IEnumerable<SqlTagDefinition> tags, ISqlDialect dialect)
|
||||
/// <exception cref="NotSupportedException">A tag carries a model this planner does not know.</exception>
|
||||
/// <param name="queries">
|
||||
/// The driver's validated named queries, which a <see cref="SqlTagModel.Query"/> tag needs: every tag
|
||||
/// naming one query folds into ONE plan running that query's own statement (design §5.4). Null when the
|
||||
/// driver declares none; a Query tag naming a query this does not hold throws
|
||||
/// <see cref="ArgumentException"/> (the driver drops such tags at Initialize, so that is a broken caller
|
||||
/// invariant).
|
||||
/// </param>
|
||||
public static IReadOnlyList<SqlQueryPlan> Plan(
|
||||
IEnumerable<SqlTagDefinition> tags,
|
||||
ISqlDialect dialect,
|
||||
IReadOnlyDictionary<string, SqlNamedQuery>? queries = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(tags);
|
||||
ArgumentNullException.ThrowIfNull(dialect);
|
||||
@@ -97,6 +103,9 @@ public static class SqlGroupPlanner
|
||||
case SqlTagModel.WideRow:
|
||||
plans.Add(BuildWideRowPlan(key, members, dialect));
|
||||
break;
|
||||
case SqlTagModel.Query:
|
||||
plans.Add(BuildQueryPlan(key, members, dialect, queries));
|
||||
break;
|
||||
default:
|
||||
throw UnsupportedModel(members[0]);
|
||||
}
|
||||
@@ -106,8 +115,8 @@ public static class SqlGroupPlanner
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Composes the equality key that decides which tags share a query. Both models produce a 5-tuple whose
|
||||
/// first element is the model, so a key-value key can never compare equal to a wide-row key.
|
||||
/// Composes the equality key that decides which tags share a query. Every model produces a 5-tuple whose
|
||||
/// first element is the model, so keys of different models can never compare equal.
|
||||
/// <list type="bullet">
|
||||
/// <item>
|
||||
/// <see cref="SqlTagModel.KeyValue"/> → <c>(model, table, keyColumn, valueColumn, timestampColumn)</c>.
|
||||
@@ -131,9 +140,49 @@ public static class SqlGroupPlanner
|
||||
SqlTagModel.KeyValue => (tag.Model, tag.Table, tag.KeyColumn, tag.ValueColumn, tag.TimestampColumn),
|
||||
SqlTagModel.WideRow => (tag.Model, tag.Table, tag.RowSelectorColumn, tag.RowSelectorValue,
|
||||
tag.RowSelectorTopByTimestamp),
|
||||
// One execution per named query, whatever columns or rows its members pick out of the result.
|
||||
SqlTagModel.Query => (tag.Model, tag.QueryName, (string?)null, (string?)null, (string?)null),
|
||||
_ => throw UnsupportedModel(tag),
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Emits one plan for a named query: the query's own (already-validated, read-only) statement, with
|
||||
/// each declared parameter spelled by the dialect's marker and bound under its bind name.
|
||||
/// <para><b>No identifier from a tag reaches this text.</b> A Query tag's <c>column</c>,
|
||||
/// <c>rowKey.column</c> and <c>timestampColumn</c> are matched against the result set's column names
|
||||
/// by the reader; they are never quoted into SQL, so they need no catalog gate.</para>
|
||||
/// <para><b>The row cap is client-side only.</b> An arbitrary statement cannot be wrapped in a
|
||||
/// provider row limit portably (a T-SQL CTE cannot sit in a derived table), so
|
||||
/// <see cref="SqlQueryPlan.RowCap"/> is the query's <c>maxRows</c> and the reader stops reading one row
|
||||
/// past it.</para>
|
||||
/// </summary>
|
||||
private static SqlQueryPlan BuildQueryPlan(
|
||||
object groupKey,
|
||||
List<SqlTagDefinition> members,
|
||||
ISqlDialect dialect,
|
||||
IReadOnlyDictionary<string, SqlNamedQuery>? queries)
|
||||
{
|
||||
var first = members[0];
|
||||
var name = first.QueryName;
|
||||
if (string.IsNullOrWhiteSpace(name)) throw MissingField(nameof(SqlTagDefinition.QueryName), first);
|
||||
if (queries is null || !queries.TryGetValue(name, out var query))
|
||||
throw new ArgumentException(
|
||||
$"Sql tag '{first.Name}' reads named query '{name}', which the driver config does not define.",
|
||||
nameof(queries));
|
||||
|
||||
var markers = new List<string>(query.ParameterNames.Count);
|
||||
var bindNames = new List<string>(query.ParameterNames.Count);
|
||||
foreach (var parameter in query.ParameterNames)
|
||||
{
|
||||
markers.Add(dialect.ParameterMarker(parameter));
|
||||
bindNames.Add(dialect.ParameterBindName(parameter));
|
||||
}
|
||||
|
||||
return new SqlQueryPlan(
|
||||
SqlTagModel.Query, groupKey, query.Sql, markers, bindNames, query.ParameterValues, members,
|
||||
SelectedColumns: [], RowCap: query.MaxRows);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Emits one key-value plan per <b>chunk</b> of the group's distinct keys, sized by
|
||||
/// <see cref="ISqlDialect.MaxBindParameters"/>. A group at or under the ceiling — every ordinary group
|
||||
@@ -346,6 +395,5 @@ public static class SqlGroupPlanner
|
||||
=> new($"Sql tag '{tag.Name}' ({tag.Model}) is missing the required '{field}'.");
|
||||
|
||||
private static NotSupportedException UnsupportedModel(SqlTagDefinition tag)
|
||||
=> new($"Sql tag '{tag.Name}' uses the {tag.Model} model, which the poll planner does not support. " +
|
||||
"v1 plans KeyValue and WideRow only; the named-query model is deferred (design §5.4).");
|
||||
=> new($"Sql tag '{tag.Name}' uses the {tag.Model} model, which the poll planner does not support.");
|
||||
}
|
||||
|
||||
@@ -52,6 +52,9 @@ public sealed class SqlPollReader : IDisposable
|
||||
private readonly Func<string, SqlTagDefinition?> _resolve;
|
||||
private readonly ILogger _logger;
|
||||
|
||||
/// <summary>The driver's validated named queries, for <see cref="SqlTagModel.Query"/> plans.</summary>
|
||||
private readonly IReadOnlyDictionary<string, SqlNamedQuery>? _queries;
|
||||
|
||||
/// <summary>
|
||||
/// Caps concurrently executing group queries — and therefore concurrently held connections
|
||||
/// (design §8.4). Disposed by <see cref="Dispose"/> only once every group that ever acquired it has
|
||||
@@ -132,6 +135,11 @@ public sealed class SqlPollReader : IDisposable
|
||||
/// straight through.
|
||||
/// </param>
|
||||
/// <param name="logger">Optional; defaults to a no-op logger.</param>
|
||||
/// <param name="queries">
|
||||
/// The driver's validated named queries (design §5.4); null when it declares none, in which case a
|
||||
/// <see cref="SqlTagModel.Query"/> definition cannot be planned and publishes
|
||||
/// <see cref="SqlStatusCodes.BadConfigurationError"/>.
|
||||
/// </param>
|
||||
/// <exception cref="ArgumentNullException">A required reference argument is null.</exception>
|
||||
/// <exception cref="ArgumentException"><paramref name="connectionString"/> is blank.</exception>
|
||||
/// <exception cref="ArgumentOutOfRangeException">A timeout is non-positive, or the cap is below 1.</exception>
|
||||
@@ -144,7 +152,8 @@ public sealed class SqlPollReader : IDisposable
|
||||
int maxConcurrentGroups,
|
||||
bool nullIsBad,
|
||||
Func<string, SqlTagDefinition?> resolve,
|
||||
ILogger? logger = null)
|
||||
ILogger? logger = null,
|
||||
IReadOnlyDictionary<string, SqlNamedQuery>? queries = null)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(factory);
|
||||
ArgumentNullException.ThrowIfNull(dialect);
|
||||
@@ -163,6 +172,7 @@ public sealed class SqlPollReader : IDisposable
|
||||
_nullIsBad = nullIsBad;
|
||||
_resolve = resolve;
|
||||
_logger = logger ?? NullLogger.Instance;
|
||||
_queries = queries;
|
||||
_gate = new SemaphoreSlim(maxConcurrentGroups, maxConcurrentGroups);
|
||||
}
|
||||
|
||||
@@ -276,7 +286,7 @@ public sealed class SqlPollReader : IDisposable
|
||||
|
||||
try
|
||||
{
|
||||
return new PollShape(resolved, definitions, slots, SqlGroupPlanner.Plan(definitions, _dialect), PlanningFailed: false);
|
||||
return new PollShape(resolved, definitions, slots, SqlGroupPlanner.Plan(definitions, _dialect, _queries), PlanningFailed: false);
|
||||
}
|
||||
catch (Exception ex) when (ex is ArgumentException or NotSupportedException)
|
||||
{
|
||||
@@ -516,7 +526,7 @@ public sealed class SqlPollReader : IDisposable
|
||||
_logger.LogWarning(
|
||||
"Sql poll group ({Model}, '{Table}', {Members} tag(s)) exceeded the {Timeout} ms operation " +
|
||||
"timeout; publishing BadTimeout. Repeats for this group are suppressed for {Interval} s.",
|
||||
plan.Model, plan.Members[0].Table, plan.Members.Count,
|
||||
plan.Model, DescribeSource(plan), plan.Members.Count,
|
||||
(int)_operationTimeout.TotalMilliseconds, (int)ContractWarningInterval.TotalSeconds);
|
||||
}
|
||||
|
||||
@@ -546,12 +556,25 @@ public sealed class SqlPollReader : IDisposable
|
||||
|
||||
try
|
||||
{
|
||||
// A named query is operator-authored SQL. The authoring guard (SqlReadOnlyStatement) already
|
||||
// refused anything that is not a single SELECT, and this is the backstop behind it: the
|
||||
// statement runs inside a transaction that is ALWAYS rolled back, so a side effect the guard
|
||||
// could not see (a function that writes) is never committed. Disposing the transaction without
|
||||
// a commit rolls it back, including on the timeout/abandon path.
|
||||
var transaction = plan.Model == SqlTagModel.Query
|
||||
? await connection.BeginTransactionAsync(cancellationToken).ConfigureAwait(false)
|
||||
: null;
|
||||
await using var rollback = transaction is null
|
||||
? null
|
||||
: new RollbackOnDispose(transaction);
|
||||
|
||||
var command = connection.CreateCommand();
|
||||
await using (command.ConfigureAwait(false))
|
||||
{
|
||||
// Before any parameter is added: on ODP.NET this is what turns bind-by-position off, and
|
||||
// a positionally-bound IN list feeds one tag's value to another tag's node in silence.
|
||||
_dialect.ConfigureCommand(command);
|
||||
command.Transaction = transaction;
|
||||
command.CommandText = plan.SqlText;
|
||||
command.CommandTimeout = _commandTimeoutSeconds;
|
||||
for (var i = 0; i < plan.ParameterBindNames.Count; i++)
|
||||
@@ -583,9 +606,10 @@ public sealed class SqlPollReader : IDisposable
|
||||
if (ShouldWarn("failed:" + plan.SqlText))
|
||||
{
|
||||
_logger.LogWarning(
|
||||
ex, "Sql poll group ({Model}, {Members} tag(s)) failed: {Sql}. Repeats for this group are " +
|
||||
"suppressed for {Interval} s.",
|
||||
plan.Model, plan.Members.Count, plan.SqlText, (int)ContractWarningInterval.TotalSeconds);
|
||||
ex, "Sql poll group ({Model}, {Source}, {Members} tag(s)) failed: {Sql}. Repeats for this " +
|
||||
"group are suppressed for {Interval} s.",
|
||||
plan.Model, DescribeSource(plan), plan.Members.Count, plan.SqlText,
|
||||
(int)ContractWarningInterval.TotalSeconds);
|
||||
}
|
||||
return GroupResult.Failed;
|
||||
}
|
||||
@@ -600,7 +624,11 @@ public sealed class SqlPollReader : IDisposable
|
||||
private async Task<GroupResult> MaterialiseAsync(
|
||||
SqlQueryPlan plan, DbDataReader reader, CancellationToken cancellationToken)
|
||||
{
|
||||
var selected = plan.SelectedColumns;
|
||||
// A named query's projection is the operator's, not the planner's: read every result column, by the
|
||||
// name the result set reports. A duplicated name keeps its first ordinal.
|
||||
IReadOnlyList<string> selected = plan.Model == SqlTagModel.Query
|
||||
? ResultColumnNames(reader)
|
||||
: plan.SelectedColumns;
|
||||
var ordinals = new int[selected.Count];
|
||||
var typeNames = new string[selected.Count];
|
||||
var columnIndex = new Dictionary<string, int>(selected.Count, StringComparer.Ordinal);
|
||||
@@ -609,9 +637,9 @@ public sealed class SqlPollReader : IDisposable
|
||||
// GetOrdinal rather than the position in SelectedColumns: the list is documented to be in
|
||||
// ordinal order, but resolving it against the live result set is what makes a wrong slice
|
||||
// impossible rather than merely unlikely.
|
||||
ordinals[c] = reader.GetOrdinal(selected[c]);
|
||||
ordinals[c] = plan.Model == SqlTagModel.Query ? c : reader.GetOrdinal(selected[c]);
|
||||
typeNames[c] = SafeTypeName(reader, ordinals[c]);
|
||||
columnIndex[selected[c]] = c;
|
||||
columnIndex.TryAdd(selected[c], c);
|
||||
}
|
||||
|
||||
// The client-side half of the row cap (R06:S-1): the statement already asks for RowCap + 1 rows, but a
|
||||
@@ -633,15 +661,20 @@ public sealed class SqlPollReader : IDisposable
|
||||
if (ShouldWarn("rowcap:" + plan.SqlText))
|
||||
{
|
||||
var first = plan.Members[0];
|
||||
var selector = plan.Model == SqlTagModel.KeyValue
|
||||
? string.Concat(first.KeyColumn, " IN (", (rowCap / 2).ToString(CultureInfo.InvariantCulture), " key(s))")
|
||||
: string.Concat(first.RowSelectorColumn, " = ", first.RowSelectorValue);
|
||||
var selector = plan.Model switch
|
||||
{
|
||||
SqlTagModel.KeyValue => string.Concat(
|
||||
first.KeyColumn, " IN (", (rowCap / 2).ToString(CultureInfo.InvariantCulture), " key(s))"),
|
||||
SqlTagModel.Query => "maxRows",
|
||||
_ => string.Concat(first.RowSelectorColumn, " = ", first.RowSelectorValue),
|
||||
};
|
||||
_logger.LogWarning(
|
||||
"Sql poll source '{Table}' returned more rows than the {Model} selector '{Selector}' can attribute " +
|
||||
"(at most {Cap}) in one poll, so the selector is ambiguous — a history/events table, or a " +
|
||||
"where column that is not unique. Its {Members} tag(s) publish BadConfigurationError and " +
|
||||
"nothing past row {Limit} is read. Point the tag at a current-values table or a latest-row view.",
|
||||
first.Table, plan.Model, selector, rowCap, plan.Members.Count, rowCap + 1);
|
||||
"nothing past row {Limit} is read. Point the tag at a current-values table or a latest-row view " +
|
||||
"(for a named query: narrow its WHERE, or raise its maxRows).",
|
||||
DescribeSource(plan), plan.Model, selector, rowCap, plan.Members.Count, rowCap + 1);
|
||||
}
|
||||
|
||||
return GroupResult.RowCapExceeded;
|
||||
@@ -699,6 +732,11 @@ public sealed class SqlPollReader : IDisposable
|
||||
{
|
||||
snapshot = new DataValueSnapshot(null, outcome.FailureStatus, null, readAt);
|
||||
}
|
||||
else if (plan.Model == SqlTagModel.Query)
|
||||
{
|
||||
snapshot = MapQueryMember(plan, member, outcome, readAt, out var refused);
|
||||
refusedSome |= refused;
|
||||
}
|
||||
else if (duplicatedKeys is not null && member.KeyValue is { } key && duplicatedKeys.Contains(key))
|
||||
{
|
||||
// More than one row for THIS tag's key: its selector is ambiguous — the same rule a where-pair
|
||||
@@ -834,6 +872,105 @@ public sealed class SqlPollReader : IDisposable
|
||||
// No row: the key was deleted, or the row selector matched nothing. Distinct from a NULL cell.
|
||||
if (row is null) return new DataValueSnapshot(null, SqlStatusCodes.BadNoData, null, readAt);
|
||||
|
||||
return MapCell(member, outcome, row, valueColumn, timestampColumn, readAt);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Maps one <see cref="SqlTagModel.Query"/> member: resolves its <c>column</c> (and <c>rowKey</c> /
|
||||
/// <c>timestampColumn</c>) against the result set's own column names, picks its row, and maps the cell.
|
||||
/// <list type="bullet">
|
||||
/// <item>A <c>column</c> or <c>rowKey.column</c> the result does not carry is an authoring fault the
|
||||
/// database just proved: <see cref="SqlStatusCodes.BadConfigurationError"/>, counted as answered.</item>
|
||||
/// <item>No row for the member (an empty result, or no row whose key matches): <see cref="SqlStatusCodes.BadNoData"/>.</item>
|
||||
/// <item>More than one candidate row (no rowKey and a multi-row result, or a duplicated key): the
|
||||
/// selector is ambiguous, so <see cref="SqlStatusCodes.BadConfigurationError"/> — never "last row wins".</item>
|
||||
/// </list>
|
||||
/// Column names match exactly first, then by a unique case-insensitive match (Postgres folds an unquoted
|
||||
/// alias to lower case, Oracle to upper case), the same rule the catalog gate applies to identifiers.
|
||||
/// </summary>
|
||||
private DataValueSnapshot MapQueryMember(
|
||||
SqlQueryPlan plan, SqlTagDefinition member, GroupResult outcome, DateTime readAt, out bool refused)
|
||||
{
|
||||
refused = false;
|
||||
var columns = outcome.ColumnIndex.Keys.ToArray();
|
||||
if (!SqlCatalog.TryMatch(columns, member.ColumnName ?? string.Empty, out var valueColumn))
|
||||
{
|
||||
refused = true;
|
||||
WarnQueryColumnMissing(plan, member, member.ColumnName, columns);
|
||||
return new DataValueSnapshot(null, SqlStatusCodes.BadConfigurationError, null, readAt);
|
||||
}
|
||||
|
||||
object?[]? row;
|
||||
if (member.RowKeyColumn is { } keyColumn)
|
||||
{
|
||||
if (!SqlCatalog.TryMatch(columns, keyColumn, out var resolvedKey))
|
||||
{
|
||||
refused = true;
|
||||
WarnQueryColumnMissing(plan, member, keyColumn, columns);
|
||||
return new DataValueSnapshot(null, SqlStatusCodes.BadConfigurationError, null, readAt);
|
||||
}
|
||||
|
||||
var keyAt = outcome.ColumnIndex[resolvedKey];
|
||||
row = null;
|
||||
var matches = 0;
|
||||
foreach (var candidate in outcome.Rows)
|
||||
{
|
||||
// Matched as text, exactly as a key-value key is: the authored value is configuration text.
|
||||
if (candidate[keyAt] is not { } cell
|
||||
|| !string.Equals(Convert.ToString(cell, CultureInfo.InvariantCulture), member.RowKeyValue,
|
||||
StringComparison.Ordinal))
|
||||
continue;
|
||||
row = candidate;
|
||||
matches++;
|
||||
}
|
||||
|
||||
if (matches > 1)
|
||||
{
|
||||
refused = true;
|
||||
return new DataValueSnapshot(null, SqlStatusCodes.BadConfigurationError, null, readAt);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (outcome.Rows.Count > 1)
|
||||
{
|
||||
refused = true;
|
||||
return new DataValueSnapshot(null, SqlStatusCodes.BadConfigurationError, null, readAt);
|
||||
}
|
||||
|
||||
row = outcome.Rows.Count == 1 ? outcome.Rows[0] : null;
|
||||
}
|
||||
|
||||
if (row is null) return new DataValueSnapshot(null, SqlStatusCodes.BadNoData, null, readAt);
|
||||
|
||||
string? timestampColumn = null;
|
||||
if (!string.IsNullOrWhiteSpace(member.TimestampColumn)
|
||||
&& SqlCatalog.TryMatch(columns, member.TimestampColumn, out var resolvedTimestamp))
|
||||
timestampColumn = resolvedTimestamp;
|
||||
|
||||
return MapCell(member, outcome, row, valueColumn, timestampColumn, readAt);
|
||||
}
|
||||
|
||||
/// <summary>Rate-limited warning for a Query tag naming a column its query does not project.</summary>
|
||||
private void WarnQueryColumnMissing(
|
||||
SqlQueryPlan plan, SqlTagDefinition member, string? column, IReadOnlyList<string> returned)
|
||||
{
|
||||
if (!ShouldWarn("querycolumn:" + plan.SqlText + "\0" + column)) return;
|
||||
_logger.LogWarning(
|
||||
"Sql tag '{Tag}' reads column '{Column}', which named query '{Query}' does not return (or matches more " +
|
||||
"than one returned column by case); it publishes BadConfigurationError. Returned columns: {Columns}.",
|
||||
member.Name, column, member.QueryName, string.Join(", ", returned));
|
||||
}
|
||||
|
||||
/// <summary>Maps one present row's cell to a snapshot: value, quality, and source timestamp.</summary>
|
||||
private DataValueSnapshot MapCell(
|
||||
SqlTagDefinition member,
|
||||
GroupResult outcome,
|
||||
object?[] row,
|
||||
string? valueColumn,
|
||||
string? timestampColumn,
|
||||
DateTime readAt)
|
||||
{
|
||||
// A timestamp that will not parse falls back to the poll clock rather than poisoning a good value.
|
||||
var sourceTimestamp = ReadTimestamp(outcome, row, timestampColumn) ?? readAt;
|
||||
|
||||
@@ -931,6 +1068,44 @@ public sealed class SqlPollReader : IDisposable
|
||||
Convert.ToDateTime(cell, CultureInfo.InvariantCulture), DateTimeKind.Utc),
|
||||
};
|
||||
|
||||
/// <summary>The operator-facing name of what a plan reads — its table, or its named query.</summary>
|
||||
private static string DescribeSource(SqlQueryPlan plan)
|
||||
=> plan.Model == SqlTagModel.Query
|
||||
? string.Concat("query ", plan.Members[0].QueryName)
|
||||
: plan.Members[0].Table;
|
||||
|
||||
/// <summary>Every result column's name, in ordinal order.</summary>
|
||||
private static string[] ResultColumnNames(DbDataReader reader)
|
||||
{
|
||||
var names = new string[reader.FieldCount];
|
||||
for (var i = 0; i < names.Length; i++) names[i] = reader.GetName(i);
|
||||
return names;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Rolls a named query's transaction back when disposed — always, because a named query is a read and
|
||||
/// nothing it did may be committed. A rollback that fails (the connection already broke) is swallowed:
|
||||
/// the uncommitted work dies with the connection either way.
|
||||
/// </summary>
|
||||
private sealed class RollbackOnDispose(DbTransaction transaction) : IAsyncDisposable
|
||||
{
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
await transaction.RollbackAsync(CancellationToken.None).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (ex is DbException or InvalidOperationException)
|
||||
{
|
||||
// Nothing was committed; the transaction ends with its connection.
|
||||
}
|
||||
finally
|
||||
{
|
||||
await transaction.DisposeAsync().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Rate-limits one per-poll warning by key; true at most once per <see cref="ContractWarningInterval"/>.</summary>
|
||||
private bool ShouldWarn(string key)
|
||||
{
|
||||
|
||||
@@ -53,13 +53,15 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Sql;
|
||||
/// </param>
|
||||
/// <param name="SelectedColumns">
|
||||
/// The bare (unquoted) column names in <see cref="SqlText"/>'s SELECT list, in order and distinct — the
|
||||
/// reader's map from result-set ordinal to source column.
|
||||
/// reader's map from result-set ordinal to source column. Empty for a <see cref="SqlTagModel.Query"/> plan,
|
||||
/// whose projection is the named query's own: the reader reads every result column by its reported name.
|
||||
/// </param>
|
||||
/// <param name="RowCap">
|
||||
/// The most rows the reader will attribute before refusing the whole group — twice the distinct key count
|
||||
/// (key-value: headroom so stray duplicates are attributed per key) or 1 (a where-pair wide row: one
|
||||
/// selector, so any second row is the group's ambiguity); <see langword="null"/> when the statement
|
||||
/// already limits itself (topByTimestamp). <see cref="SqlText"/> asks for <c>RowCap + 1</c>, and the
|
||||
/// already limits itself (topByTimestamp). For a <see cref="SqlTagModel.Query"/> plan it is the query's
|
||||
/// <c>maxRows</c>, enforced client-side only. <see cref="SqlText"/> asks for <c>RowCap + 1</c>, and the
|
||||
/// reader stops there: receiving the extra row means a history/events table or a non-unique where column,
|
||||
/// and the group publishes <c>BadConfigurationError</c> instead of materialising every matching row on
|
||||
/// every poll (R06:S-1).
|
||||
|
||||
Reference in New Issue
Block a user