Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions Source/Channel/ToChannel.Produce.cs
Original file line number Diff line number Diff line change
Expand Up @@ -223,8 +223,9 @@ IAsyncEnumerable<ReadOnlyMemory<T>> chunks
AllowSynchronousContinuations = false,
});

// A failure reaches the channel through Complete; the task
// is dropped unobserved unless the caller asked for the count.
// A failure reaches the channel through Complete: the task's own
// fault is read so that a caller who drops the count never has it
// reported as unobserved. A caller who awaits it still sees it.
readCount = ChannelPump
.Run<T, ChunkFeed<T>>(
new(chunks),
Expand All @@ -233,6 +234,13 @@ IAsyncEnumerable<ReadOnlyMemory<T>> chunks
cancellationToken)
.AsTask();

_ = readCount.ContinueWith(
static task => task.Exception,
CancellationToken.None,
TaskContinuationOptions.OnlyOnFaulted
| TaskContinuationOptions.ExecuteSynchronously,
TaskScheduler.Default);

return channel;
}
}
20 changes: 0 additions & 20 deletions Source/Core/Core/RowErrors.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,16 +12,6 @@ namespace Open.Database.Extensions;
/// </summary>
static class RowErrors
{
/// <summary>
/// Creates the exception for a failure mapping a row whose number is not known (a reader whose caller owns the read loop).
/// </summary>
/// <param name="inner">The error the read or the conversion raised.</param>
/// <param name="target">The model type, or the type of the single value.</param>
/// <param name="singleValue"><see langword="true"/> for a single value; otherwise, <see langword="false"/> for a model.</param>
/// <returns>The exception to throw.</returns>
public static ValueMappingException Create(Exception inner, Type target, bool singleValue)
=> Create(inner, target, singleValue, -1);

/// <summary>
/// Creates the exception for a failure mapping a row.
/// </summary>
Expand Down Expand Up @@ -151,16 +141,6 @@ public ValueMappingException Create(Type model, int row)
#pragma warning restore IDE0079 // Remove unnecessary suppression
sealed class RowMappingFailure(Exception inner, Type target, bool singleValue) : Exception(null, inner)
{
/// <summary>
/// Creates the wrapper; called by the compiled row readers.
/// </summary>
/// <param name="inner">The error the read or the conversion raised.</param>
/// <param name="target">The model type, or the type of the single value.</param>
/// <param name="singleValue"><see langword="true"/> for a single value; otherwise, <see langword="false"/> for a model.</param>
/// <returns>The wrapper to throw.</returns>
public static RowMappingFailure Defer(Exception inner, Type target, bool singleValue)
=> new(inner, target, singleValue);

/// <summary>
/// Returns the exception the read loop throws, naming the row.
/// </summary>
Expand Down
23 changes: 13 additions & 10 deletions Source/Core/Core/RowMap.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1807,9 +1807,18 @@ static Expression OnNull(CellRead read, Slot slot, string column)
static BlockExpression Guard(Expression body, List<ParameterExpression> variables, bool singleValue, bool rowKnown)
{
ParameterExpression ex = Expression.Parameter(typeof(Exception), "ex");
MethodInfo fail = rowKnown
? typeof(RowMappingFailure).GetMethod(nameof(RowMappingFailure.Defer))!
: typeof(RowErrors).GetMethod(nameof(RowErrors.Create), [typeof(Exception), typeof(Type), typeof(bool)])!;
Expression type = Expression.Constant(typeof(T));
Expression single = Expression.Constant(singleValue);
Expression fail = rowKnown
? Expression.New(
typeof(RowMappingFailure).GetConstructor(
[typeof(Exception), typeof(Type), typeof(bool)])!,
ex, type, single)
: Expression.Call(
typeof(RowErrors).GetMethod(
nameof(RowErrors.Create),
[typeof(Exception), typeof(Type), typeof(bool), typeof(int)])!,
ex, type, single, Expression.Constant(-1));

return Expression.Block(
typeof(T),
Expand All @@ -1823,13 +1832,7 @@ static BlockExpression Guard(Expression body, List<ParameterExpression> variable
Expression.TypeIs(ex, typeof(DbException)),
Expression.TypeIs(ex, typeof(OperationCanceledException))),
Expression.Rethrow(typeof(T)),
Expression.Throw(
Expression.Call(
fail,
ex,
Expression.Constant(typeof(T)),
Expression.Constant(singleValue)),
typeof(T))))));
Expression.Throw(fail, typeof(T))))));
}

