7f5d959fb9
Every dialect projects IS_NULLABLE and nothing read it. The browse session now reads it (tolerantly: a dialect that does not project it reads as unknown) and the picker's descriptor line says 'nullable' / 'NOT NULL', so an operator knows a cell can come back NULL (Uncertain, or Bad under nullIsBad) before committing the tag. The runtime catalog loader keeps reading names only - nothing at runtime consumes nullability. Refs #744 Claude-Session: https://claude.ai/code/session_01Ub9hGmYLQvn9XETzw7CMsT
473 lines
25 KiB
C#
473 lines
25 KiB
C#
using System.Data;
|
|
using System.Data.Common;
|
|
using ZB.MOM.WW.OtOpcUa.Commons.Browsing;
|
|
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
|
using ZB.MOM.WW.OtOpcUa.Driver.Sql.Contracts;
|
|
|
|
namespace ZB.MOM.WW.OtOpcUa.Driver.Sql.Browser;
|
|
|
|
/// <summary>
|
|
/// Live, one-level-per-call walk of a relational catalog: schemas → tables/views → columns, with the
|
|
/// column's mapped <c>DriverDataType</c> in the attribute side-panel (design §4.1, mirroring Galaxy's
|
|
/// two-stage object-then-attribute pick). Created by <c>SqlDriverBrowser</c> on picker open and owned by
|
|
/// the AdminUI's <c>BrowseSessionRegistry</c>, whose TTL reaper disposes idle sessions.
|
|
/// <para><b>Every level is the dialect's catalog SQL</b> (<see cref="ISqlDialect.ListSchemasSql"/> /
|
|
/// <see cref="ISqlDialect.ListTablesSql"/> / <see cref="ISqlDialect.ListColumnsSql"/>) — nothing here
|
|
/// knows what <c>INFORMATION_SCHEMA</c> is, because Oracle and SQLite do not have it. The catalog SQL is
|
|
/// read verbatim and its <c>schema</c> / <c>table</c> parameters are <b>bound as parameters</b> under
|
|
/// <see cref="ISqlDialect.ParameterBindName"/> — so the bind names cannot drift from the markers the
|
|
/// dialect's own SQL carries; no name from a NodeId is ever concatenated into a command text, so a
|
|
/// hostile or merely awkward catalog name is inert here.
|
|
/// <see cref="ISqlDialect.QuoteIdentifier"/> is deliberately <em>not</em> used on this path — the browse
|
|
/// never needs an identifier in text.</para>
|
|
/// <para><b>Connection ownership: this session owns the connection it is handed and closes it on
|
|
/// <see cref="DisposeAsync"/>.</b> It does not open one, and it never re-opens a closed one. The handoff
|
|
/// is the same as the Galaxy and OPC UA client sessions': the browser owns the connection only until
|
|
/// construction succeeds, after which the registry-held session is the sole thing with a lifetime hook —
|
|
/// if the session did not close it, nothing would, and every reaped picker would leak a pooled
|
|
/// connection.</para>
|
|
/// <para><b>No timeout of its own.</b> The AdminUI already bounds each root/expand/attributes call with a
|
|
/// 20-second linked CTS (<c>BrowserSessionService.PerCallTimeout</c>); this session's job is simply to
|
|
/// honour the token it is handed, into the gate wait and into every ADO.NET call. Adding a second
|
|
/// independent deadline here would only produce two competing, differently-worded failures.</para>
|
|
/// </summary>
|
|
internal sealed class SqlBrowseSession : IBrowseSession
|
|
{
|
|
/// <summary>Column alias every dialect's <see cref="ISqlDialect.ListSchemasSql"/> projects.</summary>
|
|
private const string SchemaColumn = "TABLE_SCHEMA";
|
|
|
|
/// <summary>Column alias every dialect's <see cref="ISqlDialect.ListTablesSql"/> projects.</summary>
|
|
private const string TableNameColumn = "TABLE_NAME";
|
|
|
|
/// <summary>Column alias carrying <c>BASE TABLE</c> / <c>VIEW</c>.</summary>
|
|
private const string TableTypeColumn = "TABLE_TYPE";
|
|
|
|
/// <summary>Column alias every dialect's <see cref="ISqlDialect.ListColumnsSql"/> projects.</summary>
|
|
private const string ColumnNameColumn = "COLUMN_NAME";
|
|
|
|
/// <summary>Column alias carrying the SQL type family name.</summary>
|
|
private const string DataTypeColumn = "DATA_TYPE";
|
|
|
|
/// <summary>
|
|
/// Column alias carrying <c>YES</c>/<c>NO</c> nullability. Every shipped dialect projects it (Oracle
|
|
/// normalises its <c>Y</c>/<c>N</c>); it used to be read by nothing (R06:S-5).
|
|
/// </summary>
|
|
private const string IsNullableColumn = "IS_NULLABLE";
|
|
|
|
/// <summary>The <c>TABLE_TYPE</c> value marking a view rather than a base table.</summary>
|
|
private const string ViewTableType = "VIEW";
|
|
|
|
/// <summary>Base name of the schema parameter every dialect's catalog SQL carries.</summary>
|
|
private const string SchemaParameter = "schema";
|
|
|
|
/// <summary>Base name of the table parameter <see cref="ISqlDialect.ListColumnsSql"/> carries.</summary>
|
|
private const string TableParameter = "table";
|
|
|
|
/// <summary>
|
|
/// The security class every browsed column reports. The <c>Sql</c> driver is read-only in v1
|
|
/// (design §4.3), so there is nothing else a picked column could be.
|
|
/// </summary>
|
|
private const string ReadOnlySecurityClass = "ViewOnly";
|
|
|
|
/// <summary>
|
|
/// The one SQL type family that maps to <see cref="DriverDataType.DateTime"/> while carrying <b>no
|
|
/// time of day</b> — SQL Server's and PostgreSQL's <c>date</c>. Ranked below the time-bearing
|
|
/// families by <see cref="PreferredTimestampColumn"/>; see <see cref="IsDateOnly"/> for the Oracle
|
|
/// exception.
|
|
/// </summary>
|
|
private const string DateOnlyTypeFamily = "date";
|
|
|
|
private readonly DbConnection _connection;
|
|
private readonly ISqlDialect _dialect;
|
|
|
|
/// <summary>
|
|
/// Serializes catalog calls. One ADO.NET connection carries at most one active command/reader, and
|
|
/// the AdminUI tree happily fires several expands at once when an operator clicks quickly.
|
|
/// </summary>
|
|
private readonly SemaphoreSlim _gate = new(1, 1);
|
|
|
|
private volatile bool _disposed;
|
|
|
|
/// <summary>Constructs a session over an already-open connection, which it takes ownership of.</summary>
|
|
/// <param name="connection">The open connection to browse. Closed by <see cref="DisposeAsync"/>.</param>
|
|
/// <param name="dialect">The dialect supplying the catalog SQL and the column-type map.</param>
|
|
internal SqlBrowseSession(DbConnection connection, ISqlDialect dialect)
|
|
{
|
|
_connection = connection ?? throw new ArgumentNullException(nameof(connection));
|
|
_dialect = dialect ?? throw new ArgumentNullException(nameof(dialect));
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public Guid Token { get; } = Guid.NewGuid();
|
|
|
|
/// <inheritdoc />
|
|
public DateTime LastUsedUtc { get; private set; } = DateTime.UtcNow;
|
|
|
|
/// <inheritdoc />
|
|
public async Task<IReadOnlyList<BrowseNode>> RootAsync(CancellationToken cancellationToken)
|
|
{
|
|
var schemas = await QueryAsync(
|
|
_dialect.ListSchemasSql,
|
|
static _ => { },
|
|
static reader => ReadString(reader, SchemaColumn),
|
|
cancellationToken).ConfigureAwait(false);
|
|
|
|
var nodes = new List<BrowseNode>(schemas.Count);
|
|
foreach (var schema in schemas)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(schema)) continue;
|
|
nodes.Add(new BrowseNode(
|
|
NodeId: SqlBrowseNodeId.ForSchema(schema),
|
|
DisplayName: schema,
|
|
Kind: BrowseNodeKind.Folder,
|
|
HasChildrenHint: true));
|
|
}
|
|
|
|
return nodes;
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public async Task<IReadOnlyList<BrowseNode>> ExpandAsync(string nodeId, CancellationToken cancellationToken)
|
|
{
|
|
ObjectDisposedException.ThrowIf(_disposed, this);
|
|
var reference = SqlBrowseNodeId.Parse(nodeId);
|
|
switch (reference.Kind)
|
|
{
|
|
case SqlBrowseNodeKind.Schema:
|
|
return await ExpandSchemaAsync(reference.Schema, cancellationToken).ConfigureAwait(false);
|
|
case SqlBrowseNodeKind.Table:
|
|
return await ExpandTableAsync(reference.Schema, reference.Table!, cancellationToken)
|
|
.ConfigureAwait(false);
|
|
default:
|
|
// A column is terminal. Expanding one is a UI no-op, never an error — the tree may ask before
|
|
// it has re-read the node's Kind.
|
|
LastUsedUtc = DateTime.UtcNow;
|
|
return Array.Empty<BrowseNode>();
|
|
}
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public async Task<IReadOnlyList<AttributeInfo>> AttributesAsync(
|
|
string nodeId, CancellationToken cancellationToken)
|
|
{
|
|
ObjectDisposedException.ThrowIf(_disposed, this);
|
|
var reference = SqlBrowseNodeId.Parse(nodeId);
|
|
if (reference.Kind != SqlBrowseNodeKind.Column)
|
|
{
|
|
// Schemas and tables have no side-panel — same shape as the OPC UA client browser, whose tree is
|
|
// uniform and returns empty for every node.
|
|
LastUsedUtc = DateTime.UtcNow;
|
|
return Array.Empty<AttributeInfo>();
|
|
}
|
|
|
|
var columns = await ReadColumnsAsync(
|
|
reference.Schema, reference.Table!, cancellationToken).ConfigureAwait(false);
|
|
|
|
// Computed from the columns ALREADY READ for this call — the catalog is not queried a second time.
|
|
var timestampColumn = PreferredTimestampColumn([.. columns.Select(c => (c.Name, c.DataType))]);
|
|
|
|
// Ordinal: a column NodeId is only ever minted from this same catalog output, so its case is the
|
|
// catalog's own. A case-insensitive match would pick the wrong column on a case-sensitive collation
|
|
// that legitimately carries both "Value" and "value".
|
|
foreach (var column in columns)
|
|
{
|
|
if (!string.Equals(column.Name, reference.Column, StringComparison.Ordinal)) continue;
|
|
|
|
// A column NAME alone cannot address a Sql tag — the table has to travel with it, or the
|
|
// browse-commit has nothing to build a SqlTagConfigModel from and falls through to the
|
|
// generic {"address": ...} blob the typed editor cannot read (deferment.md G-6). The
|
|
// schema is carried separately so the commit mapper can qualify the table itself rather
|
|
// than parsing a joined string back apart.
|
|
var addressFields = new Dictionary<string, string>(StringComparer.Ordinal)
|
|
{
|
|
[SqlBrowseAddressFields.Schema] = reference.Schema,
|
|
[SqlBrowseAddressFields.Table] = reference.Table!,
|
|
[SqlBrowseAddressFields.ColumnName] = column.Name,
|
|
};
|
|
|
|
// The third part of a wide-row binding: WHICH row. Stated only when the catalog actually names
|
|
// a date/time column; the key is absent otherwise, never blank, so the mapper can tell "this
|
|
// table cannot be bound by browse" from "an older session said nothing".
|
|
if (timestampColumn is not null)
|
|
addressFields[SqlBrowseAddressFields.TopByTimestamp] = timestampColumn;
|
|
|
|
return
|
|
[
|
|
new AttributeInfo(
|
|
Name: column.Name,
|
|
DriverDataType: _dialect.MapColumnType(column.DataType).ToString(),
|
|
IsArray: false,
|
|
// The picker's descriptor line ("{type} · {SecurityClass}") — display only. Nullability is
|
|
// what tells an operator a cell can come back NULL, which publishes Uncertain (or Bad under
|
|
// nullIsBad), before they commit the tag.
|
|
SecurityClass: column.IsNullable switch
|
|
{
|
|
true => ReadOnlySecurityClass + " · nullable",
|
|
false => ReadOnlySecurityClass + " · NOT NULL",
|
|
null => ReadOnlySecurityClass,
|
|
},
|
|
IsAlarm: false,
|
|
AddressFields: addressFields),
|
|
];
|
|
}
|
|
|
|
// The column is gone (dropped since the expand, or the NodeId was hand-made). An empty side-panel is
|
|
// the honest answer; the picker simply has nothing to prefill.
|
|
return Array.Empty<AttributeInfo>();
|
|
}
|
|
|
|
/// <summary>
|
|
/// Idempotently closes the owned connection. Errors are swallowed: the registry's reaper may be racing
|
|
/// a server-side disconnect, and a failed close must never surface in the AdminUI.
|
|
/// <para><b>The gate is deliberately NOT disposed</b> — the same call
|
|
/// <c>SqlPollReader</c> makes, and for a sharper reason here. This session is disposed by the
|
|
/// registry's TTL reaper, on its own thread, while a picker may have a second call parked in
|
|
/// <see cref="SemaphoreSlim.WaitAsync(CancellationToken)"/>. Disposing the semaphore does not complete
|
|
/// its pending async waiters, and the in-flight call's <c>Release()</c> would then throw
|
|
/// <see cref="ObjectDisposedException"/> from inside the semaphore — so the parked caller is never
|
|
/// released and its call never returns at all. Left undisposed, the waiter is admitted and meets the
|
|
/// guarded <c>ObjectDisposedException.ThrowIf(_disposed, this)</c> every other member raises.
|
|
/// A <see cref="SemaphoreSlim"/> that was never handed out as a <see cref="WaitHandle"/> holds no
|
|
/// unmanaged resource, so not disposing it leaks nothing.</para>
|
|
/// </summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
public async ValueTask DisposeAsync()
|
|
{
|
|
if (_disposed) return;
|
|
_disposed = true;
|
|
|
|
try { await _connection.DisposeAsync().ConfigureAwait(false); }
|
|
catch { /* best-effort: the connection may already be broken or closed. */ }
|
|
}
|
|
|
|
private async Task<IReadOnlyList<BrowseNode>> ExpandSchemaAsync(string schema, CancellationToken ct)
|
|
{
|
|
var rows = await QueryAsync(
|
|
_dialect.ListTablesSql,
|
|
command => Bind(command, _dialect.ParameterBindName(SchemaParameter), schema),
|
|
static reader => (
|
|
Name: ReadString(reader, TableNameColumn),
|
|
Type: ReadOptionalString(reader, TableTypeColumn)),
|
|
ct).ConfigureAwait(false);
|
|
|
|
var nodes = new List<BrowseNode>(rows.Count);
|
|
foreach (var (name, type) in rows)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(name)) continue;
|
|
var isView = string.Equals(type, ViewTableType, StringComparison.OrdinalIgnoreCase);
|
|
nodes.Add(new BrowseNode(
|
|
NodeId: SqlBrowseNodeId.ForTable(schema, name),
|
|
// The label is decorated, never the NodeId — a view and a table of the same name in the same
|
|
// schema cannot exist, so the suffix is presentation only.
|
|
DisplayName: isView ? $"{name} (view)" : name,
|
|
Kind: BrowseNodeKind.Folder,
|
|
HasChildrenHint: true));
|
|
}
|
|
|
|
return nodes;
|
|
}
|
|
|
|
private async Task<IReadOnlyList<BrowseNode>> ExpandTableAsync(
|
|
string schema, string table, CancellationToken ct)
|
|
{
|
|
var columns = await ReadColumnsAsync(schema, table, ct).ConfigureAwait(false);
|
|
|
|
var nodes = new List<BrowseNode>(columns.Count);
|
|
foreach (var column in columns)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(column.Name)) continue;
|
|
nodes.Add(new BrowseNode(
|
|
NodeId: SqlBrowseNodeId.ForColumn(schema, table, column.Name),
|
|
DisplayName: column.Name,
|
|
Kind: BrowseNodeKind.Leaf,
|
|
HasChildrenHint: false));
|
|
}
|
|
|
|
return nodes;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Picks the table's preferred <c>topByTimestamp</c> column — the one a browse-committed wide-row tag
|
|
/// orders by to read the newest row — or <see langword="null"/> when the table carries no
|
|
/// date/time column at all.
|
|
/// </summary>
|
|
/// <param name="columns">The table's columns, in the catalog order the dialect's column SQL returns.</param>
|
|
/// <returns>The chosen column name, or <see langword="null"/> when there is no candidate.</returns>
|
|
/// <remarks>
|
|
/// <para><b>Candidacy is decided by the column's declared TYPE, never by its name.</b> A name test
|
|
/// (<c>*_ts</c>, <c>*time*</c>, …) is a guess that reads as knowledge: it is locale-dependent, it
|
|
/// silently misses <c>Recorded</c>, and — the part that actually breaks data — it would happily order
|
|
/// a wide-row read by a <em>string</em> column called <c>timestamp</c>, binding the tag to whatever
|
|
/// row sorts last lexically. So the only input is
|
|
/// <see cref="ISqlDialect.MapColumnType"/> reporting <see cref="DriverDataType.DateTime"/>, which is
|
|
/// the same catalog metadata the browse tree already renders per column, on every dialect.</para>
|
|
/// <para><b>Ranked, because "maps to DateTime" includes DATE-ONLY types.</b>
|
|
/// <see cref="ISqlDialect.MapColumnType"/> reports <see cref="DriverDataType.DateTime"/> for SQL
|
|
/// Server's and PostgreSQL's <c>date</c> as well — and a wide-row read ordered by a date-only column
|
|
/// is <c>ORDER BY <date> DESC</c> limited to one row, which <em>ties for every row written on
|
|
/// the same day</em>: "the newest row" silently becomes storage order among the ties, and the reader
|
|
/// cannot warn about it because the server has already discarded the others. So a time-bearing
|
|
/// candidate always outranks a date-only one, wherever the two are declared.
|
|
/// <b>Falling back to a date-only column is deliberate</b> rather than dropping those types from
|
|
/// candidacy: a table whose only date/time column is a <c>date</c> stays bindable by browse (with a
|
|
/// default the operator can see and change) instead of becoming un-committable.</para>
|
|
/// <para><b>Tie-break within a rank: FIRST in catalog order.</b> Every dialect's
|
|
/// <see cref="ISqlDialect.ListColumnsSql"/> orders by ordinal position (<c>ORDINAL_POSITION</c> /
|
|
/// <c>column_id</c>), so "first" means the earliest-declared candidate and is stable across calls,
|
|
/// connections and servers — an unordered "any candidate" would let two operators browsing the same
|
|
/// table commit two differently bound tags. On the usual multi-candidate shape (a
|
|
/// <c>CreatedUtc</c>/<c>ModifiedUtc</c> pair) it picks the earlier-declared one, which is a preference
|
|
/// and not a fact about the data.</para>
|
|
/// <para><b>It is a visible, editable DEFAULT, not a hidden binding.</b> The commit writes it into the
|
|
/// tag's <c>rowSelector.topByTimestamp</c>, where the typed Sql editor shows it and the operator can
|
|
/// change it — to the other timestamp, or to a <c>whereColumn</c>/<c>whereValue</c> pair entirely.
|
|
/// Nothing about the choice is recoverable only from the browse session.</para>
|
|
/// <para>The browsed column itself is deliberately NOT excluded: picking a table's timestamp column as
|
|
/// a tag reads the newest row's timestamp, which is a legitimate (and self-consistent) tag.</para>
|
|
/// </remarks>
|
|
private string? PreferredTimestampColumn(IReadOnlyList<(string Name, string DataType)> columns)
|
|
{
|
|
// One pass, remembering the best date-only candidate seen so far: the first time-bearing column wins
|
|
// outright, and the date-only one is only used if the walk ends without finding one.
|
|
string? dateOnlyFallback = null;
|
|
|
|
foreach (var column in columns)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(column.Name)) continue;
|
|
if (_dialect.MapColumnType(column.DataType) != DriverDataType.DateTime) continue;
|
|
|
|
if (!IsDateOnly(column.DataType)) return column.Name;
|
|
dateOnlyFallback ??= column.Name;
|
|
}
|
|
|
|
return dateOnlyFallback;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Whether a column's declared type family carries a date but no time of day — the case that makes an
|
|
/// <c>ORDER BY … DESC</c> single-row read tie for a whole day's rows.
|
|
/// </summary>
|
|
/// <param name="sqlDataType">The bare SQL type family name, as the catalog reported it.</param>
|
|
/// <returns><see langword="true"/> when the family is date-only on this dialect's backend.</returns>
|
|
/// <remarks>
|
|
/// <b>Provider-qualified, because the spelling is not the meaning.</b> <c>date</c> is date-only on SQL
|
|
/// Server and PostgreSQL, but <b>Oracle's <c>DATE</c> carries a time-of-day component</b> — which is
|
|
/// why <c>OracleDialect.MapColumnType</c> calls <see cref="DriverDataType.DateTime"/> the faithful
|
|
/// mapping there rather than a widening. Demoting it on Oracle would change the pick on the backend
|
|
/// where <c>DATE</c> is the ordinary timestamp type, for no gain.
|
|
/// <para>The check is a browse-time <em>preference</em> and belongs here rather than on
|
|
/// <see cref="ISqlDialect"/>: nothing on the poll path cares, and the type map is deliberately about
|
|
/// what a value IS, not about what it is a good idea to sort by.</para>
|
|
/// </remarks>
|
|
private bool IsDateOnly(string sqlDataType)
|
|
{
|
|
if (_dialect.Provider == SqlProvider.Oracle) return false;
|
|
return string.Equals(sqlDataType.Trim(), DateOnlyTypeFamily, StringComparison.OrdinalIgnoreCase);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Reads one table's columns. A table that no longer exists (or never did) yields an empty list rather
|
|
/// than an error: the catalog answering "no rows" is indistinguishable from a genuinely column-less
|
|
/// relation, and neither is a reason to fail an operator's click.
|
|
/// </summary>
|
|
private Task<List<(string Name, string DataType, bool? IsNullable)>> ReadColumnsAsync(
|
|
string schema, string table, CancellationToken ct) =>
|
|
QueryAsync(
|
|
_dialect.ListColumnsSql,
|
|
command =>
|
|
{
|
|
Bind(command, _dialect.ParameterBindName(SchemaParameter), schema);
|
|
Bind(command, _dialect.ParameterBindName(TableParameter), table);
|
|
},
|
|
static reader => (
|
|
Name: ReadString(reader, ColumnNameColumn),
|
|
DataType: ReadOptionalString(reader, DataTypeColumn) ?? string.Empty,
|
|
IsNullable: ReadNullability(reader)),
|
|
ct);
|
|
|
|
/// <summary>
|
|
/// Reads <c>IS_NULLABLE</c> as a tri-state: <see langword="null"/> when a (custom) dialect does not
|
|
/// project it or the value is neither <c>YES</c> nor <c>NO</c> — "unknown" is said by omission, never
|
|
/// guessed.
|
|
/// </summary>
|
|
private static bool? ReadNullability(DbDataReader reader)
|
|
{
|
|
for (var i = 0; i < reader.FieldCount; i++)
|
|
{
|
|
if (!string.Equals(reader.GetName(i), IsNullableColumn, StringComparison.OrdinalIgnoreCase)) continue;
|
|
if (reader.IsDBNull(i)) return null;
|
|
var text = reader.GetValue(i)?.ToString()?.Trim();
|
|
if (string.Equals(text, "YES", StringComparison.OrdinalIgnoreCase)) return true;
|
|
if (string.Equals(text, "NO", StringComparison.OrdinalIgnoreCase)) return false;
|
|
return null;
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Runs one catalog query under the gate and projects every row. The disposed check happens
|
|
/// <em>inside</em> the gate wait so a dispose racing an in-flight call cannot be missed.
|
|
/// <para><see cref="LastUsedUtc"/> is stamped <b>on entry as well as on completion</b>. The AdminUI
|
|
/// allows a catalog call 20 s (<c>BrowserSessionService.PerCallTimeout</c>) and a queued one waits
|
|
/// behind it; stamping only on completion leaves a long expand invisible to the registry's TTL reaper
|
|
/// for its whole duration, so a session that idled to the edge of the TTL and was then given one slow
|
|
/// call gets reaped mid-call — tearing the connection down under an open reader.</para>
|
|
/// </summary>
|
|
private async Task<List<T>> QueryAsync<T>(
|
|
string sql,
|
|
Action<DbCommand> bind,
|
|
Func<DbDataReader, T> project,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
LastUsedUtc = DateTime.UtcNow;
|
|
ObjectDisposedException.ThrowIf(_disposed, this);
|
|
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
|
|
try
|
|
{
|
|
ObjectDisposedException.ThrowIf(_disposed, this);
|
|
|
|
var results = new List<T>();
|
|
await using var command = _connection.CreateCommand();
|
|
// Before the binds: on ODP.NET this is what switches bind-by-position off, and the two-parameter
|
|
// column query is exactly where positional binding swaps the schema and the table silently.
|
|
_dialect.ConfigureCommand(command);
|
|
command.CommandText = sql;
|
|
bind(command);
|
|
|
|
await using var reader = await command
|
|
.ExecuteReaderAsync(CommandBehavior.SingleResult, cancellationToken).ConfigureAwait(false);
|
|
while (await reader.ReadAsync(cancellationToken).ConfigureAwait(false))
|
|
results.Add(project(reader));
|
|
|
|
LastUsedUtc = DateTime.UtcNow;
|
|
return results;
|
|
}
|
|
finally
|
|
{
|
|
// Unconditional, and it cannot throw: DisposeAsync deliberately leaves the gate alive precisely
|
|
// so this release still reaches whoever is parked behind us.
|
|
_gate.Release();
|
|
}
|
|
}
|
|
|
|
/// <summary>Binds one catalog-query parameter. The only way a name reaches the database.</summary>
|
|
private static void Bind(DbCommand command, string name, string value)
|
|
{
|
|
var parameter = command.CreateParameter();
|
|
parameter.ParameterName = name;
|
|
parameter.DbType = DbType.String;
|
|
parameter.Value = value;
|
|
command.Parameters.Add(parameter);
|
|
}
|
|
|
|
private static string ReadString(DbDataReader reader, string columnName) =>
|
|
ReadOptionalString(reader, columnName) ?? string.Empty;
|
|
|
|
private static string? ReadOptionalString(DbDataReader reader, string columnName)
|
|
{
|
|
var ordinal = reader.GetOrdinal(columnName);
|
|
return reader.IsDBNull(ordinal) ? null : reader.GetValue(ordinal)?.ToString();
|
|
}
|
|
}
|