diff --git a/Source/Core/DbQuery.cs b/Source/Core/DbQuery.cs index 403edb8f..ccb50f72 100644 --- a/Source/Core/DbQuery.cs +++ b/Source/Core/DbQuery.cs @@ -71,9 +71,10 @@ 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 - // argument is sent as written. + // nothing. A procedure's names are remembered per server and + // 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 422dd7ce..9e25809d 100644 --- a/Source/Core/DbQueryRunner.cs +++ b/Source/Core/DbQueryRunner.cs @@ -292,17 +292,22 @@ 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. /// /// /// 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 on a connection that reports both, else once + /// per source. /// /// The query definition. /// The connection, transaction, pool or factory. @@ -319,8 +324,11 @@ 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 +354,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 +365,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..8d99c587 100644 --- a/Source/Core/ExpressiveCommandBase.cs +++ b/Source/Core/ExpressiveCommandBase.cs @@ -523,8 +523,12 @@ 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), 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 @@ -853,8 +857,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 +884,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 +900,7 @@ protected virtual ValueTask> GetProcedureParameterNamesAs TConnection connection, ProcedureKey key, CancellationToken cancellationToken) - => ProcedureParameterNames.Remember( - _poolOrConnection, + => RememberNames( key, await GetProcedureParameterNamesAsync( connection, @@ -922,7 +925,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) @@ -1052,12 +1055,42 @@ 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 as DbConnection)?.DataSource, connection.Database, + Command, connection.GetType()); + + /// + /// 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 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 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.FindUser(_poolOrConnection, key); + + /// + /// Keeps the names a lookup answered, where finds them. + /// + /// The key made by . + /// + /// 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.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 37cf2a99..c20d9894 100644 --- a/Source/Core/ProcedureParameterNames.cs +++ b/Source/Core/ProcedureParameterNames.cs @@ -3,18 +3,33 @@ 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. 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, + string? procedure, + Type? provider) : IEquatable { /// Gets the server; empty when it is not known. public string Server { get; } = server ?? string.Empty; @@ -22,10 +37,15 @@ 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 +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); return hash; } } @@ -57,6 +79,25 @@ 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. +/// +/// +/// 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; /// 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,11 +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. + /// 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 @@ -84,17 +127,98 @@ 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(); - /// Gets the kept names of a procedure. + /// + /// 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 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. + /// + /// 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 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) + => 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. + /// + /// 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 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 @@ -108,19 +232,75 @@ public sealed class Entries 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. + /// + /// 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. + // 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) + || 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. /// @@ -135,6 +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. ((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 new file mode 100644 index 00000000..91563140 --- /dev/null +++ b/Tests/Open.Database.Extensions.Core.Tests/NameCacheSharedTierCostTests.cs @@ -0,0 +1,91 @@ +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(SharedNameTierCollection.Name)] +[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"], + }; + 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() + => NewCommand() + .AddParam(orderId) + .AddParam(customerId) + .AddParam(startDate) + .ExecuteNonQuery(); + + void Explicit() + => NewCommand() + .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", 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; + + 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 new file mode 100644 index 00000000..3031bf76 --- /dev/null +++ b/Tests/Open.Database.Extensions.Core.Tests/NameCacheSharedTierLocalDbTests.cs @@ -0,0 +1,194 @@ +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 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(SharedNameTierCollection.Name)] +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 = "odx_name_first_" + id; + Second = "odx_name_second_" + id; + Shared = "odx_name_shared_" + id; + ExecuteOnly = "odx_name_user_execute_" + id; + try + { + 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; + } + } + + /// 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 parameters, string answer) + { + 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) + { + // 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. + static async Task OpenAs(string user) + { + var builder = new SqlConnectionStringBuilder(LocalDbFixture.ConnectionString) + { + Pooling = false, + }; + var connection = new SqlConnection(builder.ConnectionString); + 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) + => 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 TwoLogins_ShareAQualifiedProcedure_AndEachGetsItsOwnUnqualifiedOne() + { + LocalDbFixture.SkipUnlessAvailable(); + using var scene = new Scene(); + 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"); + 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 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 ALoginWhoseOnlyRightIsExecute_SeesTheParametersInTheSchemaLookup() + { + 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( + ProcedureSchemaNames.Collection, + [null, scene.Shared, scene.Procedure, null]); + + // 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[ProcedureSchemaNames.OrdinalPositionColumn], + System.Globalization.CultureInfo.InvariantCulture)) + .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 new file mode 100644 index 00000000..e77e4376 --- /dev/null +++ b/Tests/Open.Database.Extensions.Core.Tests/NameCacheSharedTierTests.cs @@ -0,0 +1,573 @@ +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. +// +// 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: 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 +{ + /// The name of the collection. + public const string Name + = "Shared name tier"; +} + +[Collection(SharedNameTierCollection.Name)] +[ExcludeFromCodeCoverage] +public static class NameCacheSharedTierTests +{ + static CancellationToken Token + => TestContext.Current.CancellationToken; + + const int OrderId = 1; // a name to derive the parameter name from + + // 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. + 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 RunSync(NameServer.NameConnection connection, string procedure) + => new ExpressiveDbCommand(connection, CommandType.StoredProcedure, procedure) + .AddParam(value: 1, expression: "filter.Region") + .ExecuteNonQuery(); + + static Task RunAsync(NameServer.NameConnection connection, string procedure) + => new ExpressiveDbCommand(connection, CommandType.StoredProcedure, procedure) + .AddParam(value: 1, expression: "filter.Region") + .ExecuteNonQueryAsync(Token) + .AsTask(); + + static void RunCustom(NameServer.NameConnection connection, string procedure) + => new CustomNamesCommand(connection, procedure) + .AddParam(value: 1, expression: "filter.Region") + .ExecuteNonQuery(); + + // 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) + { + RunSync(connection, procedure); + return Task.CompletedTask; + } + + static string Unique() + => ParameterNameHarness.NewProcedure(); + + // A procedure name without a schema. + static string Unqualified() + => Unique()["dbo.".Length..]; + + // ---- who shares ---- + + static async Task AssertReadOnceForTwoFreshConnections( + Func run) + { + var server = NameServer.Create(); + string procedure = Unique(); + + 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 = Unqualified(); + + RunSync(server.Connect(), procedure); + RunSync(server.Connect(), procedure); + NameServer.NameConnection same = server.Connect(); + RunSync(same, procedure); + RunSync(same, procedure); + + 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() + { + var server = NameServer.Create(); + string procedure = Unique(); + NameServer.NameConnection first = server.Connect(), second = server.Connect(); + + RunSync(first, procedure); + RunSync(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(); + RunSync(same, procedure); + RunSync(same, procedure); + Assert.Equal(1, server.Reads); + + RunSync(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) + { + // "x" stands for a server name of its own. + var server = new NameServer( + dataSource is "x" ? NameServer.Unique() : dataSource, + database); + string procedure = Unique(); + + 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 ANonDbConnection_SendsTheNameAsWritten_AndSharesNothing() + { + 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(); + Assert.Equal(["Region"], probe.Parameters.Select(p => p.ParameterName)); + } + + AssertNothingSharedFor(procedure); + } + + // 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) + { + string procedure = Unique(); + var key = new ProcedureKey(server, database, procedure, typeof(object)); + var source = new object(); + + 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); + + RunSync(source, procedure); + Assert.Equal(["@region"], source.Sent); + Assert.Equal(1, server.Reads); + + // 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 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 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() + { + FillSharedTier(); + try + { + AssertTheLibraryDoesNotTakeTheUsersNames(NameServer.Create(), Unique()); + } + finally + { + ClearShared(); + } + } + + [Fact] + public static void LibraryCommandFirst_UserKeepsItsOwn_Unqualified() + => AssertTheUserDoesNotTakeTheLibrarysNames(NameServer.Create(), Unqualified()); + + [Fact] + public static void LibraryCommandFirst_UserKeepsItsOwn_Qualified() + => AssertTheUserDoesNotTakeTheLibrarysNames(NameServer.Create(), Unique()); + + [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() + { + 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(); + NameServer.NameConnection b = secondDatabase.Connect(); + NameServer.NameConnection 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. + 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"] }; + RunSync(upper.Connect(), procedure); + 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] + public static void PastTheBound_NewSetsGoToTheirConnection_AndNothingIsCleared() + { + ClearShared(); + try + { + var server = NameServer.Create(); + + for (int i = 0; i < Bound; i++) RunSync(server.Connect(), "dbo.cap" + i); + Assert.Equal(Bound, server.Reads); + + // 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); + + // The 1025th is kept by the connection that read it, not shared. + NameServer.NameConnection owner = server.Connect(); + RunSync(owner, "dbo.cap" + Bound); + Assert.Equal(Bound + 1, server.Reads); + RunSync(owner, "dbo.cap" + Bound); + Assert.Equal(Bound + 1, server.Reads); + 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++) RunSync(server.Connect(), "dbo.cap" + i); + Assert.Equal(Bound + 2, server.Reads); + } + finally + { + ClearShared(); + } + } + + // ---- 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 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 DerivedParameterNameTests.ServerError(); + 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) + { + var server = NameServer.Create(); + string procedure = Unique(); + + await run(server.Connect(), procedure); + Assert.Equal(1, server.Reads); + + server.Failure = new DerivedParameterNameTests.ServerError(); + NameServer.NameConnection failing = server.Connect(); + 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); + Assert.Equal(2, server.Reads); + 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] + 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++) + { + NameServer.NameConnection connection = server.Connect(); + using DbTransaction transaction = connection.BeginTransaction(); + await write.Using(transaction) + .AddParam(OrderId) + .ExecuteNonQueryAsync(Token); + } + + Assert.Equal(1, server.Reads); + } + + [Fact] + public static async Task ADbNonQuery_ReadsAQualifiedNameOnce_AnUnqualifiedOneForEachConnection() + { + var server = NameServer.Create(); + server.Names = ["@order_id"]; + var shared = DbNonQuery.Procedure(Unique()); + 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..ab5ad086 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 @@ -58,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; } @@ -140,6 +140,12 @@ 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 +381,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 +399,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 +411,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 +427,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/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 new file mode 100644 index 00000000..22561982 --- /dev/null +++ b/Tests/Open.Database.Extensions.Core.Tests/TestHelpers/NameServer.cs @@ -0,0 +1,114 @@ +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 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); + DataTable table = ProcedureParametersTable.Create(); + 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 class NameConnection(NameServer server) : DbConnection + { + readonly DerivedParameterNameTests.RecordingDbCommand _command = new(); + + /// 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 + _command.Failure = server.Failure; + return _command; + } + + public override DataTable GetSchema(string collectionName, string?[] restrictionValues) + => 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 + { + 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..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 @@ -157,17 +157,29 @@ 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, 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. -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 (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, 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. 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. +- **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 72b9b5f1..8a56eecc 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 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