/// <summary>
Expand Down
14 changes: 0 additions & 14 deletions Source/Core/DbQueryBinding.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,20 +19,6 @@ static class DbQueryBinding
public static bool Known(NameSet? names)
=> names is { Names.Length: > 0 };

/// <summary>
/// Gets the real name an argument of <c>AddParam(value)</c> stands for.
/// </summary>
/// <param name="derived">The facts of the argument's text.</param>
/// <param name="names">The remembered names, or <see langword="null"/> when they are not known.</param>
/// <param name="definition">The query definition.</param>
/// <returns>The real name; the last member as written when the names are not known.</returns>
/// <exception cref="InvalidOperationException">The expression matches none of the names, or more than one equally well.</exception>
public static string ResolveDerived(
ParameterNames.DerivedExpression derived,
NameSet? names,
DbQuery definition)
=> ResolveDerived(derived, names, definition, out _);

/// <summary>
/// Gets the real name an argument of <c>AddParam(value)</c> stands for, and its place in the names.
/// </summary>
Expand Down
31 changes: 14 additions & 17 deletions Source/Core/DbQueryParams.cs
Original file line number Diff line number Diff line change
Expand Up @@ -197,23 +197,20 @@ public bool Claims(string name, NameSet? names, DbQuery definition)
Get(i, out object key, out _);
switch (key)
{
case string written:
if (DbQueryBinding.SameName(written, name)) return true;
break;

case NameSet.Entry entry:
if (DbQueryBinding.SameName(entry.Real, name)) return true;
break;

case ParameterNames.DerivedExpression derived:
if (DbQueryBinding.SameName(
DbQueryBinding.ResolveDerived(derived, names, definition),
name))
{
return true;
}

break;
case string written
when DbQueryBinding.SameName(written, name):
return true;

case NameSet.Entry entry
when DbQueryBinding.SameName(entry.Real, name):
return true;

case ParameterNames.DerivedExpression derived
when DbQueryBinding.SameName(
DbQueryBinding.ResolveDerived(
derived, names, definition, out _),
name):
return true;
}
}

Expand Down
15 changes: 3 additions & 12 deletions Source/Core/DirectStream.cs
Original file line number Diff line number Diff line change
Expand Up @@ -146,17 +146,6 @@ bool TryMove(int from, int to)
}
}

// Sets the state whatever it was, and returns what it was.
int Exchange(int to)
{
while (true)
{
long word = Volatile.Read(ref _word);
if (Interlocked.CompareExchange(ref _word, (word & ~StateMask) | (uint)to, word) == word)
return (int)(word & StateMask);
}
}

#endregion

#region The consumer's side
Expand Down Expand Up @@ -331,7 +320,9 @@ void Tick()

