Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,21 @@ static Func<ImmutableArray<string>, object> BuildMakeSet()
{
ParameterExpression names = Expression.Parameter(typeof(ImmutableArray<string>));
ConstructorInfo constructor = NameSet.GetConstructors(BindingFlags.Instance | BindingFlags.Public)[0];
NewExpression made = constructor.GetParameters().Length == 1
? Expression.New(constructor, names)
: Expression.New(constructor, names, Expression.Constant(false));
return Expression.Lambda<Func<ImmutableArray<string>, object>>(Expression.Convert(made, typeof(object)), names).Compile();

// The parameters after the names (where a procedure's
// set is kept, and its key) are left at their defaults.
ParameterInfo[] parameters = constructor.GetParameters();
Expression[] arguments =
[
names,
.. parameters.Skip(1)
.Select(p => Expression.Default(p.ParameterType)),
];
return Expression.Lambda<Func<ImmutableArray<string>, object>>(
Expression.Convert(
Expression.New(constructor, arguments),
typeof(object)),
names).Compile();
}

static Func<object, string, string, string?> BuildMatchIn()
Expand All @@ -69,7 +80,9 @@ static Func<ImmutableArray<string>, object> BuildMakeSet()
ParameterExpression procedure = Expression.Parameter(typeof(string));
MethodInfo match = NameSet.GetMethod("Match", BindingFlags.Instance | BindingFlags.Public)!;
return Expression.Lambda<Func<object, string, string, string?>>(
Expression.Call(Expression.Convert(set, NameSet), match, expression, procedure),
Expression.Call(
Expression.Convert(set, NameSet), match,
expression, procedure, Expression.Constant(null, typeof(string))),
set,
expression,
procedure).Compile();
Expand Down Expand Up @@ -149,7 +162,6 @@ public void Setup()
}
}

// One thread runs the calls directly; more run one iteration each of a Parallel.For, every iteration making the same number of calls.
int Run(Func<int> calls)
{
if (Threads == 1) return calls();
Expand Down
3 changes: 1 addition & 2 deletions Source/Core/BoundCall.cs
Original file line number Diff line number Diff line change
Expand Up @@ -394,9 +394,8 @@ static BoundCall<TKind> WithCapture<TKind, TValue>(
CaptureSource<TValue> source,
out DbCapture<TValue> capture)
{
BoundCall<TKind> captured = WithCapture(call, source);
capture = new(source);
return captured;
return WithCapture(call, source);
}

/// <summary>
Expand Down
8 changes: 1 addition & 7 deletions Source/Core/Capture.cs
Original file line number Diff line number Diff line change
Expand Up @@ -80,9 +80,6 @@ interface ICaptureSource
/// <see langword="false"/> if it was armed before.</returns>
bool TryArm();

/// <summary>Arms the capture, if it is not armed yet.</summary>
void Arm();

/// <summary>Marks the capture as belonging to a stream whose enumerator is
/// open.</summary>
void BeginStream();
Expand Down Expand Up @@ -149,9 +146,6 @@ public bool TryArm()
=> Interlocked.CompareExchange(ref _state, Armed, NotStarted)
== NotStarted;

public void Arm()
=> Interlocked.CompareExchange(ref _state, Armed, NotStarted);

public void BeginStream()
=> Volatile.Write(ref _state, StreamOpen);

Expand Down Expand Up @@ -741,7 +735,7 @@ public void Claim()
if (Interlocked.Exchange(ref _claimed, 1) != 0 || !sources[0].TryArm())
throw new InvalidOperationException(CaptureMessages.SecondRun(set));

for (int i = 1; i < sources.Length; i++) sources[i].Arm();
for (int i = 1; i < sources.Length; i++) _ = sources[i].TryArm();
}

public override CaptureRun Start(CancellationToken cancellationToken)
Expand Down
15 changes: 14 additions & 1 deletion Source/Core/Core/DbConnectionProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,10 @@ internal class DbConnectionProvider<TConnection>(TConnection connection)
public TConnection Take()
{
if (_takenConnectionState.HasValue)
throw new InvalidOperationException("Concurrent use of a single connection is not supported.");
{
throw new InvalidOperationException(
DbConnectionProvider.ConcurrentUseMessage);
}

_takenConnectionState = Connection.State;
return Connection;
Expand Down Expand Up @@ -65,6 +68,16 @@ public void Give(IDbConnection connection)
/// </summary>
internal static class DbConnectionProvider
{
/// <summary>
/// The message of the exception for a connection that is taken while it is
/// in use, whoever guards it (this provider, or a command's own guard).
/// </summary>
public const string ConcurrentUseMessage =
"Concurrent use of a single connection is not supported. "
+ "Wait for the running call to finish, "
+ "or create the command from a connection factory or pool "
+ "so each call gets its own connection.";

/// <summary>
/// Creates a provider that hands out <paramref name="connection"/>.
/// </summary>
Expand Down
6 changes: 4 additions & 2 deletions Source/Core/DbQuery.cs
Original file line number Diff line number Diff line change
Expand Up @@ -186,11 +186,13 @@ public static DbQuery Procedure(string name)
-1,
null);

static string Checked(string text, string paramName)
// The one check of a command text (a definition's, and a command's).
internal static string Checked(string text, string paramName)
=> DbQueryCall.CheckedText(
text,
paramName,
"The command cannot be empty or white space.");
"The command cannot be empty or white space. "
+ "Pass the SQL text or the name of the stored procedure.");

