diff --git a/Source/Core/DbQueryRunner.cs b/Source/Core/DbQueryRunner.cs
index f47ed595..422dd7ce 100644
--- a/Source/Core/DbQueryRunner.cs
+++ b/Source/Core/DbQueryRunner.cs
@@ -274,19 +274,15 @@ static DbCommand Make(
/// connections come from.
///
///
- /// That is the factory or pool (not the adapter AsPool makes around
- /// a factory), or the connection itself.
+ /// That is the factory or pool, or the connection itself for a
+ /// transaction. What a pool made around a factory stands for is found by
+ /// .
///
/// The connection, transaction, pool or factory.
/// The connection of the run.
/// The owner of the remembered names.
static object NameCacheOwner(object source, DbConnection connection)
- => source switch
- {
- DbTransaction => connection,
- IConnectionIdentity adapter => adapter.Identity,
- _ => source,
- };
+ => source is DbTransaction ? connection : source;
///
/// Makes the key a procedure's names are remembered under.
diff --git a/Source/Core/ExpressiveCommand.cs b/Source/Core/ExpressiveCommand.cs
index b0ef851d..7e6e9aed 100644
--- a/Source/Core/ExpressiveCommand.cs
+++ b/Source/Core/ExpressiveCommand.cs
@@ -56,10 +56,17 @@ public ExpressiveCommand(
CommandType type,
string command,
IEnumerable? @params = null)
- : base(connFactory.AsGeneric(), type, command, @params)
+ : base(CreateOf(connFactory), type, command, @params)
{
}
+ // The function is the factory's Create method, so what the factory has
+ // remembered (the names of its procedures) is shared by every command made
+ // from it. Guarding here keeps the parameter name the public constructor
+ // has always reported.
+ static Func CreateOf(IDbConnectionFactory connectionFactory)
+ => (connectionFactory ?? throw new ArgumentNullException(nameof(connectionFactory))).Create;
+
///
/// Initializes a new instance that invokes a function to create a new connection for each execution.
///
diff --git a/Source/Core/ExpressiveCommandBase.cs b/Source/Core/ExpressiveCommandBase.cs
index 2fd8fe80..e80a575d 100644
--- a/Source/Core/ExpressiveCommandBase.cs
+++ b/Source/Core/ExpressiveCommandBase.cs
@@ -853,8 +853,8 @@ protected virtual ValueTask> GetProcedureParameterNamesAs
if (Type == CommandType.StoredProcedure)
{
ProcedureKey key = KeyOf(connection);
- return ProcedureParameterNames.Find(NameCacheOwner, key)
- ?? ProcedureParameterNames.Remember(NameCacheOwner, key, GetProcedureParameterNames(connection, Command));
+ return ProcedureParameterNames.Find(_poolOrConnection, key)
+ ?? ProcedureParameterNames.Remember(_poolOrConnection, key, GetProcedureParameterNames(connection, Command));
}
// The @name markers found in the text.
@@ -880,7 +880,7 @@ protected virtual ValueTask> GetProcedureParameterNamesAs
if (Type == CommandType.StoredProcedure)
{
ProcedureKey key = KeyOf(connection);
- return ProcedureParameterNames.Find(NameCacheOwner, key) is { } kept
+ return ProcedureParameterNames.Find(_poolOrConnection, key) is { } kept
? new(kept)
: ReadNamesAsync(connection, key, cancellationToken);
}
@@ -897,7 +897,7 @@ protected virtual ValueTask> GetProcedureParameterNamesAs
ProcedureKey key,
CancellationToken cancellationToken)
=> ProcedureParameterNames.Remember(
- NameCacheOwner,
+ _poolOrConnection,
key,
await GetProcedureParameterNamesAsync(
connection,
@@ -922,7 +922,7 @@ await GetProcedureParameterNamesAsync(
if (Type == CommandType.StoredProcedure)
{
ProcedureKey key = KeyOf(connection);
- return ProcedureParameterNames.Find(NameCacheOwner, key) is { } kept
+ return ProcedureParameterNames.Find(_poolOrConnection, key) is { } kept
? kept.NeedsMetadata
? NamesWithMetadataAsync(connection, kept, cancellationToken)
: new(kept)
@@ -1043,21 +1043,6 @@ TCommand PrepareDerived(TConnection connection, NameSet? names, bool written = f
}
}
- ///
- /// Gets the object that remembered names belong to: the object commands
- /// take connections from.
- ///
- ///
- /// That is a factory (not the wrapper made around it for each command),
- /// a pool, or the bare connection.
- ///
- object NameCacheOwner => _poolOrConnection switch
- {
- DbConnectionFactoryExtensions.ConnectionFactoryToPoolAdapter typed => typed.Identity,
- DbConnectionFactoryExtensions.ConnectionFactoryToPoolAdapter untyped => untyped.Identity,
- _ => _poolOrConnection,
- };
-
///
/// Makes the key a procedure's names are remembered under.
///
diff --git a/Source/Core/Extensions/ConnectionProvider.Command.cs b/Source/Core/Extensions/ConnectionProvider.Command.cs
index f054bf2b..422d3c45 100644
--- a/Source/Core/Extensions/ConnectionProvider.Command.cs
+++ b/Source/Core/Extensions/ConnectionProvider.Command.cs
@@ -256,8 +256,8 @@ public static ExpressiveCommand Command(
public static ExpressiveCommand StoredProcedure(
this Func connectionSource,
string procedureName)
- // DbConnectionFactory.Create throws ArgumentNullException for a null source.
- => StoredProcedure(DbConnectionFactory.Create(connectionSource), procedureName);
+ // AsPool throws ArgumentNullException for a null source.
+ => StoredProcedure(connectionSource.AsPool(), procedureName);
///
/// Creates an that invokes a function to create a new connection for every execution.
diff --git a/Source/Core/IDbConnectionFactory.cs b/Source/Core/IDbConnectionFactory.cs
index 94b25fba..e475838e 100644
--- a/Source/Core/IDbConnectionFactory.cs
+++ b/Source/Core/IDbConnectionFactory.cs
@@ -131,7 +131,13 @@ public TConnection Take()
/// (the target of its Create method), which is what remembered procedure names belong to.
///
///
- /// A function with no target (a lambda) has no such identity, and its own delegate is returned.
+ ///
+ /// A function is identified by the object its method belongs to. A method of an object, and a lambda that captures only , have that object. A lambda that captures nothing belongs to a class the compiler makes for the enclosing class, so such lambdas of one class are one source. A lambda that captures a local variable or a parameter has a new closure for each time it is made, so a function made again for each command is a new source each time.
+ /// A function with no target at all (a method group of a method) has no such identity, and its own delegate is returned; whether converting the method again gives the same delegate is up to the compiler.
+ ///
+ ///
+ /// What is remembered for this identity lives as long as the object does (a singleton factory: the life of the process), at most 1024 procedures.
+ ///
///
public object Identity => _factory.Target ?? _factory;
diff --git a/Source/Core/IDbConnectionPool.cs b/Source/Core/IDbConnectionPool.cs
index cae3dd32..89b073f3 100644
--- a/Source/Core/IDbConnectionPool.cs
+++ b/Source/Core/IDbConnectionPool.cs
@@ -71,7 +71,7 @@ public static class ConnectionPoolExtensions
///
/// The pool to forward to.
/// is .
- class GenericPool(IDbConnectionPool source) : IDbConnectionPool
+ class GenericPool(IDbConnectionPool source) : IDbConnectionPool, IConnectionIdentity
{
private readonly IDbConnectionPool _source
= source ?? throw new ArgumentNullException(nameof(source));
@@ -83,6 +83,12 @@ public IDbConnection Take()
///
public void Give(IDbConnection connection)
=> _source.Give(connection);
+
+ // What remembered names belong to is the pool this one forwards to (or
+ // what that one stands for), not this wrapper, which is made again for
+ // each command.
+ object IConnectionIdentity.Identity
+ => _source is IConnectionIdentity identity ? identity.Identity : _source;
}
///
diff --git a/Source/Core/ProcedureParameterNames.cs b/Source/Core/ProcedureParameterNames.cs
index 75dc9229..37cf2a99 100644
--- a/Source/Core/ProcedureParameterNames.cs
+++ b/Source/Core/ProcedureParameterNames.cs
@@ -92,10 +92,22 @@ public sealed class Entries
/// The server, database and procedure.
/// The set, or when none is kept.
public static NameSet? Find(object source, ProcedureKey key)
- => Sources.TryGetValue(source, out Entries? entries) && entries.ByProcedure.TryGetValue(key, out NameSet? names)
+ => Sources.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
+ /// it stands for, else the source itself.
+ ///
+ /// The object commands take their connections from.
+ /// The owner of the remembered names.
+ // A pool made around a factory or a function (AsPool, AsGeneric) is made
+ // again for each command; its identity is what it stands for, so every
+ // command of one factory shares one set. One type check on each lookup.
+ static object OwnerOf(object source)
+ => source is IConnectionIdentity identity ? identity.Identity : source;
+
/// Keeps what the lookup answered.
/// The object commands take their connections from.
/// The server, database and procedure the names belong to.
@@ -103,7 +115,7 @@ public sealed class Entries
/// 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)
{
- Entries entries = Sources.GetValue(source, static _ => new Entries());
+ Entries entries = Sources.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));
diff --git a/Source/MSSqlClient/Extensions/ConnectionProvider.Command.cs b/Source/MSSqlClient/Extensions/ConnectionProvider.Command.cs
index a5c42f78..a586b43b 100644
--- a/Source/MSSqlClient/Extensions/ConnectionProvider.Command.cs
+++ b/Source/MSSqlClient/Extensions/ConnectionProvider.Command.cs
@@ -130,7 +130,8 @@ public static ExpressiveSqlCommand Command(
this Func connectionSource,
string command,
CommandType type = CommandType.Text)
- => Command(DbConnectionFactory.Create(connectionSource), command, type);
+ // AsPool throws ArgumentNullException for a null source.
+ => Command(connectionSource.AsPool(), command, type);
///
/// Creates an that calls a stored procedure, invoking a function to create a new connection for every execution.
@@ -142,5 +143,6 @@ public static ExpressiveSqlCommand Command(
public static ExpressiveSqlCommand StoredProcedure(
this Func connectionSource,
string procedureName)
- => StoredProcedure(DbConnectionFactory.Create(connectionSource), procedureName);
+ // AsPool throws ArgumentNullException for a null source.
+ => StoredProcedure(connectionSource.AsPool(), procedureName);
}
diff --git a/Source/SqlClient/Extensions/ConnectionProvider.Command.cs b/Source/SqlClient/Extensions/ConnectionProvider.Command.cs
index eaef5b50..d26e493c 100644
--- a/Source/SqlClient/Extensions/ConnectionProvider.Command.cs
+++ b/Source/SqlClient/Extensions/ConnectionProvider.Command.cs
@@ -129,7 +129,8 @@ public static ExpressiveSqlCommand Command(
this Func connectionSource,
string command,
CommandType type = CommandType.Text)
- => Command(DbConnectionFactory.Create(connectionSource), command, type);
+ // AsPool throws ArgumentNullException for a null source.
+ => Command(connectionSource.AsPool(), command, type);
///
/// Creates an that calls a stored procedure, that invokes a function to create a new connection for every execution.
@@ -142,5 +143,6 @@ public static ExpressiveSqlCommand Command(
public static ExpressiveSqlCommand StoredProcedure(
this Func connectionSource,
string procedureName)
- => StoredProcedure(DbConnectionFactory.Create(connectionSource), procedureName);
+ // AsPool throws ArgumentNullException for a null source.
+ => StoredProcedure(connectionSource.AsPool(), procedureName);
}
diff --git a/Tests/Open.Database.Extensions.Core.Tests/NameCacheSourceTests.cs b/Tests/Open.Database.Extensions.Core.Tests/NameCacheSourceTests.cs
new file mode 100644
index 00000000..590fdcb4
--- /dev/null
+++ b/Tests/Open.Database.Extensions.Core.Tests/NameCacheSourceTests.cs
@@ -0,0 +1,564 @@
+extern alias mssql;
+
+using System.Data.Common;
+using Microsoft.Data.SqlClient;
+using MsCommand = mssql::Open.Database.Extensions.ExpressiveSqlCommand;
+using MsExtensions = mssql::Open.Database.Extensions.SqlConnectionExtensions;
+using LegacyCommand = global::Open.Database.Extensions.ExpressiveSqlCommand;
+using LegacyExtensions = global::Open.Database.Extensions.SqlConnectionExtensions;
+
+namespace Open.Database.Extensions.Tests;
+
+#nullable enable
+
+// A procedure's parameter names are read once per source of connections
+// (the factory, the pool or the function a command is made from) and then
+// kept. Commands made from the same source share what it kept, so only the
+// first run pays for the read. Reads are counted at the provider: each one is
+// a GetSchema call on the connection.
+[ExcludeFromCodeCoverage]
+[Collection("LocalDB DDL")]
+public static class NameCacheSourceTests
+{
+ static CancellationToken Token
+ => TestContext.Current.CancellationToken;
+
+ sealed class Reads
+ {
+ public int Count { get; set; }
+
+ // What every command run on a connection of this source throws, when set.
+ public Exception? Failure { get; set; }
+ }
+
+ sealed class FakeDbException(string message) : DbException(message);
+
+ sealed class SchemaConnection(Reads reads) : DbConnection
+ {
+ readonly DerivedParameterNameTests.RecordingDbCommand _command = new() { Failure = reads.Failure };
+
+ [AllowNull]
+ public override string ConnectionString { get; set; } = "";
+ public override string Database
+ => "fake";
+ public override string DataSource
+ => "fake";
+ 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)
+ => throw new NotSupportedException();
+ protected override DbCommand CreateDbCommand()
+ => _command;
+
+ 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));
+ table.Rows.Add("dbo", "proc", 1, "@region");
+ return table;
+ }
+ }
+
+ // Implements only the non-generic interface: no IDbConnectionFactory.
+ sealed class PlainFactory(Reads reads) : IDbConnectionFactory
+ {
+ public IDbConnection Create()
+ => new SchemaConnection(reads);
+ }
+
+ // Implements only the non-generic interface: no IDbConnectionPool.
+ sealed class PlainPool(Reads reads) : IDbConnectionPool
+ {
+ public IDbConnection Take()
+ => new SchemaConnection(reads);
+
+ public void Give(IDbConnection connection)
+ => connection.Dispose();
+ }
+
+ sealed class TypedFactory(Reads reads) : IDbConnectionFactory
+ {
+ public SchemaConnection Create()
+ => new(reads);
+
+ IDbConnection IDbConnectionFactory.Create()
+ => Create();
+ }
+
+ // Two delegates on one object: instance methods that create connections.
+ sealed class Maker(Reads reads)
+ {
+ public SchemaConnection Create()
+ => new(reads);
+
+ public SchemaConnection CreateAnother()
+ => new(reads);
+ }
+
+ static readonly Reads Shared = new();
+
+ static IDbConnection CreateShared()
+ => new SchemaConnection(Shared);
+
+ static Func NonCapturingA()
+ => () => new SchemaConnection(Shared);
+
+ static Func NonCapturingB()
+ => () => new SchemaConnection(Shared);
+
+ // Captures reads: each call makes a closure of its own.
+ static Func Capturing(Reads reads)
+ => () => new SchemaConnection(reads);
+
+ static void Run(ExpressiveCommand command)
+ => command.AddParam(value: 1, expression: "filter.Region")
+ .ExecuteNonQuery();
+
+ static async Task RunAsync(ExpressiveDbCommand command)
+ => await command.AddParam(value: 1, expression: "filter.Region")
+ .ExecuteNonQueryAsync(Token);
+
+ static async Task RunAsync(MsCommand command)
+ => await command.AddParam(value: 1, expression: "filter.Region")
+ .ExecuteNonQueryAsync(Token);
+
+#pragma warning disable CS0618 // System.Data.SqlClient is obsolete; it is one of the two packages under test
+ static async Task RunAsync(LegacyCommand command)
+ => await command.AddParam(value: 1, expression: "filter.Region")
+ .ExecuteNonQueryAsync(Token);
+#pragma warning restore CS0618
+
+ static string Procedure()
+ => ParameterNameHarness.NewProcedure();
+
+ // ---- a non-generic factory ----
+
+ [Fact]
+ public static void TwoCommands_FromOneNonGenericFactory_ReadTheNamesOnce()
+ {
+ var reads = new Reads();
+ var factory = new PlainFactory(reads);
+ string procedure = Procedure();
+
+ Run(new ExpressiveCommand(factory, CommandType.StoredProcedure, procedure));
+ Run(new ExpressiveCommand(factory, CommandType.StoredProcedure, procedure));
+
+ Assert.Equal(1, reads.Count);
+ }
+
+ [Fact]
+ public static void TwoCommands_FromOneNonGenericFactoryExtensions_ReadTheNamesOnce()
+ {
+ var reads = new Reads();
+ var factory = new PlainFactory(reads);
+ string procedure = Procedure();
+
+ Run(factory.StoredProcedure(procedure));
+ Run(factory.Command(procedure, CommandType.StoredProcedure));
+
+ Assert.Equal(1, reads.Count);
+ }
+
+ // ---- a non-generic pool ----
+
+ [Fact]
+ public static void TwoCommands_FromOneNonGenericPool_ReadTheNamesOnce()
+ {
+ var reads = new Reads();
+ var pool = new PlainPool(reads);
+ string procedure = Procedure();
+
+ Run(new ExpressiveCommand(pool, CommandType.StoredProcedure, procedure));
+ Run(new ExpressiveCommand(pool, CommandType.StoredProcedure, procedure));
+
+ Assert.Equal(1, reads.Count);
+ }
+
+ [Fact]
+ public static void TwoCommands_FromOneNonGenericPoolExtensions_ReadTheNamesOnce()
+ {
+ var reads = new Reads();
+ var pool = new PlainPool(reads);
+ string procedure = Procedure();
+
+ Run(pool.StoredProcedure(procedure));
+ Run(pool.Command(procedure, CommandType.StoredProcedure));
+
+ Assert.Equal(1, reads.Count);
+ }
+
+ // ---- a function ----
+
+ [Fact]
+ public static void TwoCommands_FromOneFunctionConstructor_ReadTheNamesOnce()
+ {
+ var reads = new Reads();
+ Func create = Capturing(reads);
+ string procedure = Procedure();
+
+ Run(new ExpressiveCommand(create, CommandType.StoredProcedure, procedure));
+ Run(new ExpressiveCommand(create, CommandType.StoredProcedure, procedure));
+
+ Assert.Equal(1, reads.Count);
+ }
+
+ [Fact]
+ public static void TwoCommands_FromOneFunctionStoredProcedure_ReadTheNamesOnce()
+ {
+ var reads = new Reads();
+ Func create = Capturing(reads);
+ string procedure = Procedure();
+
+ Run(create.StoredProcedure(procedure));
+ Run(create.StoredProcedure(procedure));
+
+ Assert.Equal(1, reads.Count);
+ }
+
+ [Fact]
+ public static void TwoCommands_FromOneFunctionCommand_ReadTheNamesOnce()
+ {
+ var reads = new Reads();
+ Func create = Capturing(reads);
+ string procedure = Procedure();
+
+ Run(create.Command(procedure, CommandType.StoredProcedure));
+ Run(create.Command(procedure, CommandType.StoredProcedure));
+
+ Assert.Equal(1, reads.Count);
+ }
+
+ [Fact]
+ public static void TwoCommands_FromOneFunctionAsPool_ReadTheNamesOnce()
+ {
+ var reads = new Reads();
+ Func create = Capturing(reads);
+ string procedure = Procedure();
+
+ IDbConnectionPool first = create.AsPool();
+ IDbConnectionPool second = create.AsPool();
+
+ Run(first.StoredProcedure(procedure));
+ Run(second.StoredProcedure(procedure));
+
+ Assert.Equal(1, reads.Count);
+ }
+
+ [Fact]
+ public static async Task TwoCommands_FromOneTypedFunction_ReadTheNamesOnce()
+ {
+ var reads = new Reads();
+ Func create = () => new(reads);
+ string procedure = Procedure();
+
+ await RunAsync(create.StoredProcedure(procedure));
+ await RunAsync(create.StoredProcedure(procedure));
+
+ Assert.Equal(1, reads.Count);
+ }
+
+ [Fact]
+ public static async Task TwoCommands_FromOneTypedFactory_ReadTheNamesOnce()
+ {
+ var reads = new Reads();
+ var factory = new TypedFactory(reads);
+ string procedure = Procedure();
+
+ await RunAsync(factory.StoredProcedure(procedure));
+ await RunAsync(factory.StoredProcedure(procedure));
+
+ Assert.Equal(1, reads.Count);
+ }
+
+ // ---- SQL Server packages: the second run of a command from one function
+ // is cheaper by the schema read ----
+
+ // Round trips the connections of one function made, summed when each
+ // closes; reset by Take.
+ sealed class Trips
+ {
+ long _sum;
+
+ public long Take()
+ => Interlocked.Exchange(ref _sum, 0);
+
+ public void Add(long trips)
+ => Interlocked.Add(ref _sum, trips);
+ }
+
+ static Func CountingMs(Trips trips)
+ => () =>
+ {
+ SqlConnection connection = LocalDbFixture.Create();
+ connection.StatisticsEnabled = true;
+ connection.StateChange += (_, e) =>
+ {
+ if (e.CurrentState == ConnectionState.Closed)
+ {
+ trips.Add((long)connection.RetrieveStatistics()["ServerRoundtrips"]!);
+ }
+ };
+ return connection;
+ };
+
+#pragma warning disable CS0618 // System.Data.SqlClient is obsolete; it is one of the two packages under test
+ static Func CountingLegacy(Trips trips)
+ => () =>
+ {
+ var connection = new System.Data.SqlClient.SqlConnection(LocalDbFixture.ConnectionString)
+ {
+ StatisticsEnabled = true,
+ };
+ connection.StateChange += (_, e) =>
+ {
+ if (e.CurrentState == ConnectionState.Closed)
+ {
+ trips.Add((long)connection.RetrieveStatistics()["ServerRoundtrips"]!);
+ }
+ };
+ return connection;
+ };
+#pragma warning restore CS0618
+
+ [Fact]
+ public static async Task TwoCommands_FromOneSqlServerFunction_ReadTheNamesOnce()
+ {
+ LocalDbFixture.SkipUnlessAvailable();
+ using LocalDbFixture.Scratch procedure = LocalDbFixture.CreateProcedure("@region int");
+ string name = "dbo." + procedure.Name;
+ var trips = new Trips();
+ Func create = CountingMs(trips);
+
+ await RunAsync(MsExtensions.StoredProcedure(create, name));
+ long first = trips.Take();
+ await RunAsync(MsExtensions.StoredProcedure(create, name));
+ long second = trips.Take();
+ await RunAsync(
+ MsExtensions.Command(create, name, CommandType.StoredProcedure));
+ long third = trips.Take();
+
+ Assert.True(first > 0);
+ Assert.True(second < first, $"The second command paid for the names again: {first} round trips, then {second}.");
+ Assert.Equal(second, third);
+ }
+
+#pragma warning disable CS0618 // System.Data.SqlClient is obsolete; it is one of the two packages under test
+ [Fact]
+ public static async Task TwoCommands_FromOneLegacySqlServerFunction_ReadTheNamesOnce()
+ {
+ LocalDbFixture.SkipUnlessAvailable();
+ using LocalDbFixture.Scratch procedure = LocalDbFixture.CreateProcedure("@region int");
+ string name = "dbo." + procedure.Name;
+ var trips = new Trips();
+ Func create = CountingLegacy(trips);
+
+ await RunAsync(LegacyExtensions.StoredProcedure(create, name));
+ long first = trips.Take();
+ await RunAsync(LegacyExtensions.StoredProcedure(create, name));
+ long second = trips.Take();
+ await RunAsync(
+ LegacyExtensions.Command(create, name, CommandType.StoredProcedure));
+ long third = trips.Take();
+
+ Assert.True(first > 0);
+ Assert.True(second < first, $"The second command paid for the names again: {first} round trips, then {second}.");
+ Assert.Equal(second, third);
+ }
+#pragma warning restore CS0618
+
+ // ---- distinct sources stay distinct ----
+
+ [Fact]
+ public static void CommandsFromDifferentNonGenericFactories_DoNotShareTheirNames()
+ {
+ var reads = new Reads();
+ string procedure = Procedure();
+
+ Run(new ExpressiveCommand(new PlainFactory(reads), CommandType.StoredProcedure, procedure));
+ Run(new ExpressiveCommand(new PlainFactory(reads), CommandType.StoredProcedure, procedure));
+
+ Assert.Equal(2, reads.Count);
+ }
+
+ [Fact]
+ public static void CommandsFromDifferentNonGenericPools_DoNotShareTheirNames()
+ {
+ var reads = new Reads();
+ string procedure = Procedure();
+
+ Run(new ExpressiveCommand(new PlainPool(reads), CommandType.StoredProcedure, procedure));
+ Run(new ExpressiveCommand(new PlainPool(reads), CommandType.StoredProcedure, procedure));
+
+ Assert.Equal(2, reads.Count);
+ }
+
+ [Fact]
+ public static void CommandsFromDifferentFunctions_DoNotShareTheirNames()
+ {
+ var reads = new Reads();
+ string procedure = Procedure();
+
+ Run(Capturing(reads).StoredProcedure(procedure));
+ Run(Capturing(reads).StoredProcedure(procedure));
+
+ Assert.Equal(2, reads.Count);
+ }
+
+ // ---- limits of the function identity, pinned as they are ----
+
+ // A function built twice over a captured local or parameter is two
+ // sources: its target is a closure made per build.
+ [Fact]
+ public static void ACapturingLambdaBuiltTwice_IsTwoSources()
+ {
+ var reads = new Reads();
+ string procedure = Procedure();
+
+ Run(Capturing(reads).StoredProcedure(procedure));
+ Run(Capturing(reads).StoredProcedure(procedure));
+
+ Assert.Equal(2, reads.Count);
+ }
+
+ // Lambdas that capture nothing are instance methods of one class the
+ // compiler makes, so that object is their target and they are one source,
+ // whatever they connect to: the same procedure name through two of them
+ // is read once. This pins what the compiler does today, not a contract.
+ [Fact]
+ public static void TwoNonCapturingLambdasOfOneClass_ShareOneSource()
+ {
+ Shared.Count = 0;
+ string procedure = Procedure();
+
+ Run(NonCapturingA().StoredProcedure(procedure));
+ Run(NonCapturingB().StoredProcedure(procedure));
+
+ Assert.Equal(1, Shared.Count);
+ }
+
+ // A method group of a static method has no target, so the delegate itself
+ // is the source. The compiler currently reuses one delegate for the same
+ // static method, so converting it twice gives one source; that is the
+ // compiler's behavior today, not a contract.
+ [Fact]
+ public static void AStaticMethodGroupConvertedTwice_IsOneSource()
+ {
+ Shared.Count = 0;
+ string procedure = Procedure();
+
+ Func first = CreateShared;
+ Func second = CreateShared;
+
+ Run(first.StoredProcedure(procedure));
+ Run(second.StoredProcedure(procedure));
+
+ Assert.Equal(1, Shared.Count);
+ }
+
+ // Two delegates of one object are one source: the object is the identity, not the method.
+ [Fact]
+ public static void TwoInstanceMethodsOfOneObject_ShareOneSource()
+ {
+ var reads = new Reads();
+ var maker = new Maker(reads);
+ string procedure = Procedure();
+
+ Run(new ExpressiveCommand(maker.Create, CommandType.StoredProcedure, procedure));
+ Run(new ExpressiveCommand(maker.CreateAnother, CommandType.StoredProcedure, procedure));
+
+ Assert.Equal(1, reads.Count);
+ }
+
+ // A DbException from the database forgets the names the shared set holds,
+ // so the next command, from any command of that source, reads again.
+ [Fact]
+ public static void ADbException_ForgetsTheSharedNames()
+ {
+ var reads = new Reads();
+ var factory = new PlainFactory(reads);
+ string procedure = Procedure();
+
+ Run(new ExpressiveCommand(factory, CommandType.StoredProcedure, procedure));
+ Assert.Equal(1, reads.Count);
+
+ reads.Failure = new FakeDbException("rejected");
+ Assert.Throws(
+ () => Run(new ExpressiveCommand(factory, CommandType.StoredProcedure, procedure)));
+
+ reads.Failure = null;
+ Run(new ExpressiveCommand(factory, CommandType.StoredProcedure, procedure));
+
+ Assert.Equal(2, reads.Count);
+ }
+
+ // ---- what a source that is gone leaves behind ----
+
+ static WeakReference RunFromAFactory(string procedure)
+ {
+ var factory = new PlainFactory(new Reads());
+ Run(new ExpressiveCommand(factory, CommandType.StoredProcedure, procedure));
+ Run(factory.StoredProcedure(procedure));
+ return new WeakReference(factory);
+ }
+
+ [Fact]
+ public static void AFactory_IsNotKeptAliveByItsRememberedNames()
+ {
+ WeakReference weak = RunFromAFactory(Procedure());
+ for (int i = 0; i < 3 && weak.IsAlive; i++)
+ {
+ GC.Collect();
+ GC.WaitForPendingFinalizers();
+ GC.Collect();
+ }
+
+ Assert.False(weak.IsAlive);
+ }
+
+ // ---- a null source, as each entry point answers it ----
+
+ static string Refusal(Action act)
+ {
+ Exception ex = Assert.ThrowsAny(act);
+ return ex is ArgumentNullException named
+ ? $"{nameof(ArgumentNullException)}:{named.ParamName}"
+ : ex.GetType().Name;
+ }
+
+ [Fact]
+ public static void ANullSource_IsRefused_ByNamingTheParameter()
+ {
+ Assert.Equal("ArgumentNullException:connectionFactory", Refusal(() => _ = new ExpressiveCommand((IDbConnectionFactory)null!, CommandType.StoredProcedure, "proc")));
+ Assert.Equal("ArgumentNullException:source", Refusal(() => _ = new ExpressiveCommand((IDbConnectionPool)null!, CommandType.StoredProcedure, "proc")));
+ Assert.Equal("ArgumentNullException:connFactory", Refusal(() => _ = new ExpressiveCommand((Func)null!, CommandType.StoredProcedure, "proc")));
+ }
+
+ [Fact]
+ public static void ANullSource_IsRefused_ByTheCoreExtensions()
+ {
+ Assert.Equal("ArgumentNullException:factory", Refusal(() => ((Func)null!).StoredProcedure("proc")));
+ Assert.Equal("ArgumentNullException:factory", Refusal(() => ((Func)null!).Command("proc", CommandType.StoredProcedure)));
+ Assert.Equal("ArgumentNullException:factory", Refusal(() => ((Func)null!).StoredProcedure("proc")));
+ Assert.Equal("ArgumentNullException:factory", Refusal(() => ((Func)null!).Command("proc", CommandType.StoredProcedure)));
+ }
+
+ [Fact]
+ public static void ANullFunction_IsRefused_BySqlServerExtensions()
+ {
+ Assert.Equal("ArgumentNullException:factory", Refusal(() => MsExtensions.StoredProcedure((Func)null!, "proc")));
+ Assert.Equal("ArgumentNullException:factory", Refusal(() => MsExtensions.Command((Func)null!, "proc", CommandType.StoredProcedure)));
+#pragma warning disable CS0618 // System.Data.SqlClient is obsolete; it is one of the two packages under test
+ Assert.Equal("ArgumentNullException:factory", Refusal(() => LegacyExtensions.StoredProcedure((Func)null!, "proc")));
+ Assert.Equal("ArgumentNullException:factory", Refusal(() => LegacyExtensions.Command((Func)null!, "proc", CommandType.StoredProcedure)));
+#pragma warning restore CS0618
+ }
+}
diff --git a/docsite/articles/expressive-commands.md b/docsite/articles/expressive-commands.md
index f056ec75..0c93fd83 100644
--- a/docsite/articles/expressive-commands.md
+++ b/docsite/articles/expressive-commands.md
@@ -157,7 +157,7 @@ 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. **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. 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.
Names are kept per server, database and procedure name. One factory keeps the names of up to 1024 procedures; past that it starts over.
diff --git a/docsite/articles/release-notes.md b/docsite/articles/release-notes.md
index 1b7cbe58..37fa6c11 100644
--- a/docsite/articles/release-notes.md
+++ b/docsite/articles/release-notes.md
@@ -4,6 +4,10 @@ Version 11 is `11.0.0-rc.17`. For moving a 10.x codebase, read [Coming from earl
## Version 11 release candidates
+### Changes since rc.17
+
+- **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).
+
### Changes since rc.16
- **Generated row readers for `DbQuery` too.** A plain `Map()` on a `DbQuery`, a `DbQuery` or a query bound with `Using` now gets its row reader written at build time, as on a command or a reader; before, it used the runtime map. The runtime map's conversions are therefore no longer applied there: see [Generated readers](mapping.md#generated-readers) for the differences and the switch.