async ValueTask DisposeCoreAsync()
{
int was = Exchange(Disposed);
// The timestamp is only read while the state is Idle, so a disposed
// stream does not keep it.
int was = (int)(Interlocked.Exchange(ref _word, Disposed) & StateMask);
if (was is NotStarted or Disposed) return;

StopTimer();
Expand Down
12 changes: 10 additions & 2 deletions Source/Core/Extensions/Command._.cs
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,11 @@ public static async ValueTask ExecuteReaderAsync(this IDbCommand command,

if (command is DbCommand c)
{
await c.ExecuteReaderAsync(reader => handler(reader), behavior, cancellationToken).ConfigureAwait(false);
// The cast selects the DbCommand overload without allocating a closure.
await c.ExecuteReaderAsync(
(Func<DbDataReader, ValueTask>)handler,
behavior, cancellationToken)
.ConfigureAwait(false);
return;
}

Expand Down Expand Up @@ -322,7 +326,11 @@ public static ValueTask<T> ExecuteReaderAsync<T>(this IDbCommand command,
Contract.EndContractBlock();

return command is DbCommand c
? ExecuteReaderAsync(c, reader => transform(reader), behavior, cancellationToken)
// The cast selects the DbCommand overload without allocating a closure.
? ExecuteReaderAsync(
c,
(Func<DbDataReader, ValueTask<T>>)transform,
behavior, cancellationToken)
: ExecuteReaderAsyncCore(command, transform, behavior);

static async ValueTask<T> ExecuteReaderAsyncCore(IDbCommand command, Func<IDataReader, ValueTask<T>> transform, CommandBehavior behavior)
Expand Down
8 changes: 6 additions & 2 deletions Source/Core/Extensions/Transaction.cs
Original file line number Diff line number Diff line change
Expand Up @@ -242,8 +242,12 @@ public static async ValueTask ExecuteTransactionAsync(
Contract.EndContractBlock();

await connection
.ExecuteTransactionAsync(
async c => { await action(c).ConfigureAwait(false); return true; },
.ExecuteTransactionConditionalAsync(
async t =>
{
await action(t).ConfigureAwait(false);
return (true, true);
},
isolationLevel, cancellationToken)
.ConfigureAwait(false);
}
Expand Down
3 changes: 0 additions & 3 deletions Source/Core/IDbConnectionPool.cs
Original file line number Diff line number Diff line change
Expand Up @@ -80,9 +80,6 @@ private readonly IDbConnectionPool _source
public IDbConnection Take()
=> _source.Take();

IDbConnection IDbConnectionPool.Take()
=> _source.Take();

/// <inheritdoc />
public void Give(IDbConnection connection)
=> _source.Give(connection);
Expand Down
19 changes: 7 additions & 12 deletions Source/Generator/ModelReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -310,15 +310,14 @@ static bool DeclaresNullPolicy(INamedTypeSymbol t)
{
if (HasAttribute(c.GetAttributes(), NullPolicyAttribute)) return true;

// Neither attribute can be put on a field.
foreach (ISymbol m in c.GetMembers())
{
ImmutableArray<AttributeData> attributes = m switch
if (m is IPropertySymbol p
&& HasNullAttribute(p.GetAttributes()))
{
IPropertySymbol p => p.GetAttributes(),
IFieldSymbol f => f.GetAttributes(),
_ => [],
};
if (HasNullAttribute(attributes)) return true;
return true;
}
}
}

Expand Down Expand Up @@ -463,12 +462,8 @@ static bool IsRetired(ISymbol? member)
&& a.ConstructorArguments.Length == 2 && a.ConstructorArguments[1].Value is true) == true;

static bool HasAttribute(ImmutableArray<AttributeData> attributes, string fullName)
{
foreach (AttributeData a in attributes)
if (a.AttributeClass is { } c && FullName(c) == fullName) return true;

return false;
}
=> attributes.Any(
a => a.AttributeClass is { } c && FullName(c) == fullName);

// The metadata full name (namespace + nested types + arity), as reflection's Type.FullName gives it for a non-generic or definition type.
public static string FullName(ITypeSymbol t)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -146,4 +146,43 @@ public static async Task ExecuteReaderAsync_ClosedConnection_RequestsCloseConnec
}

#endregion

#region An IDbCommand that is a DbCommand

// The IDbCommand overloads hand a DbCommand to the DbCommand overloads
// with a delegate cast, which picks them without a closure.
[Fact]
public static async Task ExecuteReaderAsync_OnADbCommandBehindIDbCommand_CallsTheHandlerOncePerCall()
{
CancellationToken token = TestContext.Current.CancellationToken;
FakeDbConnection connection = new();
connection.SetState(ConnectionState.Open);
IDbCommand command = new FakeDbCommand(
connection, () => new CountingReader(3));
int handled = 0;

await command.ExecuteReaderAsync(
reader =>
{
Assert.IsType<DbDataReader>(reader, exactMatch: false);
handled++;
return default;
},
CommandBehavior.Default,
token);
int fields = await command.ExecuteReaderAsync(
reader =>
{
Assert.IsType<DbDataReader>(reader, exactMatch: false);
handled++;
return new ValueTask<int>(reader.FieldCount);
},
CommandBehavior.Default,
token);

Assert.Equal(2, handled);
Assert.Equal(1, fields);
}

#endregion
}
Loading