/// <summary>
/// Returns a new definition with the command timeout set;
Expand Down
13 changes: 5 additions & 8 deletions Source/Core/ExpressiveCommandBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -107,13 +107,7 @@ private protected sealed class CommandOptions
private protected CommandOptions EnsureOptions() => _options ??= new();

static string CheckedCommand(string command)
{
if (command is null) throw new ArgumentNullException(nameof(command));
if (string.IsNullOrWhiteSpace(command)) throw new ArgumentException("The command cannot be empty or white space. Pass the SQL text or the name of the stored procedure.", nameof(command));
Contract.EndContractBlock();

return command;
}
=> DbQuery.Checked(command, nameof(command));

/// <summary>
/// Gets the transaction the command runs in, or <see langword="null"/>
Expand Down Expand Up @@ -1510,7 +1504,10 @@ TResult ExecuteDirect<TState, TResult>(TConnection single, TState state, Func<TC
Busy EnterDirect()
{
if (Interlocked.CompareExchange(ref _busy, 1, 0) != 0)
throw new InvalidOperationException("Concurrent use of a single connection is not supported. Wait for the running call to finish, or create the command from a connection factory or pool so each call gets its own connection.");
{
throw new InvalidOperationException(
DbConnectionProvider.ConcurrentUseMessage);
}

return new Busy(this);
}
Expand Down
21 changes: 6 additions & 15 deletions Source/Core/MappedViews.cs
Original file line number Diff line number Diff line change
Expand Up @@ -303,31 +303,22 @@ public static MappedQueryCore<T> QueryCore<T>(
? FromCommand(single.Command, source, true)
: FromCommand(command, source, false);

/// <summary>
/// Makes the query core of a call made from a <see cref="DbQuery"/> definition, which the query holds as it is.
/// </summary>
/// <typeparam name="T">The type each row is mapped to.</typeparam>
/// <param name="call">The call.</param>
/// <param name="source">Reads and maps one row.</param>
/// <returns>The new query core.</returns>
public static MappedQueryCore<T> QueryCore<T>(
DbQueryCall call,
IRowSource<T> source)
=> NewCore(null, call, source, QueryOptions.None);

/// <summary>
/// Makes the query core of a call made from a <see cref="DbQuery"/>
/// definition, with the options the definition holds.
/// definition, which the query holds as it is, with the options the
/// definition holds.
/// </summary>
/// <typeparam name="T">The type each row is mapped to.</typeparam>
/// <param name="call">The call.</param>
/// <param name="source">Reads and maps one row.</param>
/// <param name="options">The switches of the definition.</param>
/// <param name="options">
/// The switches of the definition; none by default.
/// </param>
/// <returns>The new query core.</returns>
public static MappedQueryCore<T> QueryCore<T>(
DbQueryCall call,
IRowSource<T> source,
QueryOptions options)
QueryOptions options = QueryOptions.None)
=> NewCore(null, call, source, options);

static QueryOptions Single(bool singleResult)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,23 @@ public static async Task APoolThatRestoresTheState_ClosesWhatTheScopeOpened_AndL
Assert.Empty(open.Log);
}

[Fact]
public static void APoolOfOneConnection_TakenTwice_SaysWhatIsWrongAndTheFix()
{
var pool = Open.Database.Extensions.Core.DbConnectionProvider.Create(
new ConnectionScopeTests.ScopeConnection());
_ = pool.Take();

InvalidOperationException ex
= Assert.Throws<InvalidOperationException>(pool.Take);
Assert.Equal(
"Concurrent use of a single connection is not supported. "
+ "Wait for the running call to finish, "
+ "or create the command from a connection factory or pool "
+ "so each call gets its own connection.",
ex.Message);
}

[Theory]
[InlineData(false)]
[InlineData(true)]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,9 @@ namespace Open.Database.Extensions.Tests;
public static class DbQueryChecksTests
{
const string BlankName = "Parameter names cannot be empty or white space.";
const string BlankCommand = "The command cannot be empty or white space.";
const string BlankCommandOfACommand = "The command cannot be empty or white space. Pass the SQL text or the name of the stored procedure.";
const string BlankCommand =
"The command cannot be empty or white space. "
+ "Pass the SQL text or the name of the stored procedure.";

static CancellationToken Token => TestContext.Current.CancellationToken;

Expand Down Expand Up @@ -122,7 +123,7 @@ public static void ACommandText_Blank_IsRefused_ByEveryConstructorWithItsMessage
{
ArgumentException ex = Assert.Throws<ArgumentException>(make);
Assert.Equal("command", ex.ParamName);
Assert.Equal(BlankCommandOfACommand, Text(ex));
Assert.Equal(BlankCommand, Text(ex));
}
}

Expand Down