Skip to content
Open
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
namespace Thinktecture.EntityFrameworkCore.BulkOperations;

/// <summary>
/// One row that a bulk operation returned from the database (<c>RETURNING</c>).
/// Use it in the projection of <c>BulkInsertOrUpdateAsync</c> and <c>BulkUpdateAsync</c> to select the columns to return:
/// <c>output => new { output.Inserted.Id, output.Inserted.Name }</c>.
/// </summary>
/// <typeparam name="T">Type of the entity.</typeparam>
public sealed class BulkOperationOutput<T>
where T : class
{
/// <summary>
/// The row after the operation.
/// </summary>
/// <remarks>
/// Only the properties that the projection reads are loaded; the other properties keep their default values.
/// </remarks>
public T Inserted { get; internal set; } = null!;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
using System.Linq.Expressions;

namespace Thinktecture.EntityFrameworkCore.BulkOperations;

/// <summary>
/// Executes bulk operations that return the affected rows (<c>RETURNING</c>).
/// </summary>
public interface IBulkOperationOutputExecutor
{
/// <summary>
/// Updates <paramref name="entities"/> that are in the table, the rest will be inserted, and returns the rows selected by <paramref name="output"/>.
/// </summary>
/// <param name="entities">Entities to insert or update.</param>
/// <param name="options">Options.</param>
/// <param name="output">Selects the result, for example <c>row => new { row.Inserted.Id }</c>.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <typeparam name="T">Entity type.</typeparam>
/// <typeparam name="TResult">Type of the result.</typeparam>
/// <returns>One result per inserted or updated row. The order is not defined.</returns>
Task<List<TResult>> BulkInsertOrUpdateAsync<T, TResult>(
IEnumerable<T> entities,
IBulkInsertOrUpdateOptions options,
Expression<Func<BulkOperationOutput<T>, TResult>> output,
CancellationToken cancellationToken = default)
where T : class;

/// <summary>
/// Updates <paramref name="entities"/> that are in the table and returns the rows selected by <paramref name="output"/>.
/// </summary>
/// <param name="entities">Entities to update.</param>
/// <param name="options">Options.</param>
/// <param name="output">Selects the result, for example <c>row => new { row.Inserted.Id }</c>.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <typeparam name="T">Entity type.</typeparam>
/// <typeparam name="TResult">Type of the result.</typeparam>
/// <returns>One result per updated row. The order is not defined.</returns>
Task<List<TResult>> BulkUpdateAsync<T, TResult>(
IEnumerable<T> entities,
IBulkUpdateOptions options,
Expression<Func<BulkOperationOutput<T>, TResult>> output,
CancellationToken cancellationToken = default)
where T : class;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,295 @@
using System.Data.Common;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;

namespace Thinktecture.EntityFrameworkCore.BulkOperations.Internal;

/// <summary>
/// Describes a column that a bulk operation returns from the database.
/// This is an internal API. It may be changed or removed without notice.
/// </summary>
/// <param name="ColumnName">The name of the column.</param>
/// <param name="StoreType">The store type of the column.</param>
public readonly record struct BulkOperationOutputColumn(string ColumnName, string StoreType);

/// <summary>
/// Materializes the entities of the rows that a bulk operation returns from the database.
/// This is an internal API. It may be changed or removed without notice.
/// </summary>
/// <remarks>
/// The columns are the properties that the projection reads, followed by the discriminator column if the entity type has derived types.
/// The discriminator decides which type is created, because the type that is stored in the database can differ from the type of the input.
/// A database NULL resets the property, so values that the constructor assigned do not survive.
/// </remarks>
/// <typeparam name="T">Type of the entity.</typeparam>
public sealed class BulkOperationOutputMapper<T>
where T : class
{
private readonly Column[] _columns;
private readonly int _discriminatorIndex;
private readonly Dictionary<object, ConcreteType> _concreteTypes;
private readonly ConcreteType _fallback;

/// <summary>
/// The columns to return, in the order in which <see cref="Read"/> reads them.
/// </summary>
public IReadOnlyList<BulkOperationOutputColumn> Columns { get; }

private BulkOperationOutputMapper(Column[] columns, int discriminatorIndex, Dictionary<object, ConcreteType> concreteTypes, ConcreteType fallback)
{
_columns = columns;
_discriminatorIndex = discriminatorIndex;
_concreteTypes = concreteTypes;
_fallback = fallback;
Columns = columns.Select(static column => new BulkOperationOutputColumn(column.ColumnName, column.StoreType)).ToList();
}

/// <summary>
/// Creates the mapper.
/// </summary>
/// <param name="entityType">The entity type of the table.</param>
/// <param name="storeObject">The table.</param>
/// <param name="all">Indication whether all properties are read, i.e. the projection uses the whole entity.</param>
/// <param name="memberNames">The names of the properties that the projection reads.</param>
/// <returns>The mapper.</returns>
/// <exception cref="NotSupportedException">A member is not a scalar property that is mapped to a column of the table.</exception>
public static BulkOperationOutputMapper<T> Create(
IEntityType entityType,
StoreObjectIdentifier storeObject,
bool all,
IReadOnlyCollection<string> memberNames)
{
ArgumentNullException.ThrowIfNull(entityType);
ArgumentNullException.ThrowIfNull(memberNames);

// The members are validated even if the whole entity is read, so that a projection like "new { Entity = row.Inserted, row.Inserted.Parent }" is rejected.
var members = memberNames.Select(name => entityType.FindProperty(name) is { } property && property.GetColumnName(storeObject) is not null
? property
: throw new NotSupportedException($"'{name}' is not a scalar property of the entity '{entityType.DisplayName()}' that is mapped to a column of table '{storeObject.Name}'. Only such properties can be selected from the returned row."))
.ToList();

if (all)
EnsureNoUnsupportedMembers(entityType, storeObject);

var properties = all
? GetAllProperties(entityType, storeObject)
: members;

var discriminator = entityType.GetDerivedTypes().Any() ? entityType.FindDiscriminatorProperty() : null;
var columns = properties.Select(property => new Column(property, storeObject, requireSetter: true)).ToList();
var discriminatorIndex = -1;

if (discriminator is not null)
{
discriminatorIndex = properties.IndexOf(discriminator);

if (discriminatorIndex < 0)
{
discriminatorIndex = columns.Count;
columns.Add(new Column(discriminator, storeObject, requireSetter: false));
}
}

var concreteTypes = new Dictionary<object, ConcreteType>();
var hierarchy = entityType.GetDerivedTypesInclusive().Where(static type => !type.IsAbstract()).ToList();

ConcreteType? fallback = null;

foreach (var type in hierarchy)
{
var concreteType = new ConcreteType(type, columns.Select(column => column.IsDeclaredOn(type)).ToArray());
fallback ??= concreteType;

if (type == entityType)
fallback = concreteType;

if (discriminator is not null && type.GetDiscriminatorValue() is { } value)
concreteTypes[value] = concreteType;
}

return new BulkOperationOutputMapper<T>(columns.ToArray(),
discriminatorIndex,
concreteTypes,
fallback ?? throw new InvalidOperationException($"The entity type '{entityType.DisplayName()}' and its derived types are abstract, so no entity can be created."));
}

/// <summary>
/// Reads an entity from the current row of <paramref name="reader"/>.
/// </summary>
/// <param name="reader">The reader, positioned on a row.</param>
/// <param name="firstOrdinal">The ordinal of the first column of the entity.</param>
/// <returns>The entity.</returns>
public T Read(DbDataReader reader, int firstOrdinal)
{
ArgumentNullException.ThrowIfNull(reader);

var concreteType = GetConcreteType(reader, firstOrdinal);
var entity = concreteType.Create();

for (var i = 0; i < _columns.Length; i++)
{
if (!concreteType.IsColumnOfType[i])
continue;

_columns[i].Apply(entity, reader, firstOrdinal + i);
}

return (T)entity;
}

private ConcreteType GetConcreteType(DbDataReader reader, int firstOrdinal)
{
if (_discriminatorIndex < 0)
return _fallback;

var column = _columns[_discriminatorIndex];

// The deleted columns of an inserted row are NULL.
if (reader.IsDBNull(firstOrdinal + _discriminatorIndex))
return _fallback;

var value = column.ReadValue(reader, firstOrdinal + _discriminatorIndex)!;

return _concreteTypes.TryGetValue(value, out var concreteType)
? concreteType
: throw new InvalidOperationException($"The discriminator value '{value}' returned by the database does not belong to an entity type of the hierarchy of '{typeof(T).Name}'.");
}

// The whole entity has the scalar properties only. Complex properties and owned types that are stored in the table would be missing
// in the returned entity, so the projection must select their scalar properties explicitly.
private static void EnsureNoUnsupportedMembers(IEntityType entityType, StoreObjectIdentifier storeObject)
{
// The members of the base types are inherited, the members of the derived types are declared on them.
var complexProperty = entityType.GetComplexProperties()
.Concat(entityType.GetDerivedTypes().SelectMany(static type => type.GetDeclaredComplexProperties()))
.FirstOrDefault();

if (complexProperty is not null)
throw new NotSupportedException($"The entity '{entityType.DisplayName()}' has the complex property '{complexProperty.Name}', which cannot be returned as part of the whole entity. Select the scalar properties that are needed instead.");

var ownedType = entityType.GetNavigations()
.Concat(entityType.GetDerivedTypes().SelectMany(static type => type.GetDeclaredNavigations()))
.FirstOrDefault(navigation => navigation.ForeignKey.IsOwnership && navigation.TargetEntityType.GetTableName() == storeObject.Name);

if (ownedType is not null)
throw new NotSupportedException($"The entity '{entityType.DisplayName()}' has the owned type '{ownedType.Name}' that is stored in the same table, which cannot be returned as part of the whole entity. Select the scalar properties that are needed instead.");
}

private static List<IProperty> GetAllProperties(IEntityType entityType, StoreObjectIdentifier storeObject)
{
return entityType.GetProperties()
.Concat(entityType.GetDerivedTypes().SelectMany(static type => type.GetDeclaredProperties()))
.Where(property => !property.IsShadowProperty() && property.GetColumnName(storeObject) is not null)
.ToList();
}

private sealed class ConcreteType
{
private readonly Func<object> _create;

// Indication per column whether the property belongs to this type, i.e. the property is declared on the type or on one of its base types.
public bool[] IsColumnOfType { get; }

public ConcreteType(IEntityType entityType, bool[] isColumnOfType)
{
IsColumnOfType = isColumnOfType;

var constructor = entityType.ClrType.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, Type.EmptyTypes);

// The properties that are not read keep their default values, so the constructor is not required.
_create = constructor is null
? () => RuntimeHelpers.GetUninitializedObject(entityType.ClrType)
: Expression.Lambda<Func<object>>(Expression.Convert(Expression.New(constructor), typeof(object))).Compile();
}

public object Create() => _create();
}

private sealed class Column
{
private readonly IProperty _property;
private readonly ValueConverter? _converter;
private readonly Func<DbDataReader, int, object?> _read;
private readonly Action<object, object?>? _setter;
private readonly object? _nullValue;

public string ColumnName { get; }
public string StoreType { get; }

public Column(IProperty property, StoreObjectIdentifier storeObject, bool requireSetter)
{
var typeMapping = property.GetRelationalTypeMapping();

_property = property;
_converter = typeMapping.Converter;
_read = CreateReader(typeMapping);
_setter = CreateSetter(property);

if (_setter is null && requireSetter)
throw new InvalidOperationException($"The property '{property.DeclaringType.DisplayName()}.{property.Name}' has neither a setter nor a backing field, so it cannot be selected from the returned row.");

// A reference type and a nullable value type are reset to null, any other value type to its default value.
_nullValue = property.ClrType.IsValueType && Nullable.GetUnderlyingType(property.ClrType) is null
? Activator.CreateInstance(property.ClrType)
: null;

ColumnName = property.GetColumnName(storeObject)!;
StoreType = property.GetColumnType(storeObject) ?? typeMapping.StoreType;
}

public bool IsDeclaredOn(IEntityType entityType)
{
return _property.DeclaringType is IEntityType declaringType && declaringType.IsAssignableFrom(entityType);
}

public object? ReadValue(DbDataReader reader, int ordinal)
{
var value = _read(reader, ordinal);

return _converter is null ? value : _converter.ConvertFromProvider(value);
}

public void Apply(object entity, DbDataReader reader, int ordinal)
{
// The discriminator is selected to find the type. It is a shadow property if it has no setter.
if (_setter is null)
return;

_setter(entity, reader.IsDBNull(ordinal) ? _nullValue : ReadValue(reader, ordinal));
}

// The setter or the backing field may be private, the setter may be init-only.
private static Action<object, object?>? CreateSetter(IProperty property)
{
if (property.PropertyInfo?.SetMethod is { } setMethod)
{
var instance = Expression.Parameter(typeof(object));
var value = Expression.Parameter(typeof(object));
var call = Expression.Call(Expression.Convert(instance, setMethod.DeclaringType!), setMethod, Expression.Convert(value, setMethod.GetParameters()[0].ParameterType));

return Expression.Lambda<Action<object, object?>>(call, instance, value).Compile();
}

return property.FieldInfo is { } field ? field.SetValue : null;
}

private static Func<DbDataReader, int, object?> CreateReader(RelationalTypeMapping typeMapping)
{
var reader = Expression.Parameter(typeof(DbDataReader));
var ordinal = Expression.Parameter(typeof(int));
var method = typeMapping.GetDataReaderMethod();

// Some methods are declared on the reader of the provider, e.g. SqlDataReader.GetDateTimeOffset.
Expression instance = method.DeclaringType!.IsAssignableFrom(typeof(DbDataReader))
? reader
: Expression.Convert(reader, method.DeclaringType);
var call = Expression.Call(instance, method, ordinal);

return Expression.Lambda<Func<DbDataReader, int, object?>>(Expression.Convert(call, typeof(object)), reader, ordinal).Compile();
}
}
}
Loading
Loading