From 987e9c6b6406f479f09a313d1d2e1841249dc58e Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Thu, 3 Dec 2026 15:07:50 -0800 Subject: [PATCH 1/5] Share the parameter names of a schema-qualified procedure by server and database A stored procedure's parameter names were kept with the object the command's connections came from, so a connection, a factory or a lambda made for each call (or each request) asked the database for the same names on every call. A schema-qualified name (dbo.get_author) is the same procedure for every login of a database, so its answer does not depend on who asked. Those answers are now kept once per server and database and found by every command and query of the library's own types. What is shared: the names of a procedure whose name has a schema, when the answer holds names, the connection is a DbConnection that reports both a DataSource and a Database, and the command is one of the library's own exact types (a query only needs the server and the database). Lookup goes to the shared entries first, then to the source's entries as before, then to the database. Everything else stays with its source exactly as before: names without a schema (each login resolves them in its own default schema), answers of no names, connections that report no server or database or are not a DbConnection, text commands, and command classes of the user's own. The shared entries hold at most 1024 procedures and are never cleared, evicted or expired; past the limit new sets go to their source. A failure that forgets a set removes the shared one for every connection, and the next call reads it again. No public API changes. Cost on the hit path: a command of the library's own type does one more virtual type check and two string length checks on the key, then one lookup in the shared entries (a hit for a qualified name, replacing the per-source lookup; a miss for an unqualified name, which then does the per-source lookup as before). No allocation is added; the schema-qualified test parses the name only after a database round trip. A connection created for each call now skips the schema round trip and the per-connection entry. No timed measurement was made for this change. Tests: four existing tests of distinct sources now use a procedure name without a schema, because a name with one is shared whatever its source is; fail-first tests for two fresh connections, unqualified names, empty answers, missing server or database, a user's own command type in both orders, other servers and databases, the 1024 limit, forgetting for everyone, and queries with a connection or a transaction per call; allocation tests for the shared lookup; and SQL Server tests for two logins with different default schemas and for a login that may only execute the procedure. The docs section "Parameter names are read once" and the release notes say who shares what and the caveats of sharing across logins, servers that report one name, and fake connections in tests. Co-Authored-By: Claude Sonnet 5.5 --- Source/Core/DbQuery.cs | 4 +- Source/Core/DbQueryRunner.cs | 13 +- Source/Core/ExpressiveCommandBase.cs | 42 +- Source/Core/ProcedureParameterNames.cs | 57 ++- .../DerivedNameCostTests.cs | 63 +++ .../NameCacheSharedTierLocalDbTests.cs | 144 +++++++ .../NameCacheSharedTierTests.cs | 367 ++++++++++++++++++ .../NameCacheSourceTests.cs | 14 +- .../TestHelpers/NameServer.cs | 90 +++++ docsite/articles/expressive-commands.md | 21 +- docsite/articles/release-notes.md | 1 + 11 files changed, 789 insertions(+), 27 deletions(-) create mode 100644 Tests/Open.Database.Extensions.Core.Tests/NameCacheSharedTierLocalDbTests.cs create mode 100644 Tests/Open.Database.Extensions.Core.Tests/NameCacheSharedTierTests.cs create mode 100644 Tests/Open.Database.Extensions.Core.Tests/TestHelpers/NameServer.cs diff --git a/Source/Core/DbQuery.cs b/Source/Core/DbQuery.cs index 403edb8f..4c6dae09 100644 --- a/Source/Core/DbQuery.cs +++ b/Source/Core/DbQuery.cs @@ -71,8 +71,8 @@ internal DbQuery WithOutput(OutputLayout layout) /// is made; for a procedure. /// // A definition is a static field, so a call that derives names scans - // nothing. A procedure's names are remembered per source - // (ProcedureParameterNames). A set with no names means "not known": each + // nothing. A procedure's names are remembered per server and + // database when its name has a schema, else per source (ProcedureParameterNames). A set with no names means "not known": each // argument is sent as written. internal NameSet? TextNames { get; } diff --git a/Source/Core/DbQueryRunner.cs b/Source/Core/DbQueryRunner.cs index 422dd7ce..472a98fd 100644 --- a/Source/Core/DbQueryRunner.cs +++ b/Source/Core/DbQueryRunner.cs @@ -301,8 +301,9 @@ static ProcedureKey KeyOf(DbConnection connection, DbQuery definition) /// /// /// A text definition has the @name markers it found when it was made; - /// a procedure's names are read once per source and kept until a call that used - /// them cannot be built or the database rejects it. + /// a procedure's names are read once and kept until a call that used them + /// cannot be built or the database rejects it: once per server and database + /// for a schema-qualified name, else once per source. /// /// The query definition. /// The connection, transaction, pool or factory. @@ -319,8 +320,8 @@ static ProcedureKey KeyOf(DbConnection connection, DbQuery definition) object owner = NameCacheOwner(source, connection); ProcedureKey key = KeyOf(connection, definition); - return ProcedureParameterNames.Find(owner, key) - ?? ProcedureParameterNames.Remember(owner, key, ProcedureSchemaNames.Get(connection, definition.CommandText)); + return ProcedureParameterNames.FindShared(owner, key) + ?? ProcedureParameterNames.RememberShared(owner, key, ProcedureSchemaNames.Get(connection, definition.CommandText)); } /// @@ -346,7 +347,7 @@ static ProcedureKey KeyOf(DbConnection connection, DbQuery definition) object owner = NameCacheOwner(source, connection); ProcedureKey key = KeyOf(connection, definition); - return ProcedureParameterNames.Find(owner, key) is { } kept + return ProcedureParameterNames.FindShared(owner, key) is { } kept ? new(kept) : ReadNamesAsync(owner, key, connection, definition, cancellationToken); } @@ -357,7 +358,7 @@ static ProcedureKey KeyOf(DbConnection connection, DbQuery definition) DbConnection connection, DbQuery definition, CancellationToken cancellationToken) - => ProcedureParameterNames.Remember( + => ProcedureParameterNames.RememberShared( owner, key, await ProcedureSchemaNames diff --git a/Source/Core/ExpressiveCommandBase.cs b/Source/Core/ExpressiveCommandBase.cs index af34893c..9665e40a 100644 --- a/Source/Core/ExpressiveCommandBase.cs +++ b/Source/Core/ExpressiveCommandBase.cs @@ -523,8 +523,9 @@ public TThis AddParam(string name, string? value) /// when the names are known, what the procedure declares. /// /// - /// A stored procedure's names are read once per connection factory, pool or connection, and again after a call that cannot be built (other than by - /// cancellation) or that the database rejects. + /// A stored procedure's names are read once per server and database when its name has a schema (dbo.get_author) and this is one of the library's + /// own command types, else once per connection factory, pool or connection; and again after a call that cannot be built (other than by cancellation) or + /// that the database rejects. /// /// /// Where the real names are not available (a text command with no @@ -853,8 +854,8 @@ protected virtual ValueTask> GetProcedureParameterNamesAs if (Type == CommandType.StoredProcedure) { ProcedureKey key = KeyOf(connection); - return ProcedureParameterNames.Find(_poolOrConnection, key) - ?? ProcedureParameterNames.Remember(_poolOrConnection, key, GetProcedureParameterNames(connection, Command)); + return FindNames(key) + ?? RememberNames(key, GetProcedureParameterNames(connection, Command)); } // The @name markers found in the text. @@ -880,7 +881,7 @@ protected virtual ValueTask> GetProcedureParameterNamesAs if (Type == CommandType.StoredProcedure) { ProcedureKey key = KeyOf(connection); - return ProcedureParameterNames.Find(_poolOrConnection, key) is { } kept + return FindNames(key) is { } kept ? new(kept) : ReadNamesAsync(connection, key, cancellationToken); } @@ -896,8 +897,7 @@ protected virtual ValueTask> GetProcedureParameterNamesAs TConnection connection, ProcedureKey key, CancellationToken cancellationToken) - => ProcedureParameterNames.Remember( - _poolOrConnection, + => RememberNames( key, await GetProcedureParameterNamesAsync( connection, @@ -922,7 +922,7 @@ await GetProcedureParameterNamesAsync( if (Type == CommandType.StoredProcedure) { ProcedureKey key = KeyOf(connection); - return ProcedureParameterNames.Find(_poolOrConnection, key) is { } kept + return FindNames(key) is { } kept ? kept.NeedsMetadata ? NamesWithMetadataAsync(connection, kept, cancellationToken) : new(kept) @@ -1059,6 +1059,32 @@ ProcedureKey KeyOf(TConnection connection) (connection as DbConnection)?.DataSource, connection.Database, Command); + /// + /// Finds the names kept for a procedure: for a command of the library's own + /// type, the ones shared by server and database first, then the source's; + /// for any other command, the source's. + /// + /// The key made by . + /// The set, or when none is kept. + // A command type of the user's own may answer names that are its own (it + // overrides how they are read), so its answers are never given to another + // command, nor another's to it. Per call: one virtual type test. + NameSet? FindNames(ProcedureKey key) + => IsLibraryCommand + ? ProcedureParameterNames.FindShared(_poolOrConnection, key) + : ProcedureParameterNames.Find(_poolOrConnection, key); + + /// + /// Keeps the names a lookup answered, shared as finds them. + /// + /// The key made by . + /// The names as the provider reported them; empty or the default array when it reported none. + /// The set kept for the procedure. + NameSet RememberNames(ProcedureKey key, ImmutableArray names) + => IsLibraryCommand + ? ProcedureParameterNames.RememberShared(_poolOrConnection, key, names) + : ProcedureParameterNames.Remember(_poolOrConnection, key, names); + /// /// Builds, in , what one run of a command with written names sends: each name that the text declares /// with a different spelling (without its @, say) under the text's own spelling, the rest as written. diff --git a/Source/Core/ProcedureParameterNames.cs b/Source/Core/ProcedureParameterNames.cs index 37cf2a99..129a55bf 100644 --- a/Source/Core/ProcedureParameterNames.cs +++ b/Source/Core/ProcedureParameterNames.cs @@ -57,6 +57,14 @@ public override int GetHashCode() /// An entry is a : the names the database reported (none, when it reports none) and the real name each argument has matched. /// /// +/// One kind of entry is kept apart from its source, in : the names of a schema-qualified procedure, as answered for a server and +/// a database, found by every command and query of the library's own types that runs on a that names both. A schema-qualified +/// name is the same procedure for every login of the database, so the answer does not depend on who asked. An unqualified name (the login's default +/// schema picks the procedure), an answer of no names, a connection that names no server or database, and a command type of the user's own stay with +/// their source. The shared entries are never cleared or evicted and nothing expires them: at of them, new sets go to +/// their source, as before. A failure that forgets an entry removes the shared one for everyone, and the next call reads it again. +/// +/// /// Which failures forget an entry, the one rule for every path: a call that fails while it is being built forgets, unless it was canceled; /// once it is built, only a does. Reading rows and converting values raise other exceptions and do not. /// A raised while the rows are read, or by the caller's own code inside the call, also forgets: it is not told apart, @@ -66,7 +74,8 @@ public override int GetHashCode() static class ProcedureParameterNames { /// - /// How many procedures one source keeps; past it they are all dropped and read again as they are called. + /// How many procedures one source keeps; past it they are all dropped and read again as they are called. The shared entries hold at most as + /// many, and past it new sets go to their source. /// // A memory cap, for procedure names built at run time and for many databases behind one factory. A procedure with five parameters takes about // 1.2 KB with its matches (measured on .NET 11, x64), so a full source holds about 1.2 MB. @@ -87,6 +96,29 @@ public sealed class Entries /// The entries of each source, held weakly. static readonly ConditionalWeakTable Sources = new(); + /// The entries shared by every source: schema-qualified procedures of a server and a database. + // Held for the life of the process, so the weak reference every entry holds back to it never goes: Forget works as for a source's entries. + public static readonly Entries Shared = new(); + + /// + /// Gets the kept names of a procedure for a command of the library's own type, or for a query: the shared entry first, then the source's. + /// + /// The object commands take their connections from. + /// The server, database and procedure. + /// The set, or when none is kept. + // Per call, beyond Find: two length checks on the key, and one lookup in the shared entries (which a key of an unqualified name misses). + public static NameSet? FindShared(object source, ProcedureKey key) + => CanShare(key) && Shared.ByProcedure.TryGetValue(key, out NameSet? shared) + ? shared + : Find(source, key); + + /// Gets whether a key names a server and a database: only then is its answer shared. + /// The server, database and procedure. + /// if the key names both; otherwise, . + // A connection that is not a DbConnection has no server name, and one that does not know its database reports none: neither is told apart from another. + static bool CanShare(ProcedureKey key) + => key.Server.Length != 0 && key.Database.Length != 0; + /// Gets the kept names of a procedure. /// The object commands take their connections from. /// The server, database and procedure. @@ -121,6 +153,29 @@ public static NameSet Remember(object source, ProcedureKey key, ImmutableArray + /// Keeps what the lookup answered, for a command of the library's own type or for a query: shared when it can be, else with its source. + /// + /// The object commands take their connections from. + /// The server, database and procedure the names belong to. + /// The names as the database reported them; empty or the default array when it reported none. + /// The set kept for the procedure: this one, or the one another call kept first. + // Shared only when the answer holds names, the key names a server and a database, the procedure name has a schema, and the shared entries have room. + // The name is parsed here, after the round trip, and never on a lookup. + public static NameSet RememberShared(object source, ProcedureKey key, ImmutableArray names) + { + if (names.IsDefaultOrEmpty + || !CanShare(key) + || ProcedureSchemaNames.Restrictions(key.Procedure) is not { } restrictions + || restrictions[1] is null + || Shared.ByProcedure.Count >= MaxProcedures) + { + return Remember(source, key, names); + } + + return Shared.ByProcedure.GetOrAdd(key, new NameSet(names, Shared.Weak, key)); + } + /// /// Forgets the set a failed call used, so the next call reads the names again. /// diff --git a/Tests/Open.Database.Extensions.Core.Tests/DerivedNameCostTests.cs b/Tests/Open.Database.Extensions.Core.Tests/DerivedNameCostTests.cs index d6d595bd..16655628 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/DerivedNameCostTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/DerivedNameCostTests.cs @@ -765,4 +765,67 @@ public static void ConcurrentExecutions_ShareOneNameSet_AndAllResolveTheSame() Assert.Equal(1000, results.Count); Assert.All(results, r => Assert.Equal("@order_id,@customer_id,@start_date", r)); } + + // ---- a shared set ---- + + // A schema-qualified procedure of the librarys own command type is found in the tier shared by every connection to its server and database: a repeat + // run costs what the hand-written names cost, as it does with the names kept by one connection. + [Fact] + public static void StoredProcedure_ASharedSet_DerivedCostsNoMoreThanExplicit() + { + var server = new NameServer(NameServer.Unique()) { Names = ["@order_id", "@customer_id", "@start_date"] }; + NameServer.NameConnection connection = server.Connect(); + string procedure = ParameterNameHarness.NewProcedure(); + const int orderId = 5, customerId = 7; + var startDate = new DateTime(2026, 1, 2); + + void Derived() + => new ExpressiveDbCommand(connection, CommandType.StoredProcedure, procedure) + .AddParam(orderId) + .AddParam(customerId) + .AddParam(startDate) + .ExecuteNonQuery(); + void Explicit() + => new ExpressiveDbCommand(connection, CommandType.StoredProcedure, procedure) + .AddParam("@order_id", orderId) + .AddParam("@customer_id", customerId) + .AddParam("@start_date", startDate) + .ExecuteNonQuery(); + + long derived = BytesPerCall(Derived); + long explicitName = BytesPerCall(Explicit); + + Assert.Equal(1, server.Reads); + AssertWithinBudget("stored procedure, shared set, three plain locals", derived, explicitName); + } + + // The lookup itself, apart from building a command: a shared set is found, and so is a set a source keeps for an unqualified name (a miss in the + // shared entries first), without allocating. + [Fact] + public static void FindingAKeptSet_SharedOrOfItsSource_AllocatesNothing() + { + object source = new(); + string server = NameServer.Unique(); + var qualified = new ProcedureKey(server, "db", "dbo.find"); + var unqualified = new ProcedureKey(server, "db", "find"); + NameSet shared = ProcedureParameterNames.RememberShared(source, qualified, ["@a"]); + NameSet owned = ProcedureParameterNames.RememberShared(source, unqualified, ["@a"]); + NameSet? found = null; + + try + { + Assert.Same(shared, ProcedureParameterNames.FindShared(new object(), qualified)); + Assert.Null(ProcedureParameterNames.FindShared(new object(), unqualified)); + Assert.Same(owned, ProcedureParameterNames.FindShared(source, unqualified)); + + Assert.Equal(0, BytesPerCall(() => found = ProcedureParameterNames.FindShared(source, qualified))); + Assert.Equal(0, BytesPerCall(() => found = ProcedureParameterNames.FindShared(source, unqualified))); + GC.KeepAlive(found); + } + finally + { + ProcedureParameterNames.Forget(shared); + ProcedureParameterNames.Forget(owned); + } + } } diff --git a/Tests/Open.Database.Extensions.Core.Tests/NameCacheSharedTierLocalDbTests.cs b/Tests/Open.Database.Extensions.Core.Tests/NameCacheSharedTierLocalDbTests.cs new file mode 100644 index 00000000..4eae1c28 --- /dev/null +++ b/Tests/Open.Database.Extensions.Core.Tests/NameCacheSharedTierLocalDbTests.cs @@ -0,0 +1,144 @@ +extern alias mssql; + +using Microsoft.Data.SqlClient; + +#nullable enable + +namespace Open.Database.Extensions.Tests; + +// The shared tier against SQL Server: what a schema-qualified name means for logins with different default schemas, and what a login that may only +// execute a procedure can see of it. A login is a database user without a login, entered with EXECUTE AS USER on a connection of its own: a name is +// resolved by the user's default schema and the metadata a user sees by the user's permissions, whichever way the user got in. Skipped without LocalDB +// (see LocalDbFixture). +[ExcludeFromCodeCoverage] +[Collection("LocalDB DDL")] +public static class NameCacheSharedTierLocalDbTests +{ + static CancellationToken Token => TestContext.Current.CancellationToken; + + // Schemas, users and procedures made for one test and dropped when it ends. + sealed class Scene : IDisposable + { + readonly List _drops = []; + + public Scene() + { + string id = Guid.NewGuid().ToString("N")[..12]; + Procedure = "p_" + id; + First = "d1_" + id; + Second = "d2_" + id; + Shared = "s_" + id; + ExecuteOnly = "ode_u3_" + id; + foreach (string schema in new[] { First, Second, Shared }) + { + Run($"create schema [{schema}]"); + _drops.Add($"drop schema if exists [{schema}]"); + } + } + + /// Gets the name of the procedure in each schema. + public string Procedure { get; } + + /// Gets the default schema of the first user. + public string First { get; } + + /// Gets the default schema of the second user. + public string Second { get; } + + /// Gets the schema both users name when they give one. + public string Shared { get; } + + /// Gets the user that may only execute one procedure. + public string ExecuteOnly { get; } + + public static void Run(string sql) => LocalDbFixture.Execute(sql); + + public string AddUser(string name, string defaultSchema) + { + Run($"create user [{name}] without login with default_schema = [{defaultSchema}]"); + _drops.Insert(0, $"drop user if exists [{name}]"); + return name; + } + + public void AddProcedure(string schema, string parameter, string answer) + { + Run($"create procedure [{schema}].[{Procedure}] {parameter} as select '{answer}' as which"); + _drops.Insert(0, $"drop procedure if exists [{schema}].[{Procedure}]"); + } + + public void Dispose() + { + foreach (string drop in _drops) Run(drop); + } + } + + // A connection of its own (not pooled, so nothing of the impersonation outlives it) that acts as a database user. + static async Task OpenAs(string user) + { + var builder = new SqlConnectionStringBuilder(LocalDbFixture.ConnectionString) { Pooling = false }; + var connection = new SqlConnection(builder.ConnectionString); + await connection.OpenAsync(Token); + await using SqlCommand command = connection.CreateCommand(); + command.CommandText = $"execute as user = '{user}'"; + await command.ExecuteNonQueryAsync(Token); + return connection; + } + + static string? Which(SqlConnection connection, string procedure, string member) + => connection.StoredProcedure(procedure) + .AddParam(value: 1, expression: member) + .ExecuteScalar(); + + static bool IsShared(string procedure) + => ProcedureParameterNames.Shared.ByProcedure.Keys.Any(key => key.Procedure == procedure); + + // Two logins whose default schemas differ, each with a procedure of the same name in its own schema, and a third schema with another: a name with a + // schema is the one procedure for both, with the same names, and is shared; the name without one is each login's own procedure, and is not. + [Fact] + public static async Task TwoLoginsWithDifferentDefaultSchemas_ShareASchemaQualifiedProcedure_AndEachGetsItsOwnUnqualifiedOne() + { + LocalDbFixture.SkipUnlessAvailable(); + using var scene = new Scene(); + string one = scene.AddUser("ode_u1_" + scene.Procedure, scene.First); + string two = scene.AddUser("ode_u2_" + scene.Procedure, scene.Second); + scene.AddProcedure(scene.First, "@alpha int", "first"); + scene.AddProcedure(scene.Second, "@beta int", "second"); + scene.AddProcedure(scene.Shared, "@region int", "shared"); + Scene.Run($"grant execute on schema::[{scene.First}] to [{one}]"); + Scene.Run($"grant execute on schema::[{scene.Second}] to [{two}]"); + Scene.Run($"grant execute on schema::[{scene.Shared}] to [{one}]"); + Scene.Run($"grant execute on schema::[{scene.Shared}] to [{two}]"); + string qualified = $"{scene.Shared}.{scene.Procedure}"; + + await using SqlConnection first = await OpenAs(one); + await using SqlConnection second = await OpenAs(two); + + Assert.Equal("shared", Which(first, qualified, "filter.Region")); + Assert.True(IsShared(qualified)); + Assert.Equal("shared", Which(second, qualified, "filter.Region")); + + // Each login's own procedure of that name, by the names it declares: another login's names would not fit. + Assert.Equal("first", Which(first, scene.Procedure, "filter.Alpha")); + Assert.Equal("second", Which(second, scene.Procedure, "filter.Beta")); + Assert.False(IsShared(scene.Procedure)); + } + + // A login that may only execute one procedure: the schema lookup answers with its parameters (observed on SQL Server), so such a login reads the names + // as any other and is not given an empty answer. Pinned because the docs say what a shared set shows to a login with no right on the procedure. + [Fact] + public static async Task ALoginThatMayOnlyExecuteAProcedure_SeesItsParametersInTheSchemaLookup() + { + LocalDbFixture.SkipUnlessAvailable(); + using var scene = new Scene(); + string user = scene.AddUser(scene.ExecuteOnly, "dbo"); + scene.AddProcedure(scene.Shared, "@region int, @other int = 0", "shared"); + Scene.Run($"grant execute on object::[{scene.Shared}].[{scene.Procedure}] to [{user}]"); + + await using SqlConnection connection = await OpenAs(user); + using DataTable table = connection.GetSchema("ProcedureParameters", [null, scene.Shared, scene.Procedure, null]); + + // SQL Server reports both parameters to a user whose only right on the procedure is EXECUTE. + Assert.Equal(2, table.Rows.Count); + Assert.Equal(["@region", "@other"], table.Rows.Cast().OrderBy(row => Convert.ToInt32(row["ORDINAL_POSITION"], System.Globalization.CultureInfo.InvariantCulture)).Select(row => (string)row["PARAMETER_NAME"])); + } +} diff --git a/Tests/Open.Database.Extensions.Core.Tests/NameCacheSharedTierTests.cs b/Tests/Open.Database.Extensions.Core.Tests/NameCacheSharedTierTests.cs new file mode 100644 index 00000000..a11b8a8a --- /dev/null +++ b/Tests/Open.Database.Extensions.Core.Tests/NameCacheSharedTierTests.cs @@ -0,0 +1,367 @@ +using System.Data.Common; + +namespace Open.Database.Extensions.Tests; + +#nullable enable + +// A schema-qualified procedure's parameter names are read once per server and database and shared by every command and query of the library's own +// types, whatever connection or factory they run on. Everything else (an unqualified name, an empty answer, a connection that names no server or +// database, a command type of the user's own) stays with the source of its connections, as it always was. Reads are counted at the provider: each +// one is a GetSchema call on a connection. The tests run alone (see the collection) because they fill the process-wide tier, and each test uses a +// server name of its own. +[CollectionDefinition("Shared name tier", DisableParallelization = true)] +public sealed class SharedNameTierCollection; + +[Collection("Shared name tier")] +[ExcludeFromCodeCoverage] +public static class NameCacheSharedTierTests +{ + static CancellationToken Token => TestContext.Current.CancellationToken; + + const int OrderId = 1; // a name to derive the parameter name from + + sealed class FakeServerError(string message = "rejected by the server") : DbException(message); + + // What a user's own command type answers for the parameter names of any procedure. + sealed class CustomNamesCommand(DbConnection connection, string procedure) + : ExpressiveDbCommand(connection, CommandType.StoredProcedure, procedure) + { + protected override ImmutableArray GetProcedureParameterNames(DbConnection connection, string procedure) + => ["@REGION"]; + + protected override ValueTask> GetProcedureParameterNamesAsync(DbConnection connection, string procedure, CancellationToken cancellationToken) + => new(["@REGION"]); + } + + static void Run(NameServer.NameConnection connection, string procedure) + => new ExpressiveDbCommand(connection, CommandType.StoredProcedure, procedure) + .AddParam(value: 1, expression: "filter.Region") + .ExecuteNonQuery(); + + static async Task RunAsync(NameServer.NameConnection connection, string procedure) + => await new ExpressiveDbCommand(connection, CommandType.StoredProcedure, procedure) + .AddParam(value: 1, expression: "filter.Region") + .ExecuteNonQueryAsync(Token); + + static async Task Run(NameServer.NameConnection connection, string procedure, bool async) + { + if (async) + { + await RunAsync(connection, procedure); + } + else + { + Run(connection, procedure); + } + } + + static string Unique() => ParameterNameHarness.NewProcedure(); + + // A procedure name without a schema. + static string Unqualified() => Unique()[("dbo.".Length)..]; + + // ---- who shares ---- + + [Theory] + [InlineData(false)] + [InlineData(true)] + public static async Task ASchemaQualifiedName_IsReadOnce_ForTwoFreshConnections(bool async) + { + var server = NameServer.Create(); + string procedure = Unique(); + + await Run(server.Connect(), procedure, async); + await Run(server.Connect(), procedure, async); + + Assert.Equal(1, server.Reads); + } + + [Fact] + public static void AnUnqualifiedName_IsReadOnceForEachConnection() + { + var server = NameServer.Create(); + string procedure = Unique()[(Unique().IndexOf('.') + 1)..]; // names1, no schema + + Run(server.Connect(), procedure); + Run(server.Connect(), procedure); + NameServer.NameConnection same = server.Connect(); + Run(same, procedure); + Run(same, procedure); + + Assert.Equal(3, server.Reads); + } + + [Fact] + public static void ASharedSet_ResolvesTheArgumentsOfEveryCommand() + { + var server = NameServer.Create(); + string procedure = Unique(); + NameServer.NameConnection first = server.Connect(), second = server.Connect(); + + Run(first, procedure); + Run(second, procedure); + + Assert.Equal(["@region"], first.Sent); + Assert.Equal(["@region"], second.Sent); + } + + [Fact] + public static void AnEmptyAnswer_IsNotSharedButKeptByItsConnection() + { + var server = NameServer.Create(); + server.Names = []; + string procedure = Unique(); + + NameServer.NameConnection same = server.Connect(); + Run(same, procedure); + Run(same, procedure); + Assert.Equal(1, server.Reads); + + Run(server.Connect(), procedure); + Assert.Equal(2, server.Reads); + } + + [Theory] + [InlineData("", "db")] + [InlineData(null, "db")] + [InlineData("x", "")] + [InlineData("x", null)] + [InlineData("", "")] + public static void AConnectionThatNamesNoServerOrDatabase_IsReadForEachConnection(string? dataSource, string? database) + { + var server = new NameServer(dataSource is "x" ? NameServer.Unique() : dataSource, database); + string procedure = Unique(); + + Run(server.Connect(), procedure); + Run(server.Connect(), procedure); + + Assert.Equal(2, server.Reads); + } + + [Fact] + public static void ACommandOnAConnectionThatIsNotADbConnection_ShareNothing() + { + string procedure = Unique(); + + for (int i = 0; i < 2; i++) + { + var probe = new ConnectionProbe(ConnectionState.Open); + new ExpressiveCommand(probe.Connection, CommandType.StoredProcedure, procedure) + .AddParam(value: 1, expression: "filter.Region") + .ExecuteNonQuery(); + } + + AssertNothingSharedFor(procedure); + } + + [Fact] + public static void ACommandTypeOfTheUsersOwn_NeverGivesItsNamesToTheLibrarysCommands_AndNeverTakesTheirs() + { + var server = NameServer.Create(); + string procedure = Unique(); + + NameServer.NameConnection mine = server.Connect(); + new CustomNamesCommand(mine, procedure).AddParam(value: 1, expression: "filter.Region").ExecuteNonQuery(); + Assert.Equal(["@REGION"], mine.Sent); + Assert.Equal(0, server.Reads); + + NameServer.NameConnection plain = server.Connect(); + Run(plain, procedure); + Assert.Equal(["@region"], plain.Sent); + Assert.Equal(1, server.Reads); + + NameServer.NameConnection again = server.Connect(); + new CustomNamesCommand(again, procedure).AddParam(value: 1, expression: "filter.Region").ExecuteNonQuery(); + Assert.Equal(["@REGION"], again.Sent); + Assert.Equal(1, server.Reads); + + // The library's own set was shared by the plain run; the user's was not. + NameServer.NameConnection third = server.Connect(); + Run(third, procedure); + Assert.Equal(["@region"], third.Sent); + Assert.Equal(1, server.Reads); + } + + [Fact] + public static void ACommandTypeOfTheUsersOwn_WhoseNamesWereTakenFirst_DoesNotPoisonTheLibrarysCommands() + { + var server = NameServer.Create(); + string procedure = Unique(); + NameServer.NameConnection first = server.Connect(); + + Run(first, procedure); // shared now + + NameServer.NameConnection mine = server.Connect(); + new CustomNamesCommand(mine, procedure).AddParam(value: 1, expression: "filter.Region").ExecuteNonQuery(); + + Assert.Equal(["@region"], first.Sent); + Assert.Equal(["@REGION"], mine.Sent); + Assert.Equal(1, server.Reads); + } + + [Fact] + public static void AnotherServerOrDatabase_HasItsOwnEntry() + { + string name = NameServer.Unique(); + var first = new NameServer(name, "dbA") { Names = ["@region"] }; + var secondDatabase = new NameServer(name, "dbB") { Names = ["@REGION"] }; + var secondServer = new NameServer(name + "x", "dbA") { Names = ["@Region"] }; + string procedure = Unique(); + + NameServer.NameConnection a = first.Connect(), b = secondDatabase.Connect(), c = secondServer.Connect(); + Run(a, procedure); + Run(b, procedure); + Run(c, procedure); + Assert.Equal(["@region"], a.Sent); + Assert.Equal(["@REGION"], b.Sent); + Assert.Equal(["@Region"], c.Sent); + + // Each is shared on its own: another connection to it reads nothing, and the same server in another case is the same server. + Run(first.Connect(), procedure); + Run(secondDatabase.Connect(), procedure); + Run(secondServer.Connect(), procedure); + Assert.Equal(1, first.Reads); + Assert.Equal(1, secondDatabase.Reads); + Assert.Equal(1, secondServer.Reads); + + var upper = new NameServer(name.ToUpperInvariant(), "DBA") { Names = ["@never"] }; + Run(upper.Connect(), procedure); + Assert.Equal(0, upper.Reads); + } + + // ---- the bound ---- + + [Fact] + public static void PastTheBound_NewSetsGoToTheirConnection_AndNothingIsCleared() + { + ClearShared(); + try + { + var server = NameServer.Create(); + const int Bound = 1024; + + for (int i = 0; i < Bound; i++) Run(server.Connect(), "dbo.cap" + i); + Assert.Equal(Bound, server.Reads); + + // The first 1024 are shared: no connection reads them again. + for (int i = 0; i < Bound; i++) Run(server.Connect(), "dbo.cap" + i); + Assert.Equal(Bound, server.Reads); + + // The 1025th is kept by the connection that read it, not shared. + NameServer.NameConnection owner = server.Connect(); + Run(owner, "dbo.cap" + Bound); + Assert.Equal(Bound + 1, server.Reads); + Run(owner, "dbo.cap" + Bound); + Assert.Equal(Bound + 1, server.Reads); + Run(server.Connect(), "dbo.cap" + Bound); + Assert.Equal(Bound + 2, server.Reads); + + // Nothing was cleared to make room. + for (int i = 0; i < Bound; i++) Run(server.Connect(), "dbo.cap" + i); + Assert.Equal(Bound + 2, server.Reads); + } + finally + { + ClearShared(); + } + } + + // ---- forgetting ---- + + [Theory] + [InlineData(false)] + [InlineData(true)] + public static async Task ADbExceptionOnACallThatUsedTheSharedSet_RemovesItForEveryone(bool async) + { + var server = NameServer.Create(); + string procedure = Unique(); + + await Run(server.Connect(), procedure, async); + Assert.Equal(1, server.Reads); + + server.Failure = new FakeServerError(); + NameServer.NameConnection failing = server.Connect(); + if (async) + { + await Assert.ThrowsAsync(() => RunAsync(failing, procedure)); + } + else + { + Assert.Throws(() => Run(failing, procedure)); + } + + Assert.Equal(1, server.Reads); // it used what was shared, and did not read + + server.Failure = null; + await Run(server.Connect(), procedure, async); + Assert.Equal(2, server.Reads); + await Run(server.Connect(), procedure, async); + Assert.Equal(2, server.Reads); + } + + // ---- queries ---- + + [Fact] + public static async Task ADbNonQuery_OnAFreshConnectionForEachCall_ReadsOnce() + { + var server = NameServer.Create(); + server.Names = ["@order_id"]; + var write = DbNonQuery.Procedure(Unique()); + + for (int i = 0; i < 3; i++) + { + await write.Using(server.Connect()).AddParam(OrderId).ExecuteNonQueryAsync(Token); + } + + Assert.Equal(1, server.Reads); + } + + [Fact] + public static async Task ADbNonQuery_InATransactionOnAFreshConnectionForEachCall_ReadsOnce() + { + var server = NameServer.Create(); + server.Names = ["@order_id"]; + var write = DbNonQuery.Procedure(Unique()); + + for (int i = 0; i < 3; i++) + { + using DbTransaction transaction = server.Connect().BeginTransaction(); + await write.Using(transaction).AddParam(OrderId).ExecuteNonQueryAsync(Token); + } + + Assert.Equal(1, server.Reads); + } + + [Fact] + public static async Task ADbNonQuery_ReadsAQualifiedNameOnce_AndAnUnqualifiedNameForEachConnection() + { + var server = NameServer.Create(); + server.Names = ["@order_id"]; + string qualified = Unique(); + string unqualified = qualified[(qualified.IndexOf('.') + 1)..]; + var shared = DbNonQuery.Procedure(qualified); + var own = DbNonQuery.Procedure(unqualified); + + for (int i = 0; i < 3; i++) + { + await shared.Using(server.Connect()).AddParam(OrderId).ExecuteNonQueryAsync(Token); + } + + Assert.Equal(1, server.Reads); + + for (int i = 0; i < 3; i++) + { + await own.Using(server.Connect()).AddParam(OrderId).ExecuteNonQueryAsync(Token); + } + + Assert.Equal(4, server.Reads); + } + + // ---- what is in the shared tier ---- + + static void AssertNothingSharedFor(string procedure) + => Assert.DoesNotContain(ProcedureParameterNames.Shared.ByProcedure.Keys, key => key.Procedure == procedure); + + static void ClearShared() + => ProcedureParameterNames.Shared.ByProcedure.Clear(); +} diff --git a/Tests/Open.Database.Extensions.Core.Tests/NameCacheSourceTests.cs b/Tests/Open.Database.Extensions.Core.Tests/NameCacheSourceTests.cs index 590fdcb4..481786fe 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/NameCacheSourceTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/NameCacheSourceTests.cs @@ -140,6 +140,10 @@ static async Task RunAsync(LegacyCommand command) static string Procedure() => ParameterNameHarness.NewProcedure(); + // A name with a schema is shared by server and database whatever its source is (NameCacheSharedTierTests); one without stays with its source, which + // is what the tests of distinct sources need. + static string Unqualified() => Procedure()["dbo.".Length..]; + // ---- a non-generic factory ---- [Fact] @@ -375,13 +379,13 @@ await RunAsync( } #pragma warning restore CS0618 - // ---- distinct sources stay distinct ---- + // ---- distinct sources stay distinct (for a name without a schema) ---- [Fact] public static void CommandsFromDifferentNonGenericFactories_DoNotShareTheirNames() { var reads = new Reads(); - string procedure = Procedure(); + string procedure = Unqualified(); Run(new ExpressiveCommand(new PlainFactory(reads), CommandType.StoredProcedure, procedure)); Run(new ExpressiveCommand(new PlainFactory(reads), CommandType.StoredProcedure, procedure)); @@ -393,7 +397,7 @@ public static void CommandsFromDifferentNonGenericFactories_DoNotShareTheirNames public static void CommandsFromDifferentNonGenericPools_DoNotShareTheirNames() { var reads = new Reads(); - string procedure = Procedure(); + string procedure = Unqualified(); Run(new ExpressiveCommand(new PlainPool(reads), CommandType.StoredProcedure, procedure)); Run(new ExpressiveCommand(new PlainPool(reads), CommandType.StoredProcedure, procedure)); @@ -405,7 +409,7 @@ public static void CommandsFromDifferentNonGenericPools_DoNotShareTheirNames() public static void CommandsFromDifferentFunctions_DoNotShareTheirNames() { var reads = new Reads(); - string procedure = Procedure(); + string procedure = Unqualified(); Run(Capturing(reads).StoredProcedure(procedure)); Run(Capturing(reads).StoredProcedure(procedure)); @@ -421,7 +425,7 @@ public static void CommandsFromDifferentFunctions_DoNotShareTheirNames() public static void ACapturingLambdaBuiltTwice_IsTwoSources() { var reads = new Reads(); - string procedure = Procedure(); + string procedure = Unqualified(); Run(Capturing(reads).StoredProcedure(procedure)); Run(Capturing(reads).StoredProcedure(procedure)); diff --git a/Tests/Open.Database.Extensions.Core.Tests/TestHelpers/NameServer.cs b/Tests/Open.Database.Extensions.Core.Tests/TestHelpers/NameServer.cs new file mode 100644 index 00000000..9e18372c --- /dev/null +++ b/Tests/Open.Database.Extensions.Core.Tests/TestHelpers/NameServer.cs @@ -0,0 +1,90 @@ +using System.Data.Common; + +namespace Open.Database.Extensions.Tests; + +#nullable enable + +/// +/// A fake database server: every connection it makes reports the same DataSource and Database and answers the schema lookup +/// ProcedureParameters with the same parameter names, and counts how often any of them was asked. +/// +/// +/// A test gives each server a name no other test uses (), because what the library remembers about a procedure of a server and +/// a database is shared by the whole process. +/// +[ExcludeFromCodeCoverage] +internal sealed class NameServer(string? dataSource, string? database = "db") +{ + static int _counter; + + /// A server name that no other test in this process uses. + public static string Unique() => "server" + Interlocked.Increment(ref _counter); + + /// Makes a server with a name of its own. + public static NameServer Create() => new(Unique()); + + int _reads; + + public string? DataSource { get; } = dataSource; + + public string? Database { get; } = database; + + /// Gets how many schema lookups the connections of this server answered. + public int Reads => Volatile.Read(ref _reads); + + /// Gets or sets the names every lookup answers; none answers an empty table. + public string[] Names { get; set; } = ["@region"]; + + /// Gets or sets what every command run on a connection of this server throws, when set. + public Exception? Failure { get; set; } + + public NameConnection Connect() => new(this); + + DataTable Answer() + { + Interlocked.Increment(ref _reads); + var table = new DataTable("ProcedureParameters"); + table.Columns.Add("SPECIFIC_SCHEMA", typeof(string)); + table.Columns.Add("SPECIFIC_NAME", typeof(string)); + table.Columns.Add("ORDINAL_POSITION", typeof(int)); + table.Columns.Add("PARAMETER_NAME", typeof(string)); + for (int i = 0; i < Names.Length; i++) table.Rows.Add("dbo", "proc", i + 1, Names[i]); + return table; + } + + /// An open connection to a . + public sealed class NameConnection(NameServer server) : DbConnection + { + readonly DerivedParameterNameTests.RecordingDbCommand _command = new() { Failure = server.Failure }; + + /// Gets the names of the parameters the last run sent. + public string[] Sent => [.. _command.Sent.Select(p => p.ParameterName)]; + + [AllowNull] + public override string ConnectionString { get; set; } = ""; + public override string Database => server.Database!; + public override string DataSource => server.DataSource!; + public override string ServerVersion => "1.0"; + public override ConnectionState State => ConnectionState.Open; + public override void ChangeDatabase(string databaseName) { } + public override void Open() { } + public override void Close() { } + protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel) => new NameTransaction(this, isolationLevel); + + protected override DbCommand CreateDbCommand() + { + _command.Parameters.Clear(); // the fake hands out one command + return _command; + } + + public override DataTable GetSchema(string collectionName, string?[] restrictionValues) => server.Answer(); + } + + sealed class NameTransaction(NameConnection connection, IsolationLevel level) : DbTransaction + { + public override IsolationLevel IsolationLevel => level; + protected override DbConnection DbConnection => connection; + public override void Commit() { } + public override void Rollback() { } + } +} diff --git a/docsite/articles/expressive-commands.md b/docsite/articles/expressive-commands.md index 0c93fd83..e9efd575 100644 --- a/docsite/articles/expressive-commands.md +++ b/docsite/articles/expressive-commands.md @@ -157,17 +157,28 @@ An argument that is not a plain member chain (a call, an index, an operator, a l #### Parameter names are read once -The first call to a stored procedure asks the database for the procedure's parameter names. Later calls reuse them. The names are kept with the object your connections come from: the connection factory, the pool, or the connection itself when you start from one. They go when that object goes, so a factory kept for the life of the application keeps them for that long. Every command made from the same factory or pool shares them, whether you give it the object or a method of it. A function is told apart by the object its method belongs to: methods of one object are one source, lambdas that capture nothing are one source for their class, and a lambda that captures a local variable or a parameter is a new source each time it is created. A pool that is a struct, passed to `ExpressiveCommand(IDbConnectionPool)`, is boxed again for each command and does not share: pass a class. The key has no login or default schema, so two logins to one server and database share a set when they use the same factory (see the schema-qualified name below). **Keep one factory for the application (static or a singleton):** a factory or a connection you create for each scope or call asks the database every time. +The first call to a stored procedure asks the database for the procedure's parameter names. Later calls reuse them. Where they are kept depends on the name you give the procedure. -Names are kept per server, database and procedure name. One factory keeps the names of up to 1024 procedures; past that it starts over. +**A name with a schema (`dbo.get_author`) is kept once per server and database,** for the life of the process. Every command and query of the library's own types that runs on a `DbConnection` that reports its server (`DataSource`) and its `Database` finds them there, whichever connection, factory, pool or transaction it was made from, so a connection or a factory you create for each call asks the database once, not every time. Up to 1024 procedures are kept this way; past that, new names are kept as described next, and nothing already kept is dropped. -A call forgets the names when it cannot be built (for example, an argument matches no parameter, or two match one), or when a `DbException` is thrown once it is built: the database rejecting it, a command timeout, an error while the rows are read, or one from your own code inside the call. The next call reads them again, so an `AddParam(value)` argument the kept names lack fails once and the call after it uses the new names. The failed call is not retried, and its exception reaches you unchanged. A cancellation reported as `OperationCanceledException`, and failures in reading or converting a value, keep them; SQL Server reports a cancel while a command runs as `SqlException`, which forgets them. So when a parameter is renamed, removed or becomes required while the application runs, calls using the old names fail, with `InvalidOperationException` before they are sent (an argument that matches nothing) or with the database's own error, and calls after a failure use the new names. +**Everything else is kept with the object your connections come from:** the connection factory, the pool, or the connection itself when you start from one. That is a name without a schema (`get_author`: each login resolves it in its own default schema, so it can be a different procedure for each), an answer of no names (see below), a connection that reports no server or no database or is not a `DbConnection`, and a command class of your own that derives from a library command type. These names go when that object goes, so a factory kept for the life of the application keeps them for that long. Every command made from the same factory or pool shares them, whether you give it the object or a method of it; a function is told apart by the object its method belongs to: methods of one object are one source, lambdas that capture nothing are one source for their class, and a lambda that captures a local variable or a parameter is a new source each time it is created. A pool that is a struct, passed to `ExpressiveCommand(IDbConnectionPool)`, is boxed again for each command and does not share: pass a class. The key has no login or default schema, so two logins to one server and database share a set when they use the same factory. **For these, keep one factory for the application (static or a singleton):** a factory or a connection you create for each scope or call asks the database every time. One factory keeps the names of up to 1024 procedures; past that it starts over. + +Names are kept per server, database and procedure name, the procedure as you wrote it. + +A call forgets the names when it cannot be built (for example, an argument matches no parameter, or two match one), or when a `DbException` is thrown once it is built: the database rejecting it, a command timeout, an error while the rows are read, or one from your own code inside the call. The next call reads them again, so an `AddParam(value)` argument the kept names lack fails once and the call after it uses the new names. The failed call is not retried, and its exception reaches you unchanged. Names kept for the whole process are forgotten for every connection: the next call from any of them reads them again. A cancellation reported as `OperationCanceledException`, and failures in reading or converting a value, keep them; SQL Server reports a cancel while a command runs as `SqlException`, which forgets them. So when a parameter is renamed, removed or becomes required while the application runs, calls using the old names fail, with `InvalidOperationException` before they are sent (an argument that matches nothing) or with the database's own error, and calls after a failure use the new names. One change causes no failure and is therefore not noticed: a new parameter that has a default. A member of an `AddParams` object that would fill it is still not sent, and the procedure uses its default, until the names are read again: after a call that used them fails, or when the application restarts. Change the procedure before you deploy the code that passes the value, or restart the application. -When the database reports no names (the login cannot see the procedure, it declares no parameters, the name has a database part, or the provider cannot report names), that answer is kept the same way, and each argument is sent under the name as written. +When the database reports no names (the login cannot see the procedure, it declares no parameters, the name has a database part, or the provider cannot report names), that answer is kept with the object your connections come from, never shared, and each argument is sent under the name as written. + +Names read inside a transaction are kept even if the transaction rolls back. Give the procedure its schema (`dbo.get_author`): a name without one is resolved by each login's default schema, so it is kept for each source of connections and never shared. + +What sharing means for names kept for the whole process: -Names read inside a transaction are kept even if the transaction rolls back. Give the procedure its schema (`dbo.get_author`) when logins with different default schemas share one factory. +- **Every login of the process sees them.** They are names, not data. But a name that matches no parameter throws with the list of what the procedure declares, so a login with no right on the procedure can see them there once another login has read them (SQL Server already shows the parameters to a login that may only execute it). The process is the boundary: do not share a process between logins that must not see each other's procedure signatures. +- **A server is told by the name it reports as its `DataSource`.** Two servers that report the same name at different times (a test container on `localhost,1433` that is recreated with another version of the procedures, a failover to a server whose procedures differ) share one entry until a call fails and forgets it, as with any names that have gone stale. +- **A fake connection in a test reports one server and one database.** Every test in the process that uses such a fake shares its names, so a test that counts the lookups depends on the order the tests run in. Give each fake a server name of its own, or leave it empty: an empty one is never shared. +- **A call that fails for lack of the right to run the procedure forgets the names for everyone.** Other calls read them again; it costs lookups, nothing more. #### What was sent? diff --git a/docsite/articles/release-notes.md b/docsite/articles/release-notes.md index 72b9b5f1..23b72a1d 100644 --- a/docsite/articles/release-notes.md +++ b/docsite/articles/release-notes.md @@ -8,6 +8,7 @@ Version 11 is `11.0.0-rc.17`. For moving a 10.x codebase, read [Coming from earl - **Fixed: a command made from a factory, a pool or a function read a procedure's parameter names again for every command.** A command made from a factory or pool that implements only the non-generic interface, or from a `Func` or a `Func` through `Command` or `StoredProcedure`, kept a separate cache per command, so the first run of every command asked the database for the names. Commands made from the same factory, pool or function now share one cache. Different factories, pools and functions still do not share. A function is told apart by the object its method belongs to: lambdas that capture nothing, in one class, are one source and share; a lambda that captures a local variable or a parameter and is built again for each call is a new source each time, so keep one factory for the application. See [Parameter names are read once](expressive-commands.md#parameter-names-are-read-once). - **Fixed: a stored procedure's parameter names with an ordinal that is not a number.** A row of the `ProcedureParameters` schema collection whose `ORDINAL_POSITION` is not a number that fits an `int` failed the call that looks up the names; the row is now skipped, and the other parameters are still found. +- **Changed: a procedure with a schema in its name has its parameter names read once per server and database, not once per source of connections.** A command or query of the library's own types that runs on a `DbConnection` which reports its server and its database finds the names of `dbo.get_author` there, whichever connection, factory, pool or transaction it was made from, so a connection created for each call no longer asks the database every time. A name without a schema, an answer of no names, a connection that reports no server or database, and a command class of your own stay with the source of the connections, as before. Up to 1024 procedures are shared; past that, new names stay with their source and nothing is dropped. The names are shared by every login of the process: see [Parameter names are read once](expressive-commands.md#parameter-names-are-read-once) for what that means. ### Changes since rc.16 From 069a9a9ef698c0c6ff33d72ae946181d559f5444 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Thu, 3 Dec 2026 15:26:59 -0800 Subject: [PATCH 2/5] Keep a user's own command types apart from the library's in the name cache, and tidy the shared-tier tests A command class of the user's own that overrides how parameter names are read could remember its names in the same per-source table as the library's own commands, so a library command on the same connection or factory could be given the user's names, and the other way round. Such commands now keep their names in a table of their own for each source, found and kept by separate methods; the library's commands and queries keep the shared tier and their own table as before. No public API changes. Cost: none on the library's hit path; a user command does the same single lookup it did before, in its own table. Tests: new cases where the user's command runs first and the library's second on the same connection, and the reverse, for a name without a schema, a name with one, and a name with one while the shared tier is full. The shared-tier tests, the SQL Server tests and the cost tests now all sit in the one collection that runs alone, and the fakes of other tests that return names use a server name of their own. The synchronous and asynchronous paths are separate tests instead of one taking a flag, a non-DbConnection command also checks what it sends, a key without a server or database is checked directly, the SQL Server scene drops each object even when one drop fails and disposes its connection when impersonating fails, and the user and schema names there are neutral. Comments and code of the previous commit are wrapped, and a comment says the shared bound may be overshot by a few sets when calls race. Co-Authored-By: Claude Sonnet 5.5 --- Source/Core/DbQuery.cs | 3 +- Source/Core/DbQueryRunner.cs | 5 +- Source/Core/ExpressiveCommandBase.cs | 22 +- Source/Core/ProcedureParameterNames.cs | 127 +++++-- .../DerivedNameCostTests.cs | 63 ---- .../NameCacheSharedTierCostTests.cs | 88 +++++ .../NameCacheSharedTierLocalDbTests.cs | 107 ++++-- .../NameCacheSharedTierTests.cs | 331 ++++++++++++------ .../NameCacheSourceTests.cs | 14 +- .../OutputMetadataTests.cs | 4 +- .../TestHelpers/NameServer.cs | 63 ++-- docsite/articles/expressive-commands.md | 2 +- 12 files changed, 556 insertions(+), 273 deletions(-) create mode 100644 Tests/Open.Database.Extensions.Core.Tests/NameCacheSharedTierCostTests.cs diff --git a/Source/Core/DbQuery.cs b/Source/Core/DbQuery.cs index 4c6dae09..a8736224 100644 --- a/Source/Core/DbQuery.cs +++ b/Source/Core/DbQuery.cs @@ -72,7 +72,8 @@ internal DbQuery WithOutput(OutputLayout layout) /// // A definition is a static field, so a call that derives names scans // nothing. A procedure's names are remembered per server and - // database when its name has a schema, else per source (ProcedureParameterNames). A set with no names means "not known": each + // database when its name has a schema, else per source + // (ProcedureParameterNames). A set with no names means "not known": each // argument is sent as written. internal NameSet? TextNames { get; } diff --git a/Source/Core/DbQueryRunner.cs b/Source/Core/DbQueryRunner.cs index 472a98fd..e2e69e24 100644 --- a/Source/Core/DbQueryRunner.cs +++ b/Source/Core/DbQueryRunner.cs @@ -321,7 +321,10 @@ static ProcedureKey KeyOf(DbConnection connection, DbQuery definition) object owner = NameCacheOwner(source, connection); ProcedureKey key = KeyOf(connection, definition); return ProcedureParameterNames.FindShared(owner, key) - ?? ProcedureParameterNames.RememberShared(owner, key, ProcedureSchemaNames.Get(connection, definition.CommandText)); + ?? ProcedureParameterNames.RememberShared( + owner, + key, + ProcedureSchemaNames.Get(connection, definition.CommandText)); } /// diff --git a/Source/Core/ExpressiveCommandBase.cs b/Source/Core/ExpressiveCommandBase.cs index 9665e40a..c8e3124f 100644 --- a/Source/Core/ExpressiveCommandBase.cs +++ b/Source/Core/ExpressiveCommandBase.cs @@ -523,9 +523,10 @@ public TThis AddParam(string name, string? value) /// when the names are known, what the procedure declares. /// /// - /// A stored procedure's names are read once per server and database when its name has a schema (dbo.get_author) and this is one of the library's - /// own command types, else once per connection factory, pool or connection; and again after a call that cannot be built (other than by cancellation) or - /// that the database rejects. + /// A stored procedure's names are read once per server and database when its name has a + /// schema (dbo.get_author) and this is one of the library's own command types, else + /// once per connection factory, pool or connection; and again after a call that cannot be + /// built (other than by cancellation) or that the database rejects. /// /// /// Where the real names are not available (a text command with no @@ -1062,28 +1063,29 @@ ProcedureKey KeyOf(TConnection connection) /// /// Finds the names kept for a procedure: for a command of the library's own /// type, the ones shared by server and database first, then the source's; - /// for any other command, the source's. + /// for a command type of the user's own, the ones it kept for the source. /// /// The key made by . /// The set, or when none is kept. // A command type of the user's own may answer names that are its own (it - // overrides how they are read), so its answers are never given to another - // command, nor another's to it. Per call: one virtual type test. + // overrides how they are read), so what it keeps lives in a table of its + // own: never given to the library's commands, nor theirs to it. Per call: + // one virtual type test. NameSet? FindNames(ProcedureKey key) => IsLibraryCommand ? ProcedureParameterNames.FindShared(_poolOrConnection, key) - : ProcedureParameterNames.Find(_poolOrConnection, key); + : ProcedureParameterNames.FindUser(_poolOrConnection, key); /// - /// Keeps the names a lookup answered, shared as finds them. + /// Keeps the names a lookup answered, where finds them. /// /// The key made by . - /// The names as the provider reported them; empty or the default array when it reported none. + /// The names the provider reported; none when it reported none. /// The set kept for the procedure. NameSet RememberNames(ProcedureKey key, ImmutableArray names) => IsLibraryCommand ? ProcedureParameterNames.RememberShared(_poolOrConnection, key, names) - : ProcedureParameterNames.Remember(_poolOrConnection, key, names); + : ProcedureParameterNames.RememberUser(_poolOrConnection, key, names); /// /// Builds, in , what one run of a command with written names sends: each name that the text declares diff --git a/Source/Core/ProcedureParameterNames.cs b/Source/Core/ProcedureParameterNames.cs index 129a55bf..6403be24 100644 --- a/Source/Core/ProcedureParameterNames.cs +++ b/Source/Core/ProcedureParameterNames.cs @@ -57,12 +57,21 @@ public override int GetHashCode() /// An entry is a : the names the database reported (none, when it reports none) and the real name each argument has matched. /// /// -/// One kind of entry is kept apart from its source, in : the names of a schema-qualified procedure, as answered for a server and -/// a database, found by every command and query of the library's own types that runs on a that names both. A schema-qualified -/// name is the same procedure for every login of the database, so the answer does not depend on who asked. An unqualified name (the login's default -/// schema picks the procedure), an answer of no names, a connection that names no server or database, and a command type of the user's own stay with -/// their source. The shared entries are never cleared or evicted and nothing expires them: at of them, new sets go to -/// their source, as before. A failure that forgets an entry removes the shared one for everyone, and the next call reads it again. +/// One kind of entry is kept apart from its source, in : the names of a +/// schema-qualified procedure, as answered for a server and a database, found by every command +/// and query of the library's own types that runs on a that names +/// both. A schema-qualified name is the same procedure for every login of the database, so the +/// answer does not depend on who asked. An unqualified name (the login's default schema picks +/// the procedure), an answer of no names, and a connection that names no server or database +/// stay with their source. The shared entries are never cleared or evicted and nothing expires +/// them: at of them, new sets go to their source, as before. A +/// failure that forgets an entry removes the shared one for everyone, and the next call reads +/// it again. +/// +/// +/// A command type of the user's own may answer names that are its own (it overrides how they are +/// read), so what it remembers is kept in a table of its own for each source, apart from what the +/// library's own types keep there: neither is ever given to the other, and none of it is shared. /// /// /// Which failures forget an entry, the one rule for every path: a call that fails while it is being built forgets, unless it was canceled; @@ -74,8 +83,9 @@ public override int GetHashCode() static class ProcedureParameterNames { /// - /// How many procedures one source keeps; past it they are all dropped and read again as they are called. The shared entries hold at most as - /// many, and past it new sets go to their source. + /// How many procedures one source keeps; past it they are all dropped and read again as + /// they are called. The shared entries hold at most as many, and past it new sets go to + /// their source. /// // A memory cap, for procedure names built at run time and for many databases behind one factory. A procedure with five parameters takes about // 1.2 KB with its matches (measured on .NET 11, x64), so a full source holds about 1.2 MB. @@ -93,40 +103,76 @@ public sealed class Entries public WeakReference Weak { get; } } - /// The entries of each source, held weakly. + /// + /// The entries of each source for the library's own command types, held weakly. + /// static readonly ConditionalWeakTable Sources = new(); - /// The entries shared by every source: schema-qualified procedures of a server and a database. - // Held for the life of the process, so the weak reference every entry holds back to it never goes: Forget works as for a source's entries. + /// + /// The entries of each source for command types of the user's own, held weakly. + /// + static readonly ConditionalWeakTable UserSources = new(); + + /// + /// The entries shared by every source: schema-qualified procedures of a server and a + /// database. + /// + // Held for the life of the process, so the weak reference every entry holds back to it never + // goes: Forget works as for a source's entries. public static readonly Entries Shared = new(); /// - /// Gets the kept names of a procedure for a command of the library's own type, or for a query: the shared entry first, then the source's. + /// Gets the kept names of a procedure for a command of the library's own type, or for a + /// query: the shared entry first, then the source's. /// /// The object commands take their connections from. /// The server, database and procedure. /// The set, or when none is kept. - // Per call, beyond Find: two length checks on the key, and one lookup in the shared entries (which a key of an unqualified name misses). + // Per call, beyond Find: two length checks on the key, and one lookup in the shared entries + // (which a key of an unqualified name misses). public static NameSet? FindShared(object source, ProcedureKey key) => CanShare(key) && Shared.ByProcedure.TryGetValue(key, out NameSet? shared) ? shared : Find(source, key); - /// Gets whether a key names a server and a database: only then is its answer shared. + /// + /// Gets whether a key names a server and a database: only then is its answer shared. + /// /// The server, database and procedure. - /// if the key names both; otherwise, . - // A connection that is not a DbConnection has no server name, and one that does not know its database reports none: neither is told apart from another. + /// + /// if the key names both; otherwise, . + /// + // A connection that is not a DbConnection has no server name, and one that does not know its + // database reports none: neither is told apart from another. static bool CanShare(ProcedureKey key) => key.Server.Length != 0 && key.Database.Length != 0; - /// Gets the kept names of a procedure. + /// + /// Gets the kept names of a procedure for a command of the library's own type. + /// /// The object commands take their connections from. /// The server, database and procedure. /// The set, or when none is kept. public static NameSet? Find(object source, ProcedureKey key) - => Sources.TryGetValue(OwnerOf(source), out Entries? entries) && entries.ByProcedure.TryGetValue(key, out NameSet? names) - ? names - : null; + => FindIn(Sources, source, key); + + /// + /// Gets the kept names of a procedure for a command type of the user's own. + /// + /// The object commands take their connections from. + /// The server, database and procedure. + /// The set, or when none is kept. + public static NameSet? FindUser(object source, ProcedureKey key) + => FindIn(UserSources, source, key); + + static NameSet? FindIn( + ConditionalWeakTable table, + object source, + ProcedureKey key) + => table.TryGetValue(OwnerOf(source), out Entries? entries) + && entries.ByProcedure.TryGetValue(key, out NameSet? names) + ? names + : null; /// /// Gets what the names of a source belong to: the factory a pool made from @@ -140,29 +186,54 @@ static bool CanShare(ProcedureKey key) static object OwnerOf(object source) => source is IConnectionIdentity identity ? identity.Identity : source; - /// Keeps what the lookup answered. + /// Keeps what the lookup answered, for a command of the library's own type. /// The object commands take their connections from. /// The server, database and procedure the names belong to. /// The names as the database reported them; empty or the default array when it reported none. /// The set kept for the procedure: this one, or the one another call kept first. public static NameSet Remember(object source, ProcedureKey key, ImmutableArray names) + => RememberIn(Sources, source, key, names); + + /// Keeps what the lookup answered, for a command type of the user's own. + /// The object commands take their connections from. + /// The server, database and procedure the names belong to. + /// The names the database reported; none when it reported none. + /// The set kept for the procedure: this one, or the one kept first. + public static NameSet RememberUser( + object source, + ProcedureKey key, + ImmutableArray names) + => RememberIn(UserSources, source, key, names); + + static NameSet RememberIn( + ConditionalWeakTable table, + object source, + ProcedureKey key, + ImmutableArray names) { - Entries entries = Sources.GetValue(OwnerOf(source), static _ => new Entries()); + Entries entries = table.GetValue(OwnerOf(source), static _ => new Entries()); // Only here, where a lookup was just paid for, is the bound checked. if (entries.ByProcedure.Count >= MaxProcedures && !entries.ByProcedure.ContainsKey(key)) entries.ByProcedure.Clear(); return entries.ByProcedure.GetOrAdd(key, new NameSet(names.IsDefault ? [] : names, entries.Weak, key)); } /// - /// Keeps what the lookup answered, for a command of the library's own type or for a query: shared when it can be, else with its source. + /// Keeps what the lookup answered, for a command of the library's own type or for a query: + /// shared when it can be, else with its source. /// /// The object commands take their connections from. /// The server, database and procedure the names belong to. - /// The names as the database reported them; empty or the default array when it reported none. - /// The set kept for the procedure: this one, or the one another call kept first. - // Shared only when the answer holds names, the key names a server and a database, the procedure name has a schema, and the shared entries have room. - // The name is parsed here, after the round trip, and never on a lookup. - public static NameSet RememberShared(object source, ProcedureKey key, ImmutableArray names) + /// The names the database reported; none when it reported none. + /// The set kept for the procedure: this one, or the one kept first. + // Shared only when the answer holds names, the key names a server and a database, the + // procedure name has a schema, and the shared entries have room. The name is parsed here, + // after the round trip, and never on a lookup. The room is checked without a lock, so calls + // that race may overshoot the bound by a few sets: the bound is a memory cap, not an exact + // count. + public static NameSet RememberShared( + object source, + ProcedureKey key, + ImmutableArray names) { if (names.IsDefaultOrEmpty || !CanShare(key) diff --git a/Tests/Open.Database.Extensions.Core.Tests/DerivedNameCostTests.cs b/Tests/Open.Database.Extensions.Core.Tests/DerivedNameCostTests.cs index 16655628..d6d595bd 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/DerivedNameCostTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/DerivedNameCostTests.cs @@ -765,67 +765,4 @@ public static void ConcurrentExecutions_ShareOneNameSet_AndAllResolveTheSame() Assert.Equal(1000, results.Count); Assert.All(results, r => Assert.Equal("@order_id,@customer_id,@start_date", r)); } - - // ---- a shared set ---- - - // A schema-qualified procedure of the librarys own command type is found in the tier shared by every connection to its server and database: a repeat - // run costs what the hand-written names cost, as it does with the names kept by one connection. - [Fact] - public static void StoredProcedure_ASharedSet_DerivedCostsNoMoreThanExplicit() - { - var server = new NameServer(NameServer.Unique()) { Names = ["@order_id", "@customer_id", "@start_date"] }; - NameServer.NameConnection connection = server.Connect(); - string procedure = ParameterNameHarness.NewProcedure(); - const int orderId = 5, customerId = 7; - var startDate = new DateTime(2026, 1, 2); - - void Derived() - => new ExpressiveDbCommand(connection, CommandType.StoredProcedure, procedure) - .AddParam(orderId) - .AddParam(customerId) - .AddParam(startDate) - .ExecuteNonQuery(); - void Explicit() - => new ExpressiveDbCommand(connection, CommandType.StoredProcedure, procedure) - .AddParam("@order_id", orderId) - .AddParam("@customer_id", customerId) - .AddParam("@start_date", startDate) - .ExecuteNonQuery(); - - long derived = BytesPerCall(Derived); - long explicitName = BytesPerCall(Explicit); - - Assert.Equal(1, server.Reads); - AssertWithinBudget("stored procedure, shared set, three plain locals", derived, explicitName); - } - - // The lookup itself, apart from building a command: a shared set is found, and so is a set a source keeps for an unqualified name (a miss in the - // shared entries first), without allocating. - [Fact] - public static void FindingAKeptSet_SharedOrOfItsSource_AllocatesNothing() - { - object source = new(); - string server = NameServer.Unique(); - var qualified = new ProcedureKey(server, "db", "dbo.find"); - var unqualified = new ProcedureKey(server, "db", "find"); - NameSet shared = ProcedureParameterNames.RememberShared(source, qualified, ["@a"]); - NameSet owned = ProcedureParameterNames.RememberShared(source, unqualified, ["@a"]); - NameSet? found = null; - - try - { - Assert.Same(shared, ProcedureParameterNames.FindShared(new object(), qualified)); - Assert.Null(ProcedureParameterNames.FindShared(new object(), unqualified)); - Assert.Same(owned, ProcedureParameterNames.FindShared(source, unqualified)); - - Assert.Equal(0, BytesPerCall(() => found = ProcedureParameterNames.FindShared(source, qualified))); - Assert.Equal(0, BytesPerCall(() => found = ProcedureParameterNames.FindShared(source, unqualified))); - GC.KeepAlive(found); - } - finally - { - ProcedureParameterNames.Forget(shared); - ProcedureParameterNames.Forget(owned); - } - } } diff --git a/Tests/Open.Database.Extensions.Core.Tests/NameCacheSharedTierCostTests.cs b/Tests/Open.Database.Extensions.Core.Tests/NameCacheSharedTierCostTests.cs new file mode 100644 index 00000000..369b2150 --- /dev/null +++ b/Tests/Open.Database.Extensions.Core.Tests/NameCacheSharedTierCostTests.cs @@ -0,0 +1,88 @@ +using System.Data.Common; + +namespace Open.Database.Extensions.Tests; + +#nullable enable + +// What a repeat run costs when the names come from the shared tier. They run in the collection +// of the shared tier (see NameCacheSharedTierTests), where no other test touches it meanwhile. +[Collection("Shared name tier")] +[ExcludeFromCodeCoverage] +public static class NameCacheSharedTierCostTests +{ + // A schema-qualified procedure of the library's own command type is found in the tier shared + // by every connection to its server and database: a repeat run costs what the hand-written + // names cost, as it does with the names kept by one connection. + [Fact] + public static void StoredProcedure_ASharedSet_DerivedCostsNoMoreThanExplicit() + { + var server = new NameServer(NameServer.Unique()) + { + Names = ["@order_id", "@customer_id", "@start_date"], + }; + NameServer.NameConnection connection = server.Connect(); + string procedure = ParameterNameHarness.NewProcedure(); + const int orderId = 5, customerId = 7; + var startDate = new DateTime(2026, 1, 2); + + void Derived() + => new ExpressiveDbCommand(connection, CommandType.StoredProcedure, procedure) + .AddParam(orderId) + .AddParam(customerId) + .AddParam(startDate) + .ExecuteNonQuery(); + + void Explicit() + => new ExpressiveDbCommand(connection, CommandType.StoredProcedure, procedure) + .AddParam("@order_id", orderId) + .AddParam("@customer_id", customerId) + .AddParam("@start_date", startDate) + .ExecuteNonQuery(); + + long derived = DerivedNameCostTests.BytesPerCall(Derived); + long explicitName = DerivedNameCostTests.BytesPerCall(Explicit); + + Assert.Equal(1, server.Reads); + DerivedNameCostTests.AssertWithinBudget( + "stored procedure, shared set, three plain locals", + derived, + explicitName); + } + + // The lookup itself, apart from building a command: a shared set is found, and so is a set + // a source keeps for an unqualified name (a miss in the shared entries first), without + // allocating. + [Fact] + public static void FindingAKeptSet_SharedOrOfItsSource_AllocatesNothing() + { + object source = new(); + string server = NameServer.Unique(); + var qualified = new ProcedureKey(server, "db", "dbo.find"); + var unqualified = new ProcedureKey(server, "db", "find"); + NameSet shared = ProcedureParameterNames.RememberShared(source, qualified, ["@a"]); + NameSet owned = ProcedureParameterNames.RememberShared(source, unqualified, ["@a"]); + NameSet? found = null; + + try + { + Assert.Same(shared, ProcedureParameterNames.FindShared(new object(), qualified)); + Assert.Null(ProcedureParameterNames.FindShared(new object(), unqualified)); + Assert.Same(owned, ProcedureParameterNames.FindShared(source, unqualified)); + + Assert.Equal( + 0, + DerivedNameCostTests.BytesPerCall( + () => found = ProcedureParameterNames.FindShared(source, qualified))); + Assert.Equal( + 0, + DerivedNameCostTests.BytesPerCall( + () => found = ProcedureParameterNames.FindShared(source, unqualified))); + GC.KeepAlive(found); + } + finally + { + ProcedureParameterNames.Forget(shared); + ProcedureParameterNames.Forget(owned); + } + } +} diff --git a/Tests/Open.Database.Extensions.Core.Tests/NameCacheSharedTierLocalDbTests.cs b/Tests/Open.Database.Extensions.Core.Tests/NameCacheSharedTierLocalDbTests.cs index 4eae1c28..969ee184 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/NameCacheSharedTierLocalDbTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/NameCacheSharedTierLocalDbTests.cs @@ -6,15 +6,18 @@ namespace Open.Database.Extensions.Tests; -// The shared tier against SQL Server: what a schema-qualified name means for logins with different default schemas, and what a login that may only -// execute a procedure can see of it. A login is a database user without a login, entered with EXECUTE AS USER on a connection of its own: a name is -// resolved by the user's default schema and the metadata a user sees by the user's permissions, whichever way the user got in. Skipped without LocalDB -// (see LocalDbFixture). +// The shared tier against SQL Server: what a schema-qualified name means for logins with +// different default schemas, and what a login that may only execute a procedure sees of it. A +// login is a database user without a login, entered with EXECUTE AS USER on a connection of its +// own: a name is resolved by the user's default schema and the metadata a user sees by the +// user's permissions, whichever way the user got in. In the collection of the shared tier, +// which runs alone, so its DDL meets no other. Skipped without LocalDB (see LocalDbFixture). [ExcludeFromCodeCoverage] -[Collection("LocalDB DDL")] +[Collection("Shared name tier")] public static class NameCacheSharedTierLocalDbTests { - static CancellationToken Token => TestContext.Current.CancellationToken; + static CancellationToken Token + => TestContext.Current.CancellationToken; // Schemas, users and procedures made for one test and dropped when it ends. sealed class Scene : IDisposable @@ -25,10 +28,10 @@ public Scene() { string id = Guid.NewGuid().ToString("N")[..12]; Procedure = "p_" + id; - First = "d1_" + id; - Second = "d2_" + id; - Shared = "s_" + id; - ExecuteOnly = "ode_u3_" + id; + First = "odx_name_first_" + id; + Second = "odx_name_second_" + id; + Shared = "odx_name_shared_" + id; + ExecuteOnly = "odx_name_user_execute_" + id; foreach (string schema in new[] { First, Second, Shared }) { Run($"create schema [{schema}]"); @@ -51,7 +54,8 @@ public Scene() /// Gets the user that may only execute one procedure. public string ExecuteOnly { get; } - public static void Run(string sql) => LocalDbFixture.Execute(sql); + public static void Run(string sql) + => LocalDbFixture.Execute(sql); public string AddUser(string name, string defaultSchema) { @@ -60,28 +64,52 @@ public string AddUser(string name, string defaultSchema) return name; } - public void AddProcedure(string schema, string parameter, string answer) + public void AddProcedure(string schema, string parameters, string answer) { - Run($"create procedure [{schema}].[{Procedure}] {parameter} as select '{answer}' as which"); + Run( + $"create procedure [{schema}].[{Procedure}] {parameters} " + + $"as select '{answer}' as which"); _drops.Insert(0, $"drop procedure if exists [{schema}].[{Procedure}]"); } public void Dispose() { - foreach (string drop in _drops) Run(drop); + foreach (string drop in _drops) + { + // A drop that fails must not leave the rest of the scene behind. + try + { + Run(drop); + } + catch (SqlException) + { + } + } } } - // A connection of its own (not pooled, so nothing of the impersonation outlives it) that acts as a database user. + // A connection of its own (not pooled, so nothing of the impersonation outlives it) that + // acts as a database user. static async Task OpenAs(string user) { - var builder = new SqlConnectionStringBuilder(LocalDbFixture.ConnectionString) { Pooling = false }; + var builder = new SqlConnectionStringBuilder(LocalDbFixture.ConnectionString) + { + Pooling = false, + }; var connection = new SqlConnection(builder.ConnectionString); - await connection.OpenAsync(Token); - await using SqlCommand command = connection.CreateCommand(); - command.CommandText = $"execute as user = '{user}'"; - await command.ExecuteNonQueryAsync(Token); - return connection; + try + { + await connection.OpenAsync(Token); + await using SqlCommand command = connection.CreateCommand(); + command.CommandText = $"execute as user = '{user}'"; + await command.ExecuteNonQueryAsync(Token); + return connection; + } + catch + { + await connection.DisposeAsync(); + throw; + } } static string? Which(SqlConnection connection, string procedure, string member) @@ -92,15 +120,17 @@ static async Task OpenAs(string user) static bool IsShared(string procedure) => ProcedureParameterNames.Shared.ByProcedure.Keys.Any(key => key.Procedure == procedure); - // Two logins whose default schemas differ, each with a procedure of the same name in its own schema, and a third schema with another: a name with a - // schema is the one procedure for both, with the same names, and is shared; the name without one is each login's own procedure, and is not. + // Two logins whose default schemas differ, each with a procedure of the same name in its own + // schema, and a third schema with another: a name with a schema is the one procedure for + // both, with the same names, and is shared; the name without one is each login's own + // procedure, and is not. [Fact] - public static async Task TwoLoginsWithDifferentDefaultSchemas_ShareASchemaQualifiedProcedure_AndEachGetsItsOwnUnqualifiedOne() + public static async Task TwoLogins_ShareAQualifiedProcedure_AndEachGetsItsOwnUnqualifiedOne() { LocalDbFixture.SkipUnlessAvailable(); using var scene = new Scene(); - string one = scene.AddUser("ode_u1_" + scene.Procedure, scene.First); - string two = scene.AddUser("ode_u2_" + scene.Procedure, scene.Second); + string one = scene.AddUser("odx_name_user_1_" + scene.Procedure, scene.First); + string two = scene.AddUser("odx_name_user_2_" + scene.Procedure, scene.Second); scene.AddProcedure(scene.First, "@alpha int", "first"); scene.AddProcedure(scene.Second, "@beta int", "second"); scene.AddProcedure(scene.Shared, "@region int", "shared"); @@ -117,16 +147,19 @@ public static async Task TwoLoginsWithDifferentDefaultSchemas_ShareASchemaQualif Assert.True(IsShared(qualified)); Assert.Equal("shared", Which(second, qualified, "filter.Region")); - // Each login's own procedure of that name, by the names it declares: another login's names would not fit. + // Each login's own procedure of that name, by the names it declares: another login's + // names would not fit. Assert.Equal("first", Which(first, scene.Procedure, "filter.Alpha")); Assert.Equal("second", Which(second, scene.Procedure, "filter.Beta")); Assert.False(IsShared(scene.Procedure)); } - // A login that may only execute one procedure: the schema lookup answers with its parameters (observed on SQL Server), so such a login reads the names - // as any other and is not given an empty answer. Pinned because the docs say what a shared set shows to a login with no right on the procedure. + // A login whose only right on a procedure is EXECUTE: the schema lookup answers with the + // parameters (observed on SQL Server), so such a login reads the names as any other and is + // not given an empty answer. Pinned because the docs say what a shared set shows to a login + // with no right on the procedure at all: that is a login this test does not cover. [Fact] - public static async Task ALoginThatMayOnlyExecuteAProcedure_SeesItsParametersInTheSchemaLookup() + public static async Task ALoginWhoseOnlyRightIsExecute_SeesTheParametersInTheSchemaLookup() { LocalDbFixture.SkipUnlessAvailable(); using var scene = new Scene(); @@ -135,10 +168,18 @@ public static async Task ALoginThatMayOnlyExecuteAProcedure_SeesItsParametersInT Scene.Run($"grant execute on object::[{scene.Shared}].[{scene.Procedure}] to [{user}]"); await using SqlConnection connection = await OpenAs(user); - using DataTable table = connection.GetSchema("ProcedureParameters", [null, scene.Shared, scene.Procedure, null]); + using DataTable table = connection.GetSchema( + "ProcedureParameters", + [null, scene.Shared, scene.Procedure, null]); - // SQL Server reports both parameters to a user whose only right on the procedure is EXECUTE. + // SQL Server reports both parameters to a user whose only right is EXECUTE. Assert.Equal(2, table.Rows.Count); - Assert.Equal(["@region", "@other"], table.Rows.Cast().OrderBy(row => Convert.ToInt32(row["ORDINAL_POSITION"], System.Globalization.CultureInfo.InvariantCulture)).Select(row => (string)row["PARAMETER_NAME"])); + Assert.Equal( + ["@region", "@other"], + table.Rows.Cast() + .OrderBy(row => Convert.ToInt32( + row["ORDINAL_POSITION"], + System.Globalization.CultureInfo.InvariantCulture)) + .Select(row => (string)row["PARAMETER_NAME"])); } } diff --git a/Tests/Open.Database.Extensions.Core.Tests/NameCacheSharedTierTests.cs b/Tests/Open.Database.Extensions.Core.Tests/NameCacheSharedTierTests.cs index a11b8a8a..5e61399a 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/NameCacheSharedTierTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/NameCacheSharedTierTests.cs @@ -4,11 +4,19 @@ namespace Open.Database.Extensions.Tests; #nullable enable -// A schema-qualified procedure's parameter names are read once per server and database and shared by every command and query of the library's own -// types, whatever connection or factory they run on. Everything else (an unqualified name, an empty answer, a connection that names no server or -// database, a command type of the user's own) stays with the source of its connections, as it always was. Reads are counted at the provider: each -// one is a GetSchema call on a connection. The tests run alone (see the collection) because they fill the process-wide tier, and each test uses a -// server name of its own. +// A schema-qualified procedure's parameter names are read once per server and database and +// shared by every command and query of the library's own types, whatever connection or factory +// they run on. Everything else (an unqualified name, an empty answer, a connection that names no +// server or database, a command type of the user's own) stays with the source of its +// connections, as it always was. Reads are counted at the provider: each one is a GetSchema call +// on a connection. +// +// Every test that reads or writes ProcedureParameterNames.Shared is in this collection. A +// collection that disables parallelization runs after the parallel ones, one test at a time, so +// no test runs while the bound test has the process-wide tier full or cleared. Each test uses a +// server name of its own (NameServer.Unique), so what another test shared is never found. +// Tests in other collections that use a qualified name on a fake give it a server name of its +// own too. [CollectionDefinition("Shared name tier", DisableParallelization = true)] public sealed class SharedNameTierCollection; @@ -16,77 +24,97 @@ public sealed class SharedNameTierCollection; [ExcludeFromCodeCoverage] public static class NameCacheSharedTierTests { - static CancellationToken Token => TestContext.Current.CancellationToken; + static CancellationToken Token + => TestContext.Current.CancellationToken; const int OrderId = 1; // a name to derive the parameter name from - sealed class FakeServerError(string message = "rejected by the server") : DbException(message); + // The most procedures the shared tier holds. + const int Bound = 1024; - // What a user's own command type answers for the parameter names of any procedure. + sealed class FakeServerError(string message = "rejected by the server") + : DbException(message); + + // What a user's own command type answers for the parameter names of any procedure: the + // same argument matches it as matches the server's names, under another spelling. sealed class CustomNamesCommand(DbConnection connection, string procedure) : ExpressiveDbCommand(connection, CommandType.StoredProcedure, procedure) { - protected override ImmutableArray GetProcedureParameterNames(DbConnection connection, string procedure) + protected override ImmutableArray GetProcedureParameterNames( + DbConnection connection, + string procedure) => ["@REGION"]; - protected override ValueTask> GetProcedureParameterNamesAsync(DbConnection connection, string procedure, CancellationToken cancellationToken) + protected override ValueTask> GetProcedureParameterNamesAsync( + DbConnection connection, + string procedure, + CancellationToken cancellationToken) => new(["@REGION"]); } - static void Run(NameServer.NameConnection connection, string procedure) + static void RunSync(NameServer.NameConnection connection, string procedure) => new ExpressiveDbCommand(connection, CommandType.StoredProcedure, procedure) .AddParam(value: 1, expression: "filter.Region") .ExecuteNonQuery(); - static async Task RunAsync(NameServer.NameConnection connection, string procedure) - => await new ExpressiveDbCommand(connection, CommandType.StoredProcedure, procedure) + static Task RunAsync(NameServer.NameConnection connection, string procedure) + => new ExpressiveDbCommand(connection, CommandType.StoredProcedure, procedure) .AddParam(value: 1, expression: "filter.Region") - .ExecuteNonQueryAsync(Token); + .ExecuteNonQueryAsync(Token) + .AsTask(); + + static void RunCustom(NameServer.NameConnection connection, string procedure) + => new CustomNamesCommand(connection, procedure) + .AddParam(value: 1, expression: "filter.Region") + .ExecuteNonQuery(); - static async Task Run(NameServer.NameConnection connection, string procedure, bool async) + // The same run as RunSync, as a task: it completes at once, or throws as RunSync does. + static Task RunSyncAsTask(NameServer.NameConnection connection, string procedure) { - if (async) - { - await RunAsync(connection, procedure); - } - else - { - Run(connection, procedure); - } + RunSync(connection, procedure); + return Task.CompletedTask; } - static string Unique() => ParameterNameHarness.NewProcedure(); + static string Unique() + => ParameterNameHarness.NewProcedure(); // A procedure name without a schema. - static string Unqualified() => Unique()[("dbo.".Length)..]; + static string Unqualified() + => Unique()["dbo.".Length..]; // ---- who shares ---- - [Theory] - [InlineData(false)] - [InlineData(true)] - public static async Task ASchemaQualifiedName_IsReadOnce_ForTwoFreshConnections(bool async) + static async Task AssertReadOnceForTwoFreshConnections( + Func run) { var server = NameServer.Create(); string procedure = Unique(); - await Run(server.Connect(), procedure, async); - await Run(server.Connect(), procedure, async); + await run(server.Connect(), procedure); + await run(server.Connect(), procedure); Assert.Equal(1, server.Reads); } + [Fact] + public static Task ASchemaQualifiedName_IsReadOnce_ForTwoFreshConnections_OnTheSyncPath() + => AssertReadOnceForTwoFreshConnections(RunSyncAsTask); + + [Fact] + public static Task ASchemaQualifiedName_IsReadOnce_ForTwoFreshConnections_OnTheAsyncPath() + => AssertReadOnceForTwoFreshConnections(RunAsync); + [Fact] public static void AnUnqualifiedName_IsReadOnceForEachConnection() { var server = NameServer.Create(); - string procedure = Unique()[(Unique().IndexOf('.') + 1)..]; // names1, no schema + string procedure = Unqualified(); - Run(server.Connect(), procedure); - Run(server.Connect(), procedure); + RunSync(server.Connect(), procedure); + RunSync(server.Connect(), procedure); NameServer.NameConnection same = server.Connect(); - Run(same, procedure); - Run(same, procedure); + RunSync(same, procedure); + RunSync(same, procedure); Assert.Equal(3, server.Reads); } @@ -98,8 +126,8 @@ public static void ASharedSet_ResolvesTheArgumentsOfEveryCommand() string procedure = Unique(); NameServer.NameConnection first = server.Connect(), second = server.Connect(); - Run(first, procedure); - Run(second, procedure); + RunSync(first, procedure); + RunSync(second, procedure); Assert.Equal(["@region"], first.Sent); Assert.Equal(["@region"], second.Sent); @@ -113,11 +141,11 @@ public static void AnEmptyAnswer_IsNotSharedButKeptByItsConnection() string procedure = Unique(); NameServer.NameConnection same = server.Connect(); - Run(same, procedure); - Run(same, procedure); + RunSync(same, procedure); + RunSync(same, procedure); Assert.Equal(1, server.Reads); - Run(server.Connect(), procedure); + RunSync(server.Connect(), procedure); Assert.Equal(2, server.Reads); } @@ -127,19 +155,27 @@ public static void AnEmptyAnswer_IsNotSharedButKeptByItsConnection() [InlineData("x", "")] [InlineData("x", null)] [InlineData("", "")] - public static void AConnectionThatNamesNoServerOrDatabase_IsReadForEachConnection(string? dataSource, string? database) + public static void AConnectionThatNamesNoServerOrDatabase_IsReadForEachConnection( + string? dataSource, + string? database) { - var server = new NameServer(dataSource is "x" ? NameServer.Unique() : dataSource, database); + // "x" stands for a server name of its own. + var server = new NameServer( + dataSource is "x" ? NameServer.Unique() : dataSource, + database); string procedure = Unique(); - Run(server.Connect(), procedure); - Run(server.Connect(), procedure); + RunSync(server.Connect(), procedure); + RunSync(server.Connect(), procedure); Assert.Equal(2, server.Reads); + AssertNothingSharedFor(procedure); } + // A library command on a connection that is not a DbConnection never reads: there is no + // schema lookup to ask. What it sends is the argument as written, and nothing is shared. [Fact] - public static void ACommandOnAConnectionThatIsNotADbConnection_ShareNothing() + public static void ANonDbConnection_SendsTheNameAsWritten_AndSharesNothing() { string procedure = Unique(); @@ -149,56 +185,131 @@ public static void ACommandOnAConnectionThatIsNotADbConnection_ShareNothing() new ExpressiveCommand(probe.Connection, CommandType.StoredProcedure, procedure) .AddParam(value: 1, expression: "filter.Region") .ExecuteNonQuery(); + Assert.Equal(["Region"], probe.Parameters.Select(p => p.ParameterName)); } AssertNothingSharedFor(procedure); } - [Fact] - public static void ACommandTypeOfTheUsersOwn_NeverGivesItsNamesToTheLibrarysCommands_AndNeverTakesTheirs() + // What a connection that is not a DbConnection (no server name) or that reports no database + // looks like to the tier: a key with an empty server or database is never shared, whatever + // the answer. + [Theory] + [InlineData("", "db")] + [InlineData("server", "")] + [InlineData("", "")] + public static void AKeyWithNoServerOrDatabase_IsNeverShared(string server, string database) { - var server = NameServer.Create(); string procedure = Unique(); + var key = new ProcedureKey(server, database, procedure); + var source = new object(); - NameServer.NameConnection mine = server.Connect(); - new CustomNamesCommand(mine, procedure).AddParam(value: 1, expression: "filter.Region").ExecuteNonQuery(); - Assert.Equal(["@REGION"], mine.Sent); + NameSet kept = ProcedureParameterNames.RememberShared(source, key, ["@region"]); + + AssertNothingSharedFor(procedure); + Assert.Same(kept, ProcedureParameterNames.FindShared(source, key)); + Assert.Null(ProcedureParameterNames.FindShared(new object(), key)); + } + + // ---- a command type of the user's own ---- + + // The user's command type runs first on a connection, then the library's on the same + // connection (so the same source): the library's reads its own names. + static void AssertTheLibraryDoesNotTakeTheUsersNames(NameServer server, string procedure) + { + NameServer.NameConnection source = server.Connect(); + + RunCustom(source, procedure); + Assert.Equal(["@REGION"], source.Sent); Assert.Equal(0, server.Reads); + AssertNothingSharedFor(procedure); - NameServer.NameConnection plain = server.Connect(); - Run(plain, procedure); - Assert.Equal(["@region"], plain.Sent); + RunSync(source, procedure); + Assert.Equal(["@region"], source.Sent); Assert.Equal(1, server.Reads); - NameServer.NameConnection again = server.Connect(); - new CustomNamesCommand(again, procedure).AddParam(value: 1, expression: "filter.Region").ExecuteNonQuery(); - Assert.Equal(["@REGION"], again.Sent); + // Each keeps its own from then on. + RunCustom(source, procedure); + Assert.Equal(["@REGION"], source.Sent); + RunSync(source, procedure); + Assert.Equal(["@region"], source.Sent); Assert.Equal(1, server.Reads); + } - // The library's own set was shared by the plain run; the user's was not. - NameServer.NameConnection third = server.Connect(); - Run(third, procedure); - Assert.Equal(["@region"], third.Sent); + // The library's command runs first, then the user's on the same connection: the user's + // answers its own names, as its override says. + static void AssertTheUserDoesNotTakeTheLibrarysNames(NameServer server, string procedure) + { + NameServer.NameConnection source = server.Connect(); + + RunSync(source, procedure); + Assert.Equal(["@region"], source.Sent); + Assert.Equal(1, server.Reads); + + RunCustom(source, procedure); + Assert.Equal(["@REGION"], source.Sent); + Assert.Equal(1, server.Reads); + + RunSync(source, procedure); + Assert.Equal(["@region"], source.Sent); Assert.Equal(1, server.Reads); } + // Fills the shared tier to its bound with procedures of another server. + static void FillSharedTier() + { + ClearShared(); + var other = NameServer.Create(); + for (int i = 0; i < Bound; i++) RunSync(other.Connect(), "dbo.fill" + i); + Assert.Equal(Bound, ProcedureParameterNames.Shared.ByProcedure.Count); + } + [Fact] - public static void ACommandTypeOfTheUsersOwn_WhoseNamesWereTakenFirst_DoesNotPoisonTheLibrarysCommands() + public static void UsersCommandFirst_LibraryReadsItsOwn_Unqualified() + => AssertTheLibraryDoesNotTakeTheUsersNames(NameServer.Create(), Unqualified()); + + [Fact] + public static void UsersCommandFirst_LibraryReadsItsOwn_Qualified() + => AssertTheLibraryDoesNotTakeTheUsersNames(NameServer.Create(), Unique()); + + [Fact] + public static void UsersCommandFirst_LibraryReadsItsOwn_QualifiedWhileSharedIsFull() { - var server = NameServer.Create(); - string procedure = Unique(); - NameServer.NameConnection first = server.Connect(); + FillSharedTier(); + try + { + AssertTheLibraryDoesNotTakeTheUsersNames(NameServer.Create(), Unique()); + } + finally + { + ClearShared(); + } + } - Run(first, procedure); // shared now + [Fact] + public static void LibraryCommandFirst_UserKeepsItsOwn_Unqualified() + => AssertTheUserDoesNotTakeTheLibrarysNames(NameServer.Create(), Unqualified()); - NameServer.NameConnection mine = server.Connect(); - new CustomNamesCommand(mine, procedure).AddParam(value: 1, expression: "filter.Region").ExecuteNonQuery(); + [Fact] + public static void LibraryCommandFirst_UserKeepsItsOwn_Qualified() + => AssertTheUserDoesNotTakeTheLibrarysNames(NameServer.Create(), Unique()); - Assert.Equal(["@region"], first.Sent); - Assert.Equal(["@REGION"], mine.Sent); - Assert.Equal(1, server.Reads); + [Fact] + public static void LibraryCommandFirst_UserKeepsItsOwn_QualifiedWhileSharedIsFull() + { + FillSharedTier(); + try + { + AssertTheUserDoesNotTakeTheLibrarysNames(NameServer.Create(), Unique()); + } + finally + { + ClearShared(); + } } + // ---- other servers and databases ---- + [Fact] public static void AnotherServerOrDatabase_HasItsOwnEntry() { @@ -208,24 +319,27 @@ public static void AnotherServerOrDatabase_HasItsOwnEntry() var secondServer = new NameServer(name + "x", "dbA") { Names = ["@Region"] }; string procedure = Unique(); - NameServer.NameConnection a = first.Connect(), b = secondDatabase.Connect(), c = secondServer.Connect(); - Run(a, procedure); - Run(b, procedure); - Run(c, procedure); + NameServer.NameConnection a = first.Connect(), + b = secondDatabase.Connect(), + c = secondServer.Connect(); + RunSync(a, procedure); + RunSync(b, procedure); + RunSync(c, procedure); Assert.Equal(["@region"], a.Sent); Assert.Equal(["@REGION"], b.Sent); Assert.Equal(["@Region"], c.Sent); - // Each is shared on its own: another connection to it reads nothing, and the same server in another case is the same server. - Run(first.Connect(), procedure); - Run(secondDatabase.Connect(), procedure); - Run(secondServer.Connect(), procedure); + // Each is shared on its own: another connection to it reads nothing, and the same + // server in another case is the same server. + RunSync(first.Connect(), procedure); + RunSync(secondDatabase.Connect(), procedure); + RunSync(secondServer.Connect(), procedure); Assert.Equal(1, first.Reads); Assert.Equal(1, secondDatabase.Reads); Assert.Equal(1, secondServer.Reads); var upper = new NameServer(name.ToUpperInvariant(), "DBA") { Names = ["@never"] }; - Run(upper.Connect(), procedure); + RunSync(upper.Connect(), procedure); Assert.Equal(0, upper.Reads); } @@ -238,26 +352,25 @@ public static void PastTheBound_NewSetsGoToTheirConnection_AndNothingIsCleared() try { var server = NameServer.Create(); - const int Bound = 1024; - for (int i = 0; i < Bound; i++) Run(server.Connect(), "dbo.cap" + i); + for (int i = 0; i < Bound; i++) RunSync(server.Connect(), "dbo.cap" + i); Assert.Equal(Bound, server.Reads); // The first 1024 are shared: no connection reads them again. - for (int i = 0; i < Bound; i++) Run(server.Connect(), "dbo.cap" + i); + for (int i = 0; i < Bound; i++) RunSync(server.Connect(), "dbo.cap" + i); Assert.Equal(Bound, server.Reads); // The 1025th is kept by the connection that read it, not shared. NameServer.NameConnection owner = server.Connect(); - Run(owner, "dbo.cap" + Bound); + RunSync(owner, "dbo.cap" + Bound); Assert.Equal(Bound + 1, server.Reads); - Run(owner, "dbo.cap" + Bound); + RunSync(owner, "dbo.cap" + Bound); Assert.Equal(Bound + 1, server.Reads); - Run(server.Connect(), "dbo.cap" + Bound); + RunSync(server.Connect(), "dbo.cap" + Bound); Assert.Equal(Bound + 2, server.Reads); // Nothing was cleared to make room. - for (int i = 0; i < Bound; i++) Run(server.Connect(), "dbo.cap" + i); + for (int i = 0; i < Bound; i++) RunSync(server.Connect(), "dbo.cap" + i); Assert.Equal(Bound + 2, server.Reads); } finally @@ -268,37 +381,35 @@ public static void PastTheBound_NewSetsGoToTheirConnection_AndNothingIsCleared() // ---- forgetting ---- - [Theory] - [InlineData(false)] - [InlineData(true)] - public static async Task ADbExceptionOnACallThatUsedTheSharedSet_RemovesItForEveryone(bool async) + static async Task AssertAFailureRemovesTheSharedSetForEveryone( + Func run) { var server = NameServer.Create(); string procedure = Unique(); - await Run(server.Connect(), procedure, async); + await run(server.Connect(), procedure); Assert.Equal(1, server.Reads); server.Failure = new FakeServerError(); NameServer.NameConnection failing = server.Connect(); - if (async) - { - await Assert.ThrowsAsync(() => RunAsync(failing, procedure)); - } - else - { - Assert.Throws(() => Run(failing, procedure)); - } - + await Assert.ThrowsAsync(() => run(failing, procedure)); Assert.Equal(1, server.Reads); // it used what was shared, and did not read server.Failure = null; - await Run(server.Connect(), procedure, async); + await run(server.Connect(), procedure); Assert.Equal(2, server.Reads); - await Run(server.Connect(), procedure, async); + await run(server.Connect(), procedure); Assert.Equal(2, server.Reads); } + [Fact] + public static Task ADbExceptionOnTheSyncPath_RemovesTheSharedSetForEveryone() + => AssertAFailureRemovesTheSharedSetForEveryone(RunSyncAsTask); + + [Fact] + public static Task ADbExceptionOnTheAsyncPath_RemovesTheSharedSetForEveryone() + => AssertAFailureRemovesTheSharedSetForEveryone(RunAsync); + // ---- queries ---- [Fact] @@ -333,14 +444,12 @@ public static async Task ADbNonQuery_InATransactionOnAFreshConnectionForEachCall } [Fact] - public static async Task ADbNonQuery_ReadsAQualifiedNameOnce_AndAnUnqualifiedNameForEachConnection() + public static async Task ADbNonQuery_ReadsAQualifiedNameOnce_AnUnqualifiedOneForEachConnection() { var server = NameServer.Create(); server.Names = ["@order_id"]; - string qualified = Unique(); - string unqualified = qualified[(qualified.IndexOf('.') + 1)..]; - var shared = DbNonQuery.Procedure(qualified); - var own = DbNonQuery.Procedure(unqualified); + var shared = DbNonQuery.Procedure(Unique()); + var own = DbNonQuery.Procedure(Unqualified()); for (int i = 0; i < 3; i++) { @@ -360,7 +469,9 @@ public static async Task ADbNonQuery_ReadsAQualifiedNameOnce_AndAnUnqualifiedNam // ---- what is in the shared tier ---- static void AssertNothingSharedFor(string procedure) - => Assert.DoesNotContain(ProcedureParameterNames.Shared.ByProcedure.Keys, key => key.Procedure == procedure); + => Assert.DoesNotContain( + ProcedureParameterNames.Shared.ByProcedure.Keys, + key => key.Procedure == procedure); static void ClearShared() => ProcedureParameterNames.Shared.ByProcedure.Clear(); diff --git a/Tests/Open.Database.Extensions.Core.Tests/NameCacheSourceTests.cs b/Tests/Open.Database.Extensions.Core.Tests/NameCacheSourceTests.cs index 481786fe..57c677eb 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/NameCacheSourceTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/NameCacheSourceTests.cs @@ -27,6 +27,10 @@ sealed class Reads { public int Count { get; set; } + // A server name of its own, so what a test shares under a procedure name with a + // schema is not found by another test. + public string DataSource { get; } = NameServer.Unique(); + // What every command run on a connection of this source throws, when set. public Exception? Failure { get; set; } } @@ -42,7 +46,7 @@ sealed class SchemaConnection(Reads reads) : DbConnection public override string Database => "fake"; public override string DataSource - => "fake"; + => reads.DataSource; public override string ServerVersion => "1.0"; public override ConnectionState State @@ -140,9 +144,11 @@ static async Task RunAsync(LegacyCommand command) static string Procedure() => ParameterNameHarness.NewProcedure(); - // A name with a schema is shared by server and database whatever its source is (NameCacheSharedTierTests); one without stays with its source, which - // is what the tests of distinct sources need. - static string Unqualified() => Procedure()["dbo.".Length..]; + // A name with a schema is shared by server and database whatever its source is + // (NameCacheSharedTierTests); one without stays with its source, which is what the + // tests of distinct sources need. + static string Unqualified() + => Procedure()["dbo.".Length..]; // ---- a non-generic factory ---- diff --git a/Tests/Open.Database.Extensions.Core.Tests/OutputMetadataTests.cs b/Tests/Open.Database.Extensions.Core.Tests/OutputMetadataTests.cs index 0700c16f..4dd93f4e 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/OutputMetadataTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/OutputMetadataTests.cs @@ -35,7 +35,9 @@ sealed class MetaConnection : DbConnection [AllowNull] public override string ConnectionString { get; set; } = "meta"; public override string Database => "meta"; - public override string DataSource => "meta"; + // A server name of its own: names of a procedure with a schema are shared by server + // and database. + public override string DataSource { get; } = NameServer.Unique(); public override string ServerVersion => "1.0"; public override ConnectionState State => ConnectionState.Open; public override void ChangeDatabase(string databaseName) { } diff --git a/Tests/Open.Database.Extensions.Core.Tests/TestHelpers/NameServer.cs b/Tests/Open.Database.Extensions.Core.Tests/TestHelpers/NameServer.cs index 9e18372c..8165c247 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/TestHelpers/NameServer.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/TestHelpers/NameServer.cs @@ -5,12 +5,14 @@ namespace Open.Database.Extensions.Tests; #nullable enable /// -/// A fake database server: every connection it makes reports the same DataSource and Database and answers the schema lookup -/// ProcedureParameters with the same parameter names, and counts how often any of them was asked. +/// A fake database server: every connection it makes reports the same DataSource and +/// Database and answers the schema lookup ProcedureParameters with the same +/// parameter names, and counts how often any of them was asked. /// /// -/// A test gives each server a name no other test uses (), because what the library remembers about a procedure of a server and -/// a database is shared by the whole process. +/// A test gives each server a name no other test uses (), because what the +/// library remembers about a procedure of a server and a database is shared by the whole +/// process. /// [ExcludeFromCodeCoverage] internal sealed class NameServer(string? dataSource, string? database = "db") @@ -18,10 +20,12 @@ internal sealed class NameServer(string? dataSource, string? database = "db") static int _counter; /// A server name that no other test in this process uses. - public static string Unique() => "server" + Interlocked.Increment(ref _counter); + public static string Unique() + => "server" + Interlocked.Increment(ref _counter); /// Makes a server with a name of its own. - public static NameServer Create() => new(Unique()); + public static NameServer Create() + => new(Unique()); int _reads; @@ -30,15 +34,17 @@ internal sealed class NameServer(string? dataSource, string? database = "db") public string? Database { get; } = database; /// Gets how many schema lookups the connections of this server answered. - public int Reads => Volatile.Read(ref _reads); + public int Reads + => Volatile.Read(ref _reads); /// Gets or sets the names every lookup answers; none answers an empty table. public string[] Names { get; set; } = ["@region"]; - /// Gets or sets what every command run on a connection of this server throws, when set. + /// Gets or sets what every command run on a new connection throws, when set. public Exception? Failure { get; set; } - public NameConnection Connect() => new(this); + public NameConnection Connect() + => new(this); DataTable Answer() { @@ -48,28 +54,39 @@ DataTable Answer() table.Columns.Add("SPECIFIC_NAME", typeof(string)); table.Columns.Add("ORDINAL_POSITION", typeof(int)); table.Columns.Add("PARAMETER_NAME", typeof(string)); - for (int i = 0; i < Names.Length; i++) table.Rows.Add("dbo", "proc", i + 1, Names[i]); + for (int i = 0; i < Names.Length; i++) + { + table.Rows.Add("dbo", "proc", i + 1, Names[i]); + } + return table; } /// An open connection to a . public sealed class NameConnection(NameServer server) : DbConnection { - readonly DerivedParameterNameTests.RecordingDbCommand _command = new() { Failure = server.Failure }; + readonly DerivedParameterNameTests.RecordingDbCommand _command + = new() { Failure = server.Failure }; /// Gets the names of the parameters the last run sent. - public string[] Sent => [.. _command.Sent.Select(p => p.ParameterName)]; + public string[] Sent + => [.. _command.Sent.Select(p => p.ParameterName)]; [AllowNull] public override string ConnectionString { get; set; } = ""; - public override string Database => server.Database!; - public override string DataSource => server.DataSource!; - public override string ServerVersion => "1.0"; - public override ConnectionState State => ConnectionState.Open; + public override string Database + => server.Database!; + public override string DataSource + => server.DataSource!; + public override string ServerVersion + => "1.0"; + public override ConnectionState State + => ConnectionState.Open; public override void ChangeDatabase(string databaseName) { } public override void Open() { } public override void Close() { } - protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel) => new NameTransaction(this, isolationLevel); + protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel) + => new NameTransaction(this, isolationLevel); protected override DbCommand CreateDbCommand() { @@ -77,13 +94,17 @@ protected override DbCommand CreateDbCommand() return _command; } - public override DataTable GetSchema(string collectionName, string?[] restrictionValues) => server.Answer(); + public override DataTable GetSchema(string collectionName, string?[] restrictionValues) + => server.Answer(); } - sealed class NameTransaction(NameConnection connection, IsolationLevel level) : DbTransaction + sealed class NameTransaction(NameConnection connection, IsolationLevel level) + : DbTransaction { - public override IsolationLevel IsolationLevel => level; - protected override DbConnection DbConnection => connection; + public override IsolationLevel IsolationLevel + => level; + protected override DbConnection DbConnection + => connection; public override void Commit() { } public override void Rollback() { } } diff --git a/docsite/articles/expressive-commands.md b/docsite/articles/expressive-commands.md index e9efd575..8e4e0af1 100644 --- a/docsite/articles/expressive-commands.md +++ b/docsite/articles/expressive-commands.md @@ -161,7 +161,7 @@ The first call to a stored procedure asks the database for the procedure's param **A name with a schema (`dbo.get_author`) is kept once per server and database,** for the life of the process. Every command and query of the library's own types that runs on a `DbConnection` that reports its server (`DataSource`) and its `Database` finds them there, whichever connection, factory, pool or transaction it was made from, so a connection or a factory you create for each call asks the database once, not every time. Up to 1024 procedures are kept this way; past that, new names are kept as described next, and nothing already kept is dropped. -**Everything else is kept with the object your connections come from:** the connection factory, the pool, or the connection itself when you start from one. That is a name without a schema (`get_author`: each login resolves it in its own default schema, so it can be a different procedure for each), an answer of no names (see below), a connection that reports no server or no database or is not a `DbConnection`, and a command class of your own that derives from a library command type. These names go when that object goes, so a factory kept for the life of the application keeps them for that long. Every command made from the same factory or pool shares them, whether you give it the object or a method of it; a function is told apart by the object its method belongs to: methods of one object are one source, lambdas that capture nothing are one source for their class, and a lambda that captures a local variable or a parameter is a new source each time it is created. A pool that is a struct, passed to `ExpressiveCommand(IDbConnectionPool)`, is boxed again for each command and does not share: pass a class. The key has no login or default schema, so two logins to one server and database share a set when they use the same factory. **For these, keep one factory for the application (static or a singleton):** a factory or a connection you create for each scope or call asks the database every time. One factory keeps the names of up to 1024 procedures; past that it starts over. +**Everything else is kept with the object your connections come from:** the connection factory, the pool, or the connection itself when you start from one. That is a name without a schema (`get_author`: each login resolves it in its own default schema, so it can be a different procedure for each), an answer of no names (see below), a connection that reports no server or no database or is not a `DbConnection`, and a command class of your own that derives from a library command type (what it kept is never given to the library's own commands, nor theirs to it). These names go when that object goes, so a factory kept for the life of the application keeps them for that long. Every command made from the same factory or pool shares them, whether you give it the object or a method of it; a function is told apart by the object its method belongs to: methods of one object are one source, lambdas that capture nothing are one source for their class, and a lambda that captures a local variable or a parameter is a new source each time it is created. A pool that is a struct, passed to `ExpressiveCommand(IDbConnectionPool)`, is boxed again for each command and does not share: pass a class. The key has no login or default schema, so two logins to one server and database share a set when they use the same factory. **For these, keep one factory for the application (static or a singleton):** a factory or a connection you create for each scope or call asks the database every time. One factory keeps the names of up to 1024 procedures; past that it starts over. Names are kept per server, database and procedure name, the procedure as you wrote it. From e1318f58e8780412f1e4a8272947788f3cb30978 Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Thu, 3 Dec 2026 15:49:55 -0800 Subject: [PATCH 3/5] Tell kinds of provider apart in the shared parameter-name tier, and document the fall-through after the tier is full Two connection classes can report the same server and database (a test container, a provider behind a proxy), so a set of names shared by those two alone could be handed to the wrong provider. The key of a remembered set now also holds the runtime type of the connection, compared by reference: connections of different kinds of provider never share a set. One key shape serves both the shared entries and a source's own entries. Cost per call: one reference comparison in key equality and one runtime-type hash in the key hash, and a call to GetType on the connection when the key is made; nothing is allocated, and the key keeps only the type itself alive. Also documented, with a code comment and a test that pins it: once the shared tier has been full, a set of the same procedure can sit in a source's own entries beside one shared later. If the shared one is forgotten, the next call of that source can find the older set once, use it and fail, which forgets it too, and the call after that reads the names again. It is rare, loud and heals itself, so it is not guarded. Tests: a fail-first test with two connection classes that report the same server and database (one class shares, the other has its own entry) and a test for the fall-through. The fake server now applies its failure to each command, so a connection made earlier can fail later. Docs: the names section says names are kept per server, database, kind of provider and procedure, and describes the fall-through. Co-Authored-By: Claude Sonnet 5.5 --- Source/Core/DbQueryRunner.cs | 9 ++- Source/Core/ExpressiveCommandBase.cs | 9 ++- Source/Core/ProcedureParameterNames.cs | 46 ++++++++--- .../NameCacheSharedTierCostTests.cs | 4 +- .../NameCacheSharedTierLocalDbTests.cs | 4 +- .../NameCacheSharedTierTests.cs | 78 ++++++++++++++++++- .../TestHelpers/NameServer.cs | 15 +++- docsite/articles/expressive-commands.md | 4 +- 8 files changed, 138 insertions(+), 31 deletions(-) diff --git a/Source/Core/DbQueryRunner.cs b/Source/Core/DbQueryRunner.cs index e2e69e24..18f8e632 100644 --- a/Source/Core/DbQueryRunner.cs +++ b/Source/Core/DbQueryRunner.cs @@ -292,9 +292,14 @@ static object NameCacheOwner(object source, DbConnection connection) /// The key. // The server and the database are part of the key: one connection can be // switched to another database, and one factory can hand out connections to - // different servers. + // different servers. So is the kind of provider: two kinds can report the same + // server and database. static ProcedureKey KeyOf(DbConnection connection, DbQuery definition) - => new(connection.DataSource, connection.Database, definition.CommandText); + => new( + connection.DataSource, + connection.Database, + definition.CommandText, + connection.GetType()); /// /// Finds the real names that the derived parameters are matched to. diff --git a/Source/Core/ExpressiveCommandBase.cs b/Source/Core/ExpressiveCommandBase.cs index c8e3124f..0527bc2c 100644 --- a/Source/Core/ExpressiveCommandBase.cs +++ b/Source/Core/ExpressiveCommandBase.cs @@ -1053,12 +1053,15 @@ TCommand PrepareDerived(TConnection connection, NameSet? names, bool written = f // switched to another database, and one factory can hand out connections to // different servers, where the same procedure name may be a different // procedure. IDbConnection has no server name, so a connection that is not - // a DbConnection contributes none. The key is a struct of the three parts, - // so no string is built. + // a DbConnection contributes none. The kind of provider (the connection's + // runtime type) is part of it too: two kinds can report the same server and + // database. The key is a struct of the four parts, so no string is built. ProcedureKey KeyOf(TConnection connection) => new( (connection as DbConnection)?.DataSource, - connection.Database, Command); + connection.Database, + Command, + connection.GetType()); /// /// Finds the names kept for a procedure: for a command of the library's own diff --git a/Source/Core/ProcedureParameterNames.cs b/Source/Core/ProcedureParameterNames.cs index 6403be24..889e982d 100644 --- a/Source/Core/ProcedureParameterNames.cs +++ b/Source/Core/ProcedureParameterNames.cs @@ -3,18 +3,29 @@ namespace Open.Database.Extensions; /// -/// The server, the database and the procedure a set of names belongs to. +/// The server, the database, the kind of provider and the procedure a set of names belongs to. /// /// /// The server and the database are compared ignoring case, the procedure exactly: a case-sensitive database can hold two procedures that differ only /// in case, and an extra entry for one procedure written two ways costs only a second read. A part that is is the empty string. +/// The kind of provider is the runtime type of the connection, compared by reference: +/// connections of different kinds of provider never share a set, even when they report the +/// same server and database. /// /// The server, or when it is not known. /// The database, or when it is not known. /// The procedure name. +/// The runtime type of the connection, or if none. // A small struct compared part by part, so looking a procedure up builds no string. // StringComparer.GetHashCode(null) throws, and a missing server or database is the same key as an empty one. -readonly struct ProcedureKey(string? server, string? database, string? procedure) : IEquatable +// The type is the one reference a key holds besides its strings, and keeps nothing alive but +// the type itself. One shape for both tiers: a source's own entries cost one more reference +// comparison, and a lookup allocates nothing. +readonly struct ProcedureKey( + string? server, + string? database, + string? procedure, + Type? provider) : IEquatable { /// Gets the server; empty when it is not known. public string Server { get; } = server ?? string.Empty; @@ -22,10 +33,13 @@ readonly struct ProcedureKey(string? server, string? database, string? procedure public string Database { get; } = database ?? string.Empty; /// Gets the procedure name. public string Procedure { get; } = procedure ?? string.Empty; + /// Gets the runtime type of the connection; if none. + public Type? Provider { get; } = provider; /// public bool Equals(ProcedureKey other) => string.Equals(Procedure, other.Procedure, StringComparison.Ordinal) + && ReferenceEquals(Provider, other.Provider) && string.Equals(Database, other.Database, StringComparison.OrdinalIgnoreCase) && string.Equals(Server, other.Server, StringComparison.OrdinalIgnoreCase); @@ -42,6 +56,7 @@ public override int GetHashCode() int hash = comparer.GetHashCode(Server); hash = (hash * 397) ^ comparer.GetHashCode(Database); hash = (hash * 397) ^ StringComparer.Ordinal.GetHashCode(Procedure); + hash = (hash * 397) ^ System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(Provider); return hash; } } @@ -58,15 +73,15 @@ public override int GetHashCode() /// /// /// One kind of entry is kept apart from its source, in : the names of a -/// schema-qualified procedure, as answered for a server and a database, found by every command -/// and query of the library's own types that runs on a that names -/// both. A schema-qualified name is the same procedure for every login of the database, so the -/// answer does not depend on who asked. An unqualified name (the login's default schema picks -/// the procedure), an answer of no names, and a connection that names no server or database -/// stay with their source. The shared entries are never cleared or evicted and nothing expires -/// them: at of them, new sets go to their source, as before. A -/// failure that forgets an entry removes the shared one for everyone, and the next call reads -/// it again. +/// schema-qualified procedure, as answered for a server, a database and a kind of provider (the +/// runtime type of the connection), found by every command and query of the library's own types +/// that runs on a that names both server and database. A +/// schema-qualified name is the same procedure for every login of the database, so the answer +/// does not depend on who asked. An unqualified name (the login's default schema picks the +/// procedure), an answer of no names, and a connection that names no server or database stay +/// with their source. The shared entries are never cleared or evicted and nothing expires them: +/// at of them, new sets go to their source, as before. A failure +/// that forgets an entry removes the shared one for everyone, and the next call reads it again. /// /// /// A command type of the user's own may answer names that are its own (it overrides how they are @@ -129,7 +144,12 @@ public sealed class Entries /// The server, database and procedure. /// The set, or when none is kept. // Per call, beyond Find: two length checks on the key, and one lookup in the shared entries - // (which a key of an unqualified name misses). + // (which a key of an unqualified name misses). When the shared entries were full, the + // set of a qualified name may also sit in the source's entries, and when a slot is + // free again another source may share one beside it. If that shared set is forgotten, + // this falls through to the source's older one: one more call may use it and fail, + // and Forget then removes it too, so the call after reads the names again. Rare, loud + // and self-healing, so it is documented rather than guarded. public static NameSet? FindShared(object source, ProcedureKey key) => CanShare(key) && Shared.ByProcedure.TryGetValue(key, out NameSet? shared) ? shared @@ -261,6 +281,8 @@ public static bool Forget(NameSet? names) if (names?.Home is { } home && home.TryGetTarget(out Entries? entries)) { // Removes the pair only while this very instance is the value (NameSet compares by reference). + // A set of a source's own entries is removed from there only: see FindShared for the + // older set a forgotten shared one can fall through to. ((ICollection>)entries.ByProcedure).Remove(new(names.Key, names)); } diff --git a/Tests/Open.Database.Extensions.Core.Tests/NameCacheSharedTierCostTests.cs b/Tests/Open.Database.Extensions.Core.Tests/NameCacheSharedTierCostTests.cs index 369b2150..0e9b9ae5 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/NameCacheSharedTierCostTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/NameCacheSharedTierCostTests.cs @@ -57,8 +57,8 @@ public static void FindingAKeptSet_SharedOrOfItsSource_AllocatesNothing() { object source = new(); string server = NameServer.Unique(); - var qualified = new ProcedureKey(server, "db", "dbo.find"); - var unqualified = new ProcedureKey(server, "db", "find"); + var qualified = new ProcedureKey(server, "db", "dbo.find", typeof(object)); + var unqualified = new ProcedureKey(server, "db", "find", typeof(object)); NameSet shared = ProcedureParameterNames.RememberShared(source, qualified, ["@a"]); NameSet owned = ProcedureParameterNames.RememberShared(source, unqualified, ["@a"]); NameSet? found = null; diff --git a/Tests/Open.Database.Extensions.Core.Tests/NameCacheSharedTierLocalDbTests.cs b/Tests/Open.Database.Extensions.Core.Tests/NameCacheSharedTierLocalDbTests.cs index 969ee184..cb9b93a8 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/NameCacheSharedTierLocalDbTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/NameCacheSharedTierLocalDbTests.cs @@ -67,8 +67,8 @@ public string AddUser(string name, string defaultSchema) public void AddProcedure(string schema, string parameters, string answer) { Run( - $"create procedure [{schema}].[{Procedure}] {parameters} " + - $"as select '{answer}' as which"); + $"create procedure [{schema}].[{Procedure}] {parameters} " + + $"as select '{answer}' as which"); _drops.Insert(0, $"drop procedure if exists [{schema}].[{Procedure}]"); } diff --git a/Tests/Open.Database.Extensions.Core.Tests/NameCacheSharedTierTests.cs b/Tests/Open.Database.Extensions.Core.Tests/NameCacheSharedTierTests.cs index 5e61399a..713833b4 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/NameCacheSharedTierTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/NameCacheSharedTierTests.cs @@ -201,7 +201,7 @@ public static void ANonDbConnection_SendsTheNameAsWritten_AndSharesNothing() public static void AKeyWithNoServerOrDatabase_IsNeverShared(string server, string database) { string procedure = Unique(); - var key = new ProcedureKey(server, database, procedure); + var key = new ProcedureKey(server, database, procedure, typeof(object)); var source = new object(); NameSet kept = ProcedureParameterNames.RememberShared(source, key, ["@region"]); @@ -319,9 +319,9 @@ public static void AnotherServerOrDatabase_HasItsOwnEntry() var secondServer = new NameServer(name + "x", "dbA") { Names = ["@Region"] }; string procedure = Unique(); - NameServer.NameConnection a = first.Connect(), - b = secondDatabase.Connect(), - c = secondServer.Connect(); + NameServer.NameConnection a = first.Connect(); + NameServer.NameConnection b = secondDatabase.Connect(); + NameServer.NameConnection c = secondServer.Connect(); RunSync(a, procedure); RunSync(b, procedure); RunSync(c, procedure); @@ -343,6 +343,27 @@ public static void AnotherServerOrDatabase_HasItsOwnEntry() Assert.Equal(0, upper.Reads); } + // ---- the kind of provider ---- + + // Two connection classes can report the same server and database (a test container, a + // provider behind a proxy): their answers are not told apart by those, so they are by class. + [Fact] + public static void TwoKindsOfProvider_WithTheSameServerAndDatabase_ShareNothing() + { + var server = NameServer.Create(); + string procedure = Unique(); + + RunSync(server.Connect(), procedure); + RunSync(server.Connect(), procedure); + Assert.Equal(1, server.Reads); // one kind: shared + + RunSync(server.ConnectOtherKind(), procedure); + Assert.Equal(2, server.Reads); // the other kind: its own entry + RunSync(server.ConnectOtherKind(), procedure); + RunSync(server.Connect(), procedure); + Assert.Equal(2, server.Reads); + } + // ---- the bound ---- [Fact] @@ -381,6 +402,55 @@ public static void PastTheBound_NewSetsGoToTheirConnection_AndNothingIsCleared() // ---- forgetting ---- + // Once the shared tier has been full, a set of the same procedure can sit in a source's own + // entries beside one shared later. When the shared one is forgotten, the next call of that + // source finds the older one: it can be stale, and then fails and is forgotten itself. + // Pinned as documented: loud, rare and self-healing. + [Fact] + public static void AForgottenSharedSet_FallsThroughOnceToTheOlderSetOfASource_ThenHeals() + { + FillSharedTier(); + try + { + var server = NameServer.Create(); + string procedure = Unique(); + NameServer.NameConnection older = server.Connect(); + RunSync(older, procedure); // the tier is full: the connection keeps it + Assert.Equal(1, server.Reads); + + // A slot is free again, and another connection shares the procedure. + ProcedureParameterNames.Shared.ByProcedure.TryRemove( + ProcedureParameterNames.Shared.ByProcedure.Keys.First(), + out _); + NameServer.NameConnection newer = server.Connect(); + RunSync(newer, procedure); + Assert.Equal(2, server.Reads); + + // A failure forgets the shared set. + server.Failure = new FakeServerError(); + Assert.Throws(() => RunSync(newer, procedure)); + server.Failure = null; + Assert.Equal(2, server.Reads); + + // The older connection finds its own set once more: no read, and it can fail. + RunSync(older, procedure); + Assert.Equal(2, server.Reads); + server.Failure = new FakeServerError(); + Assert.Throws(() => RunSync(older, procedure)); + server.Failure = null; + + // It was forgotten too: the next call reads the names again. + RunSync(older, procedure); + Assert.Equal(3, server.Reads); + RunSync(older, procedure); + Assert.Equal(3, server.Reads); + } + finally + { + ClearShared(); + } + } + static async Task AssertAFailureRemovesTheSharedSetForEveryone( Func run) { diff --git a/Tests/Open.Database.Extensions.Core.Tests/TestHelpers/NameServer.cs b/Tests/Open.Database.Extensions.Core.Tests/TestHelpers/NameServer.cs index 8165c247..9fd020fc 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/TestHelpers/NameServer.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/TestHelpers/NameServer.cs @@ -40,12 +40,16 @@ public int Reads /// Gets or sets the names every lookup answers; none answers an empty table. public string[] Names { get; set; } = ["@region"]; - /// Gets or sets what every command run on a new connection throws, when set. + /// Gets or sets what every command run on a connection throws, when set. public Exception? Failure { get; set; } public NameConnection Connect() => new(this); + /// Makes a connection of another kind of provider to the same server and database. + public NameConnection ConnectOtherKind() + => new OtherKindConnection(this); + DataTable Answer() { Interlocked.Increment(ref _reads); @@ -63,10 +67,9 @@ DataTable Answer() } /// An open connection to a . - public sealed class NameConnection(NameServer server) : DbConnection + public class NameConnection(NameServer server) : DbConnection { - readonly DerivedParameterNameTests.RecordingDbCommand _command - = new() { Failure = server.Failure }; + readonly DerivedParameterNameTests.RecordingDbCommand _command = new(); /// Gets the names of the parameters the last run sent. public string[] Sent @@ -91,6 +94,7 @@ protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLeve protected override DbCommand CreateDbCommand() { _command.Parameters.Clear(); // the fake hands out one command + _command.Failure = server.Failure; return _command; } @@ -98,6 +102,9 @@ public override DataTable GetSchema(string collectionName, string?[] restriction => server.Answer(); } + // The same server and database, reported by another connection class. + sealed class OtherKindConnection(NameServer server) : NameConnection(server); + sealed class NameTransaction(NameConnection connection, IsolationLevel level) : DbTransaction { diff --git a/docsite/articles/expressive-commands.md b/docsite/articles/expressive-commands.md index 8e4e0af1..69d26168 100644 --- a/docsite/articles/expressive-commands.md +++ b/docsite/articles/expressive-commands.md @@ -159,11 +159,11 @@ An argument that is not a plain member chain (a call, an index, an operator, a l The first call to a stored procedure asks the database for the procedure's parameter names. Later calls reuse them. Where they are kept depends on the name you give the procedure. -**A name with a schema (`dbo.get_author`) is kept once per server and database,** for the life of the process. Every command and query of the library's own types that runs on a `DbConnection` that reports its server (`DataSource`) and its `Database` finds them there, whichever connection, factory, pool or transaction it was made from, so a connection or a factory you create for each call asks the database once, not every time. Up to 1024 procedures are kept this way; past that, new names are kept as described next, and nothing already kept is dropped. +**A name with a schema (`dbo.get_author`) is kept once per server and database,** for the life of the process, for connections of one kind of provider (one connection class): two providers that report the same server and database do not share. Every command and query of the library's own types that runs on a `DbConnection` that reports its server (`DataSource`) and its `Database` finds them there, whichever connection, factory, pool or transaction it was made from, so a connection or a factory you create for each call asks the database once, not every time. Up to 1024 procedures are kept this way; past that, new names are kept as described next, and nothing already kept is dropped. Once that limit has been reached, a shared set that is forgotten (see below) can be replaced for one more call by an older set of the same procedure that a source kept: that call may use it and fail, and the names are read again after it. **Everything else is kept with the object your connections come from:** the connection factory, the pool, or the connection itself when you start from one. That is a name without a schema (`get_author`: each login resolves it in its own default schema, so it can be a different procedure for each), an answer of no names (see below), a connection that reports no server or no database or is not a `DbConnection`, and a command class of your own that derives from a library command type (what it kept is never given to the library's own commands, nor theirs to it). These names go when that object goes, so a factory kept for the life of the application keeps them for that long. Every command made from the same factory or pool shares them, whether you give it the object or a method of it; a function is told apart by the object its method belongs to: methods of one object are one source, lambdas that capture nothing are one source for their class, and a lambda that captures a local variable or a parameter is a new source each time it is created. A pool that is a struct, passed to `ExpressiveCommand(IDbConnectionPool)`, is boxed again for each command and does not share: pass a class. The key has no login or default schema, so two logins to one server and database share a set when they use the same factory. **For these, keep one factory for the application (static or a singleton):** a factory or a connection you create for each scope or call asks the database every time. One factory keeps the names of up to 1024 procedures; past that it starts over. -Names are kept per server, database and procedure name, the procedure as you wrote it. +Names are kept per server, database, kind of provider and procedure name, the procedure as you wrote it. A call forgets the names when it cannot be built (for example, an argument matches no parameter, or two match one), or when a `DbException` is thrown once it is built: the database rejecting it, a command timeout, an error while the rows are read, or one from your own code inside the call. The next call reads them again, so an `AddParam(value)` argument the kept names lack fails once and the call after it uses the new names. The failed call is not retried, and its exception reaches you unchanged. Names kept for the whole process are forgotten for every connection: the next call from any of them reads them again. A cancellation reported as `OperationCanceledException`, and failures in reading or converting a value, keep them; SQL Server reports a cancel while a command runs as `SqlException`, which forgets them. So when a parameter is renamed, removed or becomes required while the application runs, calls using the old names fail, with `InvalidOperationException` before they are sent (an argument that matches nothing) or with the database's own error, and calls after a failure use the new names. From f254f8b36f8451318f93559d63ab24f3670fcc7c Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Fri, 4 Dec 2026 05:35:47 -0800 Subject: [PATCH 4/5] Use the library's own names in the shared-tier tests, and one text for each fact The tests of the shared name tier repeated text that already has one home. The fake servers and the source tests built the ProcedureParameters schema table with their own copies of its name and column words; they now take the table from the existing test helper, which takes them from the library's constants. The LocalDB test reads the schema collection and its columns by those constants too. The name of the test collection is one constant used by its definition and every test class in it, and the shared tier tests reuse the existing server-error test type instead of declaring a second one with the same message. Where a chain of calls sat on one line it now has the first call on the receiver's line and one call per line after it. Tests only: no run-time change, no public API change, no message text changed. Co-Authored-By: Claude Sonnet 5.5 --- .../NameCacheSharedTierCostTests.cs | 2 +- .../NameCacheSharedTierLocalDbTests.cs | 8 ++-- .../NameCacheSharedTierTests.cs | 45 ++++++++++++------- .../NameCacheSourceTests.cs | 6 +-- .../TestHelpers/NameServer.cs | 6 +-- 5 files changed, 35 insertions(+), 32 deletions(-) diff --git a/Tests/Open.Database.Extensions.Core.Tests/NameCacheSharedTierCostTests.cs b/Tests/Open.Database.Extensions.Core.Tests/NameCacheSharedTierCostTests.cs index 0e9b9ae5..1d51832d 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/NameCacheSharedTierCostTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/NameCacheSharedTierCostTests.cs @@ -6,7 +6,7 @@ namespace Open.Database.Extensions.Tests; // What a repeat run costs when the names come from the shared tier. They run in the collection // of the shared tier (see NameCacheSharedTierTests), where no other test touches it meanwhile. -[Collection("Shared name tier")] +[Collection(SharedNameTierCollection.Name)] [ExcludeFromCodeCoverage] public static class NameCacheSharedTierCostTests { diff --git a/Tests/Open.Database.Extensions.Core.Tests/NameCacheSharedTierLocalDbTests.cs b/Tests/Open.Database.Extensions.Core.Tests/NameCacheSharedTierLocalDbTests.cs index cb9b93a8..05b1e6b8 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/NameCacheSharedTierLocalDbTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/NameCacheSharedTierLocalDbTests.cs @@ -13,7 +13,7 @@ namespace Open.Database.Extensions.Tests; // user's permissions, whichever way the user got in. In the collection of the shared tier, // which runs alone, so its DDL meets no other. Skipped without LocalDB (see LocalDbFixture). [ExcludeFromCodeCoverage] -[Collection("Shared name tier")] +[Collection(SharedNameTierCollection.Name)] public static class NameCacheSharedTierLocalDbTests { static CancellationToken Token @@ -169,7 +169,7 @@ public static async Task ALoginWhoseOnlyRightIsExecute_SeesTheParametersInTheSch await using SqlConnection connection = await OpenAs(user); using DataTable table = connection.GetSchema( - "ProcedureParameters", + ProcedureSchemaNames.Collection, [null, scene.Shared, scene.Procedure, null]); // SQL Server reports both parameters to a user whose only right is EXECUTE. @@ -178,8 +178,8 @@ public static async Task ALoginWhoseOnlyRightIsExecute_SeesTheParametersInTheSch ["@region", "@other"], table.Rows.Cast() .OrderBy(row => Convert.ToInt32( - row["ORDINAL_POSITION"], + row[ProcedureSchemaNames.OrdinalPositionColumn], System.Globalization.CultureInfo.InvariantCulture)) - .Select(row => (string)row["PARAMETER_NAME"])); + .Select(row => (string)row[ProcedureSchemaNames.ParameterNameColumn])); } } diff --git a/Tests/Open.Database.Extensions.Core.Tests/NameCacheSharedTierTests.cs b/Tests/Open.Database.Extensions.Core.Tests/NameCacheSharedTierTests.cs index 713833b4..6f3cc8d7 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/NameCacheSharedTierTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/NameCacheSharedTierTests.cs @@ -17,10 +17,15 @@ namespace Open.Database.Extensions.Tests; // server name of its own (NameServer.Unique), so what another test shared is never found. // Tests in other collections that use a qualified name on a fake give it a server name of its // own too. -[CollectionDefinition("Shared name tier", DisableParallelization = true)] -public sealed class SharedNameTierCollection; +[CollectionDefinition(Name, DisableParallelization = true)] +public sealed class SharedNameTierCollection +{ + /// The name of the collection. + public const string Name + = "Shared name tier"; +} -[Collection("Shared name tier")] +[Collection(SharedNameTierCollection.Name)] [ExcludeFromCodeCoverage] public static class NameCacheSharedTierTests { @@ -32,9 +37,6 @@ static CancellationToken Token // The most procedures the shared tier holds. const int Bound = 1024; - sealed class FakeServerError(string message = "rejected by the server") - : DbException(message); - // What a user's own command type answers for the parameter names of any procedure: the // same argument matches it as matches the server's names, under another spelling. sealed class CustomNamesCommand(DbConnection connection, string procedure) @@ -427,16 +429,16 @@ public static void AForgottenSharedSet_FallsThroughOnceToTheOlderSetOfASource_Th Assert.Equal(2, server.Reads); // A failure forgets the shared set. - server.Failure = new FakeServerError(); - Assert.Throws(() => RunSync(newer, procedure)); + server.Failure = new DerivedParameterNameTests.ServerError(); + Assert.Throws(() => RunSync(newer, procedure)); server.Failure = null; Assert.Equal(2, server.Reads); // The older connection finds its own set once more: no read, and it can fail. RunSync(older, procedure); Assert.Equal(2, server.Reads); - server.Failure = new FakeServerError(); - Assert.Throws(() => RunSync(older, procedure)); + server.Failure = new DerivedParameterNameTests.ServerError(); + Assert.Throws(() => RunSync(older, procedure)); server.Failure = null; // It was forgotten too: the next call reads the names again. @@ -460,9 +462,9 @@ static async Task AssertAFailureRemovesTheSharedSetForEveryone( await run(server.Connect(), procedure); Assert.Equal(1, server.Reads); - server.Failure = new FakeServerError(); + server.Failure = new DerivedParameterNameTests.ServerError(); NameServer.NameConnection failing = server.Connect(); - await Assert.ThrowsAsync(() => run(failing, procedure)); + await Assert.ThrowsAsync(() => run(failing, procedure)); Assert.Equal(1, server.Reads); // it used what was shared, and did not read server.Failure = null; @@ -491,7 +493,9 @@ public static async Task ADbNonQuery_OnAFreshConnectionForEachCall_ReadsOnce() for (int i = 0; i < 3; i++) { - await write.Using(server.Connect()).AddParam(OrderId).ExecuteNonQueryAsync(Token); + await write.Using(server.Connect()) + .AddParam(OrderId) + .ExecuteNonQueryAsync(Token); } Assert.Equal(1, server.Reads); @@ -506,8 +510,11 @@ public static async Task ADbNonQuery_InATransactionOnAFreshConnectionForEachCall for (int i = 0; i < 3; i++) { - using DbTransaction transaction = server.Connect().BeginTransaction(); - await write.Using(transaction).AddParam(OrderId).ExecuteNonQueryAsync(Token); + NameServer.NameConnection connection = server.Connect(); + using DbTransaction transaction = connection.BeginTransaction(); + await write.Using(transaction) + .AddParam(OrderId) + .ExecuteNonQueryAsync(Token); } Assert.Equal(1, server.Reads); @@ -523,14 +530,18 @@ public static async Task ADbNonQuery_ReadsAQualifiedNameOnce_AnUnqualifiedOneFor for (int i = 0; i < 3; i++) { - await shared.Using(server.Connect()).AddParam(OrderId).ExecuteNonQueryAsync(Token); + await shared.Using(server.Connect()) + .AddParam(OrderId) + .ExecuteNonQueryAsync(Token); } Assert.Equal(1, server.Reads); for (int i = 0; i < 3; i++) { - await own.Using(server.Connect()).AddParam(OrderId).ExecuteNonQueryAsync(Token); + await own.Using(server.Connect()) + .AddParam(OrderId) + .ExecuteNonQueryAsync(Token); } Assert.Equal(4, server.Reads); diff --git a/Tests/Open.Database.Extensions.Core.Tests/NameCacheSourceTests.cs b/Tests/Open.Database.Extensions.Core.Tests/NameCacheSourceTests.cs index 57c677eb..ab5ad086 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/NameCacheSourceTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/NameCacheSourceTests.cs @@ -62,11 +62,7 @@ protected override DbCommand CreateDbCommand() public override DataTable GetSchema(string collectionName, string?[] restrictionValues) { reads.Count++; - var table = new DataTable("ProcedureParameters"); - table.Columns.Add("SPECIFIC_SCHEMA", typeof(string)); - table.Columns.Add("SPECIFIC_NAME", typeof(string)); - table.Columns.Add("ORDINAL_POSITION", typeof(int)); - table.Columns.Add("PARAMETER_NAME", typeof(string)); + DataTable table = ProcedureParametersTable.Create(); table.Rows.Add("dbo", "proc", 1, "@region"); return table; } diff --git a/Tests/Open.Database.Extensions.Core.Tests/TestHelpers/NameServer.cs b/Tests/Open.Database.Extensions.Core.Tests/TestHelpers/NameServer.cs index 9fd020fc..22561982 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/TestHelpers/NameServer.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/TestHelpers/NameServer.cs @@ -53,11 +53,7 @@ public NameConnection ConnectOtherKind() DataTable Answer() { Interlocked.Increment(ref _reads); - var table = new DataTable("ProcedureParameters"); - table.Columns.Add("SPECIFIC_SCHEMA", typeof(string)); - table.Columns.Add("SPECIFIC_NAME", typeof(string)); - table.Columns.Add("ORDINAL_POSITION", typeof(int)); - table.Columns.Add("PARAMETER_NAME", typeof(string)); + DataTable table = ProcedureParametersTable.Create(); for (int i = 0; i < Names.Length; i++) { table.Rows.Add("dbo", "proc", i + 1, Names[i]); From 86a7b967762aaaa7d941de52d0bdc56b45b3e42e Mon Sep 17 00:00:00 2001 From: electricessence <5899455+electricessence@users.noreply.github.com> Date: Fri, 4 Dec 2026 06:17:13 -0800 Subject: [PATCH 5/5] Skip the shared-tier probe for a name with no dot, and fix the review findings A procedure name with no '.' cannot be schema-qualified, so it is never in the shared entries. FindShared now skips the shared probe for it. Cost per call: one scan of the procedure text for a dot (a short span search, no allocation) in place of a four-part hash and a table lookup for an unqualified name; a name with a dot probes as before, so bracketed names such as [dbo].[p] are still shared. Which names are shared does not change. Also: - Docs: the shared set also holds the parameter modes and scales the output-parameter check reads, read by whichever login needs them first and kept for every sharer until the set is forgotten. The release note says so in one sentence. - XML docs and comments on where names are kept now give every condition (schema, a DbConnection that reports server and database, the library's own command types). - The MSSqlClient README no longer says names are read once per connection factory: a schema-qualified name is kept per server and database, an unqualified one per factory. The article's overview sentence says the same. - The comments on the procedure key and the shared table say the static table keeps the provider type for the life of the process. - The shared-tier cost test creates a connection for each call, so it fails without the shared tier. The LocalDB test scene drops what it created if its constructor throws. A test comment about server names on fakes is now accurate. The tests read the bound from the library's own constant, which is now public. - Key construction and a few long comment lines are regrouped and wrapped. Co-Authored-By: Claude Sonnet 5.5 --- Source/Core/DbQuery.cs | 6 +- Source/Core/DbQueryRunner.cs | 9 +- Source/Core/ExpressiveCommandBase.cs | 18 ++- Source/Core/ProcedureParameterNames.cs | 138 +++++++++++------- Source/MSSqlClient/README.md | 2 +- .../NameCacheSharedTierCostTests.cs | 9 +- .../NameCacheSharedTierLocalDbTests.cs | 15 +- .../NameCacheSharedTierTests.cs | 24 ++- docsite/articles/expressive-commands.md | 3 +- docsite/articles/release-notes.md | 2 +- 10 files changed, 144 insertions(+), 82 deletions(-) diff --git a/Source/Core/DbQuery.cs b/Source/Core/DbQuery.cs index a8736224..ccb50f72 100644 --- a/Source/Core/DbQuery.cs +++ b/Source/Core/DbQuery.cs @@ -72,9 +72,9 @@ internal DbQuery WithOutput(OutputLayout layout) /// // A definition is a static field, so a call that derives names scans // nothing. A procedure's names are remembered per server and - // database when its name has a schema, else per source - // (ProcedureParameterNames). A set with no names means "not known": each - // argument is sent as written. + // database when its name has a schema and the connection reports + // both, else per source (ProcedureParameterNames). A set with no + // names means "not known": each argument is sent as written. internal NameSet? TextNames { get; } /// diff --git a/Source/Core/DbQueryRunner.cs b/Source/Core/DbQueryRunner.cs index 18f8e632..9e25809d 100644 --- a/Source/Core/DbQueryRunner.cs +++ b/Source/Core/DbQueryRunner.cs @@ -296,10 +296,8 @@ static object NameCacheOwner(object source, DbConnection connection) // server and database. static ProcedureKey KeyOf(DbConnection connection, DbQuery definition) => new( - connection.DataSource, - connection.Database, - definition.CommandText, - connection.GetType()); + connection.DataSource, connection.Database, + definition.CommandText, connection.GetType()); /// /// Finds the real names that the derived parameters are matched to. @@ -308,7 +306,8 @@ static ProcedureKey KeyOf(DbConnection connection, DbQuery definition) /// A text definition has the @name markers it found when it was made; /// a procedure's names are read once and kept until a call that used them /// cannot be built or the database rejects it: once per server and database - /// for a schema-qualified name, else once per source. + /// for a schema-qualified name on a connection that reports both, else once + /// per source. /// /// The query definition. /// The connection, transaction, pool or factory. diff --git a/Source/Core/ExpressiveCommandBase.cs b/Source/Core/ExpressiveCommandBase.cs index 0527bc2c..8d99c587 100644 --- a/Source/Core/ExpressiveCommandBase.cs +++ b/Source/Core/ExpressiveCommandBase.cs @@ -524,9 +524,11 @@ public TThis AddParam(string name, string? value) /// /// /// A stored procedure's names are read once per server and database when its name has a - /// schema (dbo.get_author) and this is one of the library's own command types, else - /// once per connection factory, pool or connection; and again after a call that cannot be - /// built (other than by cancellation) or that the database rejects. + /// schema (dbo.get_author), the connection is a that + /// reports its server and its database, and this is one of the library's own command + /// types; otherwise once per connection factory, pool or connection. They are read again + /// after a call that cannot be built (other than by cancellation) or that the database + /// rejects. /// /// /// Where the real names are not available (a text command with no @@ -1058,10 +1060,8 @@ TCommand PrepareDerived(TConnection connection, NameSet? names, bool written = f // database. The key is a struct of the four parts, so no string is built. ProcedureKey KeyOf(TConnection connection) => new( - (connection as DbConnection)?.DataSource, - connection.Database, - Command, - connection.GetType()); + (connection as DbConnection)?.DataSource, connection.Database, + Command, connection.GetType()); /// /// Finds the names kept for a procedure: for a command of the library's own @@ -1083,7 +1083,9 @@ ProcedureKey KeyOf(TConnection connection) /// Keeps the names a lookup answered, where finds them. /// /// The key made by . - /// The names the provider reported; none when it reported none. + /// + /// The names the provider reported; none when it reported none. + /// /// The set kept for the procedure. NameSet RememberNames(ProcedureKey key, ImmutableArray names) => IsLibraryCommand diff --git a/Source/Core/ProcedureParameterNames.cs b/Source/Core/ProcedureParameterNames.cs index 889e982d..c20d9894 100644 --- a/Source/Core/ProcedureParameterNames.cs +++ b/Source/Core/ProcedureParameterNames.cs @@ -3,24 +3,28 @@ namespace Open.Database.Extensions; /// -/// The server, the database, the kind of provider and the procedure a set of names belongs to. +/// The server, the database, the kind of provider and the procedure a set of names belongs +/// to. /// /// /// The server and the database are compared ignoring case, the procedure exactly: a case-sensitive database can hold two procedures that differ only /// in case, and an extra entry for one procedure written two ways costs only a second read. A part that is is the empty string. /// The kind of provider is the runtime type of the connection, compared by reference: -/// connections of different kinds of provider never share a set, even when they report the -/// same server and database. +/// connections of different kinds of provider never share a set, even when they report +/// the same server and database. /// /// The server, or when it is not known. /// The database, or when it is not known. /// The procedure name. -/// The runtime type of the connection, or if none. +/// +/// The runtime type of the connection, or if none. +/// // A small struct compared part by part, so looking a procedure up builds no string. // StringComparer.GetHashCode(null) throws, and a missing server or database is the same key as an empty one. -// The type is the one reference a key holds besides its strings, and keeps nothing alive but -// the type itself. One shape for both tiers: a source's own entries cost one more reference -// comparison, and a lookup allocates nothing. +// The type is the one reference a key holds besides its strings. The shared table is static +// and never cleared, so it keeps that type alive for the life of the process. One shape for +// both tiers: a source's own entries cost one more reference comparison, and a lookup +// allocates nothing. readonly struct ProcedureKey( string? server, string? database, @@ -33,7 +37,9 @@ readonly struct ProcedureKey( public string Database { get; } = database ?? string.Empty; /// Gets the procedure name. public string Procedure { get; } = procedure ?? string.Empty; - /// Gets the runtime type of the connection; if none. + /// + /// Gets the runtime type of the connection; if none. + /// public Type? Provider { get; } = provider; /// @@ -56,7 +62,8 @@ public override int GetHashCode() int hash = comparer.GetHashCode(Server); hash = (hash * 397) ^ comparer.GetHashCode(Database); hash = (hash * 397) ^ StringComparer.Ordinal.GetHashCode(Procedure); - hash = (hash * 397) ^ System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(Provider); + hash = (hash * 397) + ^ System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(Provider); return hash; } } @@ -72,21 +79,23 @@ public override int GetHashCode() /// An entry is a : the names the database reported (none, when it reports none) and the real name each argument has matched. /// /// -/// One kind of entry is kept apart from its source, in : the names of a -/// schema-qualified procedure, as answered for a server, a database and a kind of provider (the -/// runtime type of the connection), found by every command and query of the library's own types -/// that runs on a that names both server and database. A -/// schema-qualified name is the same procedure for every login of the database, so the answer -/// does not depend on who asked. An unqualified name (the login's default schema picks the -/// procedure), an answer of no names, and a connection that names no server or database stay -/// with their source. The shared entries are never cleared or evicted and nothing expires them: -/// at of them, new sets go to their source, as before. A failure -/// that forgets an entry removes the shared one for everyone, and the next call reads it again. +/// One kind of entry is kept apart from its source, in : the names of +/// a schema-qualified procedure, as answered for a server, a database and a kind of +/// provider (the runtime type of the connection), found by every command and query of the +/// library's own types that runs on a that names both server and +/// database. A schema-qualified name is the same procedure for every login of the +/// database, so the answer does not depend on who asked. An unqualified name (the login's +/// default schema picks the procedure), an answer of no names, and a connection that names +/// no server or database stay with their source. The shared entries are never cleared or +/// evicted and nothing expires them: at of them, new sets go to +/// their source, as before. A failure that forgets an entry removes the shared one for +/// everyone, and the next call reads it again. /// /// -/// A command type of the user's own may answer names that are its own (it overrides how they are -/// read), so what it remembers is kept in a table of its own for each source, apart from what the -/// library's own types keep there: neither is ever given to the other, and none of it is shared. +/// A command type of the user's own may answer names that are its own (it overrides how +/// they are read), so what it remembers is kept in a table of its own for each source, +/// apart from what the library's own types keep there: neither is ever given to the other, +/// and none of it is shared. /// /// /// Which failures forget an entry, the one rule for every path: a call that fails while it is being built forgets, unless it was canceled; @@ -98,13 +107,13 @@ public override int GetHashCode() static class ProcedureParameterNames { /// - /// How many procedures one source keeps; past it they are all dropped and read again as - /// they are called. The shared entries hold at most as many, and past it new sets go to - /// their source. + /// How many procedures one source keeps; past it they are all dropped and read again + /// as they are called. The shared entries hold at most as many, and past it new sets go + /// to their source. /// // A memory cap, for procedure names built at run time and for many databases behind one factory. A procedure with five parameters takes about // 1.2 KB with its matches (measured on .NET 11, x64), so a full source holds about 1.2 MB. - const int MaxProcedures = 1024; + public const int MaxProcedures = 1024; /// The entries of one source. public sealed class Entries @@ -132,29 +141,46 @@ public sealed class Entries /// The entries shared by every source: schema-qualified procedures of a server and a /// database. /// - // Held for the life of the process, so the weak reference every entry holds back to it never - // goes: Forget works as for a source's entries. + // Held for the life of the process and never cleared, so the weak reference every entry + // holds back to it never goes: Forget works as for a source's entries. The keys' + // provider types are kept alive with it. public static readonly Entries Shared = new(); /// - /// Gets the kept names of a procedure for a command of the library's own type, or for a - /// query: the shared entry first, then the source's. + /// Gets the kept names of a procedure for a command of the library's own type, or for + /// a query: the shared entry first, then the source's. /// /// The object commands take their connections from. /// The server, database and procedure. /// The set, or when none is kept. - // Per call, beyond Find: two length checks on the key, and one lookup in the shared entries - // (which a key of an unqualified name misses). When the shared entries were full, the - // set of a qualified name may also sit in the source's entries, and when a slot is - // free again another source may share one beside it. If that shared set is forgotten, - // this falls through to the source's older one: one more call may use it and fail, - // and Forget then removes it too, so the call after reads the names again. Rare, loud - // and self-healing, so it is documented rather than guarded. + // Per call, beyond Find: two length checks on the key and a scan of the procedure text + // for a dot, and, only when it holds one, a lookup in the shared entries. When the + // shared entries were full, the set of a qualified name may also sit in the source's + // entries, and when a slot is free again another source may share one beside it. If + // that shared set is forgotten, this falls through to the source's older one: one more + // call may use it and fail, and Forget then removes it too, so the call after reads the + // names again. Rare, loud and self-healing, so it is documented rather than guarded. public static NameSet? FindShared(object source, ProcedureKey key) - => CanShare(key) && Shared.ByProcedure.TryGetValue(key, out NameSet? shared) + => MayBeShared(key) && Shared.ByProcedure.TryGetValue(key, out NameSet? shared) ? shared : Find(source, key); + /// + /// Gets whether a key can hold a shared set, so a lookup can skip the shared entries + /// when it cannot. + /// + /// The server, database and procedure. + /// + /// if the key names a server and a database and its procedure + /// text holds a dot; otherwise, . + /// + // Only a schema-qualified name is shared, and a qualified name holds a dot (a bracketed + // "[dbo].[p]" does too), so a text without one is never in the shared entries. A dot + // that does not qualify just misses there, as before. + [SuppressMessage("Usage", "CA2249", Justification = "string.Contains(char) does not exist on netstandard2.0.")] + static bool MayBeShared(ProcedureKey key) + => CanShare(key) && key.Procedure.IndexOf('.') >= 0; + /// /// Gets whether a key names a server and a database: only then is its answer shared. /// @@ -162,8 +188,8 @@ public sealed class Entries /// /// if the key names both; otherwise, . /// - // A connection that is not a DbConnection has no server name, and one that does not know its - // database reports none: neither is told apart from another. + // A connection that is not a DbConnection has no server name, and one that does not know + // its database reports none: neither is told apart from another. static bool CanShare(ProcedureKey key) => key.Server.Length != 0 && key.Database.Length != 0; @@ -206,7 +232,9 @@ static bool CanShare(ProcedureKey key) static object OwnerOf(object source) => source is IConnectionIdentity identity ? identity.Identity : source; - /// Keeps what the lookup answered, for a command of the library's own type. + /// + /// Keeps what the lookup answered, for a command of the library's own type. + /// /// The object commands take their connections from. /// The server, database and procedure the names belong to. /// The names as the database reported them; empty or the default array when it reported none. @@ -214,10 +242,14 @@ static object OwnerOf(object source) public static NameSet Remember(object source, ProcedureKey key, ImmutableArray names) => RememberIn(Sources, source, key, names); - /// Keeps what the lookup answered, for a command type of the user's own. + /// + /// Keeps what the lookup answered, for a command type of the user's own. + /// /// The object commands take their connections from. /// The server, database and procedure the names belong to. - /// The names the database reported; none when it reported none. + /// + /// The names the database reported; none when it reported none. + /// /// The set kept for the procedure: this one, or the one kept first. public static NameSet RememberUser( object source, @@ -238,18 +270,20 @@ static NameSet RememberIn( } /// - /// Keeps what the lookup answered, for a command of the library's own type or for a query: - /// shared when it can be, else with its source. + /// Keeps what the lookup answered, for a command of the library's own type or for a + /// query: shared when it can be, else with its source. /// /// The object commands take their connections from. /// The server, database and procedure the names belong to. - /// The names the database reported; none when it reported none. + /// + /// The names the database reported; none when it reported none. + /// /// The set kept for the procedure: this one, or the one kept first. // Shared only when the answer holds names, the key names a server and a database, the - // procedure name has a schema, and the shared entries have room. The name is parsed here, - // after the round trip, and never on a lookup. The room is checked without a lock, so calls - // that race may overshoot the bound by a few sets: the bound is a memory cap, not an exact - // count. + // procedure name has a schema, and the shared entries have room. The name is parsed + // here, after the round trip, and never on a lookup. The room is checked without a lock, + // so calls that race may overshoot the bound by a few sets: the bound is a memory cap, + // not an exact count. public static NameSet RememberShared( object source, ProcedureKey key, @@ -281,8 +315,8 @@ public static bool Forget(NameSet? names) if (names?.Home is { } home && home.TryGetTarget(out Entries? entries)) { // Removes the pair only while this very instance is the value (NameSet compares by reference). - // A set of a source's own entries is removed from there only: see FindShared for the - // older set a forgotten shared one can fall through to. + // A set of a source's own entries is removed from there only: see FindShared for + // the older set a forgotten shared one can fall through to. ((ICollection>)entries.ByProcedure).Remove(new(names.Key, names)); } diff --git a/Source/MSSqlClient/README.md b/Source/MSSqlClient/README.md index 80312062..8b3ff1f8 100644 --- a/Source/MSSqlClient/README.md +++ b/Source/MSSqlClient/README.md @@ -47,7 +47,7 @@ posts = await connectionFactory .ToArrayAsync(); ``` -Parameter names are read once per connection factory, and again after a call that cannot be built or that the database rejects (keep one factory: a connection or factory you create for each call reads them for every command). The return value of a procedure is readable with `ExecuteReturn()`; output parameters are not set on the chain: read them with `ExecuteOutputAsync`, or use the raw extensions inside `ExecuteAsync(command => ...)`. See [Expressive commands](https://open-net-libraries.github.io/Open.Database.Extensions/articles/expressive-commands.html) for the rules and limits. +Parameter names are read once, and again after a call that cannot be built or that the database rejects. A name with a schema (`[dbo].[SearchPosts]`) is kept per server and database, whichever connection or factory runs it; a name without one is kept per connection factory, so keep one factory for those (a connection or factory you create for each call reads them for every command). The return value of a procedure is readable with `ExecuteReturn()`; output parameters are not set on the chain: read them with `ExecuteOutputAsync`, or use the raw extensions inside `ExecuteAsync(command => ...)`. See [Expressive commands](https://open-net-libraries.github.io/Open.Database.Extensions/articles/expressive-commands.html) for the rules and limits. ## The packages diff --git a/Tests/Open.Database.Extensions.Core.Tests/NameCacheSharedTierCostTests.cs b/Tests/Open.Database.Extensions.Core.Tests/NameCacheSharedTierCostTests.cs index 1d51832d..91563140 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/NameCacheSharedTierCostTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/NameCacheSharedTierCostTests.cs @@ -20,20 +20,23 @@ public static void StoredProcedure_ASharedSet_DerivedCostsNoMoreThanExplicit() { Names = ["@order_id", "@customer_id", "@start_date"], }; - NameServer.NameConnection connection = server.Connect(); string procedure = ParameterNameHarness.NewProcedure(); const int orderId = 5, customerId = 7; var startDate = new DateTime(2026, 1, 2); + // Each run has a connection of its own, so the names can only come from the shared set. + ExpressiveDbCommand NewCommand() + => new(server.Connect(), CommandType.StoredProcedure, procedure); + void Derived() - => new ExpressiveDbCommand(connection, CommandType.StoredProcedure, procedure) + => NewCommand() .AddParam(orderId) .AddParam(customerId) .AddParam(startDate) .ExecuteNonQuery(); void Explicit() - => new ExpressiveDbCommand(connection, CommandType.StoredProcedure, procedure) + => NewCommand() .AddParam("@order_id", orderId) .AddParam("@customer_id", customerId) .AddParam("@start_date", startDate) diff --git a/Tests/Open.Database.Extensions.Core.Tests/NameCacheSharedTierLocalDbTests.cs b/Tests/Open.Database.Extensions.Core.Tests/NameCacheSharedTierLocalDbTests.cs index 05b1e6b8..3031bf76 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/NameCacheSharedTierLocalDbTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/NameCacheSharedTierLocalDbTests.cs @@ -32,10 +32,19 @@ public Scene() Second = "odx_name_second_" + id; Shared = "odx_name_shared_" + id; ExecuteOnly = "odx_name_user_execute_" + id; - foreach (string schema in new[] { First, Second, Shared }) + try { - Run($"create schema [{schema}]"); - _drops.Add($"drop schema if exists [{schema}]"); + foreach (string schema in new[] { First, Second, Shared }) + { + Run($"create schema [{schema}]"); + _drops.Add($"drop schema if exists [{schema}]"); + } + } + catch + { + // The caller never gets the scene to dispose, so drop what was made so far. + Dispose(); + throw; } } diff --git a/Tests/Open.Database.Extensions.Core.Tests/NameCacheSharedTierTests.cs b/Tests/Open.Database.Extensions.Core.Tests/NameCacheSharedTierTests.cs index 6f3cc8d7..e77e4376 100644 --- a/Tests/Open.Database.Extensions.Core.Tests/NameCacheSharedTierTests.cs +++ b/Tests/Open.Database.Extensions.Core.Tests/NameCacheSharedTierTests.cs @@ -15,8 +15,9 @@ namespace Open.Database.Extensions.Tests; // collection that disables parallelization runs after the parallel ones, one test at a time, so // no test runs while the bound test has the process-wide tier full or cleared. Each test uses a // server name of its own (NameServer.Unique), so what another test shared is never found. -// Tests in other collections that use a qualified name on a fake give it a server name of its -// own too. +// Tests in other collections: the fakes that read a qualified name give themselves a server +// name of their own too; the others keep a fixed server name and use names without a schema, +// names unique to them, or command types of their own, whose names are never shared. [CollectionDefinition(Name, DisableParallelization = true)] public sealed class SharedNameTierCollection { @@ -34,8 +35,8 @@ static CancellationToken Token const int OrderId = 1; // a name to derive the parameter name from - // The most procedures the shared tier holds. - const int Bound = 1024; + // The most procedures the shared tier holds: the library's own bound. + const int Bound = ProcedureParameterNames.MaxProcedures; // What a user's own command type answers for the parameter names of any procedure: the // same argument matches it as matches the server's names, under another spelling. @@ -121,6 +122,19 @@ public static void AnUnqualifiedName_IsReadOnceForEachConnection() Assert.Equal(3, server.Reads); } + // The brackets are not what makes a name shared: the schema is. + [Fact] + public static void ABracketedSchemaQualifiedName_IsReadOnce_ForTwoFreshConnections() + { + var server = NameServer.Create(); + string procedure = "[dbo].[" + Unqualified() + "]"; + + RunSync(server.Connect(), procedure); + RunSync(server.Connect(), procedure); + + Assert.Equal(1, server.Reads); + } + [Fact] public static void ASharedSet_ResolvesTheArgumentsOfEveryCommand() { @@ -379,7 +393,7 @@ public static void PastTheBound_NewSetsGoToTheirConnection_AndNothingIsCleared() for (int i = 0; i < Bound; i++) RunSync(server.Connect(), "dbo.cap" + i); Assert.Equal(Bound, server.Reads); - // The first 1024 are shared: no connection reads them again. + // The first ones, up to the bound, are shared: no connection reads them again. for (int i = 0; i < Bound; i++) RunSync(server.Connect(), "dbo.cap" + i); Assert.Equal(Bound, server.Reads); diff --git a/docsite/articles/expressive-commands.md b/docsite/articles/expressive-commands.md index 69d26168..7e3cf885 100644 --- a/docsite/articles/expressive-commands.md +++ b/docsite/articles/expressive-commands.md @@ -68,7 +68,7 @@ A parameter added after `Using` is added to a query that `Using` made from a def Everything after `Using` is what a command does: `Map()` is the same extension, every terminal and `SingleResult()` apply, the connection is opened late and closed again only if the call opened it, a factory's connection is disposed and a pool's is given back. `SetTimeout(seconds)` on a definition returns a new definition. A `DbQuery` takes the same sources as `Using` does for a command, but only the typed ones: a connection (`DbConnection`), a transaction, an `IDbConnectionPool` or an `IDbConnectionFactory`; a bare `Func` is not one (wrap it in `new DbConnectionFactory(func)`). -A call allocates less than the command builder and within 7 bytes of ADO.NET written by hand (within 23 bytes at a single value). Names are resolved as a command resolves them (see [Name a parameter from its argument](#name-a-parameter-from-its-argument)): `AddParam(authorId)` finds `@author_id`, and the typed form matches each member of the values type the same way and, when the names are known, does not send a member the query does not declare. A text definition finds its `@name` markers once, when it is made; a procedure's names are kept per connection source (the factory, the pool or the connection, also for a transaction) and per server and database (see [Parameter names are read once](#parameter-names-are-read-once)). +A call allocates less than the command builder and within 7 bytes of ADO.NET written by hand (within 23 bytes at a single value). Names are resolved as a command resolves them (see [Name a parameter from its argument](#name-a-parameter-from-its-argument)): `AddParam(authorId)` finds `@author_id`, and the typed form matches each member of the values type the same way and, when the names are known, does not send a member the query does not declare. A text definition finds its `@name` markers once, when it is made; a procedure's names are kept per server and database when its name has a schema, else per connection source (the factory, the pool or the connection, also for a transaction); see [Parameter names are read once](#parameter-names-are-read-once). ### Writes and scalars @@ -178,6 +178,7 @@ What sharing means for names kept for the whole process: - **Every login of the process sees them.** They are names, not data. But a name that matches no parameter throws with the list of what the procedure declares, so a login with no right on the procedure can see them there once another login has read them (SQL Server already shows the parameters to a login that may only execute it). The process is the boundary: do not share a process between logins that must not see each other's procedure signatures. - **A server is told by the name it reports as its `DataSource`.** Two servers that report the same name at different times (a test container on `localhost,1433` that is recreated with another version of the procedures, a failover to a server whose procedures differ) share one entry until a call fails and forgets it, as with any names that have gone stale. - **A fake connection in a test reports one server and one database.** Every test in the process that uses such a fake shares its names, so a test that counts the lookups depends on the order the tests run in. Give each fake a server name of its own, or leave it empty: an empty one is never shared. +- **The shared set also holds the parameter modes and scales that the [output-parameter check](#output-parameters) reads.** Whichever login needs them first reads them, and every sharer uses what it read until the set is forgotten, as with two logins sharing names. - **A call that fails for lack of the right to run the procedure forgets the names for everyone.** Other calls read them again; it costs lookups, nothing more. #### What was sent? diff --git a/docsite/articles/release-notes.md b/docsite/articles/release-notes.md index 23b72a1d..8a56eecc 100644 --- a/docsite/articles/release-notes.md +++ b/docsite/articles/release-notes.md @@ -8,7 +8,7 @@ Version 11 is `11.0.0-rc.17`. For moving a 10.x codebase, read [Coming from earl - **Fixed: a command made from a factory, a pool or a function read a procedure's parameter names again for every command.** A command made from a factory or pool that implements only the non-generic interface, or from a `Func` or a `Func` through `Command` or `StoredProcedure`, kept a separate cache per command, so the first run of every command asked the database for the names. Commands made from the same factory, pool or function now share one cache. Different factories, pools and functions still do not share. A function is told apart by the object its method belongs to: lambdas that capture nothing, in one class, are one source and share; a lambda that captures a local variable or a parameter and is built again for each call is a new source each time, so keep one factory for the application. See [Parameter names are read once](expressive-commands.md#parameter-names-are-read-once). - **Fixed: a stored procedure's parameter names with an ordinal that is not a number.** A row of the `ProcedureParameters` schema collection whose `ORDINAL_POSITION` is not a number that fits an `int` failed the call that looks up the names; the row is now skipped, and the other parameters are still found. -- **Changed: a procedure with a schema in its name has its parameter names read once per server and database, not once per source of connections.** A command or query of the library's own types that runs on a `DbConnection` which reports its server and its database finds the names of `dbo.get_author` there, whichever connection, factory, pool or transaction it was made from, so a connection created for each call no longer asks the database every time. A name without a schema, an answer of no names, a connection that reports no server or database, and a command class of your own stay with the source of the connections, as before. Up to 1024 procedures are shared; past that, new names stay with their source and nothing is dropped. The names are shared by every login of the process: see [Parameter names are read once](expressive-commands.md#parameter-names-are-read-once) for what that means. +- **Changed: a procedure with a schema in its name has its parameter names read once per server and database, not once per source of connections.** A command or query of the library's own types that runs on a `DbConnection` which reports its server and its database finds the names of `dbo.get_author` there, whichever connection, factory, pool or transaction it was made from, so a connection created for each call no longer asks the database every time. A name without a schema, an answer of no names, a connection that reports no server or database, and a command class of your own stay with the source of the connections, as before. Up to 1024 procedures are shared; past that, new names stay with their source and nothing is dropped. The parameter modes and scales that the output-parameter check reads are shared the same way. The names are shared by every login of the process: see [Parameter names are read once](expressive-commands.md#parameter-names-are-read-once) for what that means. ### Changes since rc.16