diff --git a/src/Thinktecture.EntityFrameworkCore.BulkOperations/EntityFrameworkCore/BulkOperations/BulkOperationOutput.cs b/src/Thinktecture.EntityFrameworkCore.BulkOperations/EntityFrameworkCore/BulkOperations/BulkOperationOutput.cs new file mode 100644 index 00000000..0b62f8aa --- /dev/null +++ b/src/Thinktecture.EntityFrameworkCore.BulkOperations/EntityFrameworkCore/BulkOperations/BulkOperationOutput.cs @@ -0,0 +1,19 @@ +namespace Thinktecture.EntityFrameworkCore.BulkOperations; + +/// +/// One row that a bulk operation returned from the database (RETURNING). +/// Use it in the projection of BulkInsertOrUpdateAsync and BulkUpdateAsync to select the columns to return: +/// output => new { output.Inserted.Id, output.Inserted.Name }. +/// +/// Type of the entity. +public sealed class BulkOperationOutput + where T : class +{ + /// + /// The row after the operation. + /// + /// + /// Only the properties that the projection reads are loaded; the other properties keep their default values. + /// + public T Inserted { get; internal set; } = null!; +} diff --git a/src/Thinktecture.EntityFrameworkCore.BulkOperations/EntityFrameworkCore/BulkOperations/IBulkOperationOutputExecutor.cs b/src/Thinktecture.EntityFrameworkCore.BulkOperations/EntityFrameworkCore/BulkOperations/IBulkOperationOutputExecutor.cs new file mode 100644 index 00000000..c516b941 --- /dev/null +++ b/src/Thinktecture.EntityFrameworkCore.BulkOperations/EntityFrameworkCore/BulkOperations/IBulkOperationOutputExecutor.cs @@ -0,0 +1,43 @@ +using System.Linq.Expressions; + +namespace Thinktecture.EntityFrameworkCore.BulkOperations; + +/// +/// Executes bulk operations that return the affected rows (RETURNING). +/// +public interface IBulkOperationOutputExecutor +{ + /// + /// Updates that are in the table, the rest will be inserted, and returns the rows selected by . + /// + /// Entities to insert or update. + /// Options. + /// Selects the result, for example row => new { row.Inserted.Id }. + /// Cancellation token. + /// Entity type. + /// Type of the result. + /// One result per inserted or updated row. The order is not defined. + Task> BulkInsertOrUpdateAsync( + IEnumerable entities, + IBulkInsertOrUpdateOptions options, + Expression, TResult>> output, + CancellationToken cancellationToken = default) + where T : class; + + /// + /// Updates that are in the table and returns the rows selected by . + /// + /// Entities to update. + /// Options. + /// Selects the result, for example row => new { row.Inserted.Id }. + /// Cancellation token. + /// Entity type. + /// Type of the result. + /// One result per updated row. The order is not defined. + Task> BulkUpdateAsync( + IEnumerable entities, + IBulkUpdateOptions options, + Expression, TResult>> output, + CancellationToken cancellationToken = default) + where T : class; +} diff --git a/src/Thinktecture.EntityFrameworkCore.BulkOperations/EntityFrameworkCore/BulkOperations/Internal/BulkOperationOutputMapper.cs b/src/Thinktecture.EntityFrameworkCore.BulkOperations/EntityFrameworkCore/BulkOperations/Internal/BulkOperationOutputMapper.cs new file mode 100644 index 00000000..23d3c7e5 --- /dev/null +++ b/src/Thinktecture.EntityFrameworkCore.BulkOperations/EntityFrameworkCore/BulkOperations/Internal/BulkOperationOutputMapper.cs @@ -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; + +/// +/// Describes a column that a bulk operation returns from the database. +/// This is an internal API. It may be changed or removed without notice. +/// +/// The name of the column. +/// The store type of the column. +public readonly record struct BulkOperationOutputColumn(string ColumnName, string StoreType); + +/// +/// 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. +/// +/// +/// 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. +/// +/// Type of the entity. +public sealed class BulkOperationOutputMapper + where T : class +{ + private readonly Column[] _columns; + private readonly int _discriminatorIndex; + private readonly Dictionary _concreteTypes; + private readonly ConcreteType _fallback; + + /// + /// The columns to return, in the order in which reads them. + /// + public IReadOnlyList Columns { get; } + + private BulkOperationOutputMapper(Column[] columns, int discriminatorIndex, Dictionary concreteTypes, ConcreteType fallback) + { + _columns = columns; + _discriminatorIndex = discriminatorIndex; + _concreteTypes = concreteTypes; + _fallback = fallback; + Columns = columns.Select(static column => new BulkOperationOutputColumn(column.ColumnName, column.StoreType)).ToList(); + } + + /// + /// Creates the mapper. + /// + /// The entity type of the table. + /// The table. + /// Indication whether all properties are read, i.e. the projection uses the whole entity. + /// The names of the properties that the projection reads. + /// The mapper. + /// A member is not a scalar property that is mapped to a column of the table. + public static BulkOperationOutputMapper Create( + IEntityType entityType, + StoreObjectIdentifier storeObject, + bool all, + IReadOnlyCollection 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(); + 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(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.")); + } + + /// + /// Reads an entity from the current row of . + /// + /// The reader, positioned on a row. + /// The ordinal of the first column of the entity. + /// The entity. + 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 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 _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>(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 _read; + private readonly Action? _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? 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>(call, instance, value).Compile(); + } + + return property.FieldInfo is { } field ? field.SetValue : null; + } + + private static Func 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>(Expression.Convert(call, typeof(object)), reader, ordinal).Compile(); + } + } +} diff --git a/src/Thinktecture.EntityFrameworkCore.BulkOperations/EntityFrameworkCore/BulkOperations/Internal/BulkOperationReturningProjection.cs b/src/Thinktecture.EntityFrameworkCore.BulkOperations/EntityFrameworkCore/BulkOperations/Internal/BulkOperationReturningProjection.cs new file mode 100644 index 00000000..a5fe5ee2 --- /dev/null +++ b/src/Thinktecture.EntityFrameworkCore.BulkOperations/EntityFrameworkCore/BulkOperations/Internal/BulkOperationReturningProjection.cs @@ -0,0 +1,132 @@ +using System.Data.Common; +using System.Linq.Expressions; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Storage; + +namespace Thinktecture.EntityFrameworkCore.BulkOperations.Internal; + +/// +/// Translates the projection of a bulk operation result to the columns of a RETURNING clause and materializes the returned rows. +/// This is an internal API. It may be changed or removed without notice. +/// +/// Type of the entity. +/// Type of the result. +public sealed class BulkOperationReturningProjection + where T : class +{ + private readonly BulkOperationOutputMapper _mapper; + private readonly Func, TResult> _projection; + + /// + /// The names of the columns to return, in the order in which reads them. + /// + public IReadOnlyList ColumnNames { get; } + + private BulkOperationReturningProjection(BulkOperationOutputMapper mapper, Func, TResult> projection) + { + _mapper = mapper; + _projection = projection; + ColumnNames = mapper.Columns.Select(static column => column.ColumnName).ToList(); + } + + /// + /// Creates the projection. + /// + /// The entity type of the table. + /// The projection of the result. + /// The projection. + /// reads a member that is not a scalar property mapped to a column. + public static BulkOperationReturningProjection Create(IEntityType entityType, Expression, TResult>> output) + { + ArgumentNullException.ThrowIfNull(entityType); + ArgumentNullException.ThrowIfNull(output); + + var storeObject = StoreObjectIdentifier.Create(entityType, StoreObjectType.Table) + ?? throw new InvalidOperationException($"Could not create StoreObjectIdentifier for table '{entityType.Name}'."); + + var collector = new MemberCollector(output.Parameters[0]); + collector.Visit(output.Body); + + var members = collector.Members; + + // A statement without a column to return is invalid. The projection reads nothing from the row, so any column is good enough. + if (members.Count == 0 && !collector.All) + members = [(entityType.FindPrimaryKey()?.Properties[0] ?? entityType.GetProperties().First(property => property.GetColumnName(storeObject) is not null)).Name]; + + return new BulkOperationReturningProjection(BulkOperationOutputMapper.Create(entityType, storeObject, collector.All, members), output.Compile()); + } + + /// + /// Reads the current row of . The columns are read by position, in the order of . + /// + /// The reader, positioned on a row. + /// The result of the projection. + public TResult Read(DbDataReader reader) + { + ArgumentNullException.ThrowIfNull(reader); + + return _projection(new BulkOperationOutput { Inserted = _mapper.Read(reader, 0) }); + } + + /// + /// Reads all rows of . + /// + /// The reader. + /// Cancellation token. + /// The results of the projection. + public async Task> ReadAllAsync(DbDataReader reader, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(reader); + + var results = new List(); + + while (await reader.ReadAsync(cancellationToken).ConfigureAwait(false)) + { + results.Add(Read(reader)); + } + + return results; + } + + // Collects the members of "output.Inserted" that the projection reads. + private sealed class MemberCollector(ParameterExpression parameter) : ExpressionVisitor + { + public HashSet Members { get; } = []; + public bool All { get; private set; } + + protected override Expression VisitMember(MemberExpression node) + { + // output.Inserted.Name + if (IsInserted(node.Expression)) + { + Members.Add(node.Member.Name); + return node; + } + + // output.Inserted: the whole entity + if (IsInserted(node)) + { + All = true; + return node; + } + + return base.VisitMember(node); + } + + protected override Expression VisitParameter(ParameterExpression node) + { + // The output row is used as a whole, for example passed to a method: load everything. + if (node == parameter) + All = true; + + return node; + } + + private bool IsInserted(Expression? expression) + { + return expression is MemberExpression { Expression: ParameterExpression owner } member + && owner == parameter + && member.Member.Name == nameof(BulkOperationOutput.Inserted); + } + } +} diff --git a/src/Thinktecture.EntityFrameworkCore.BulkOperations/Extensions/BulkOperationsDbContextExtensions.cs b/src/Thinktecture.EntityFrameworkCore.BulkOperations/Extensions/BulkOperationsDbContextExtensions.cs index cf7120ed..72c3c0da 100644 --- a/src/Thinktecture.EntityFrameworkCore.BulkOperations/Extensions/BulkOperationsDbContextExtensions.cs +++ b/src/Thinktecture.EntityFrameworkCore.BulkOperations/Extensions/BulkOperationsDbContextExtensions.cs @@ -1,5 +1,6 @@ using System.Linq.Expressions; using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.Extensions.DependencyInjection; using Thinktecture.EntityFrameworkCore.BulkOperations; using Thinktecture.EntityFrameworkCore.Parameters; using Thinktecture.EntityFrameworkCore.TempTables; @@ -199,6 +200,67 @@ public static async Task BulkInsertOrUpdateAsync( .BulkInsertOrUpdateAsync(entities, options, cancellationToken).ConfigureAwait(false); } + /// + /// Updates that are in the table, the rest will be inserted, and returns the rows selected by (RETURNING). + /// + /// Database context. + /// Entities to insert or update. + /// Options. + /// + /// Selects the result, for example row => new { row.Inserted.Id, row.Inserted.Name }. row.Inserted is the row after the operation. + /// Only the properties that the expression reads are requested from the database. + /// + /// Cancellation token. + /// One result per inserted or updated row. The order is not defined, it is not the order of . + /// Entity type. + /// Type of the result. + /// , , or is null. + /// The database provider cannot return the rows of a bulk operation, or reads a member that is not a scalar property mapped to a column. + public static Task> BulkInsertOrUpdateAsync( + this DbContext ctx, + IEnumerable entities, + IBulkInsertOrUpdateOptions options, + Expression, TResult>> output, + CancellationToken cancellationToken = default) + where T : class + { + return GetOutputExecutor(ctx).BulkInsertOrUpdateAsync(entities, options, output, cancellationToken); + } + + /// + /// Updates that are in the table and returns the rows selected by (RETURNING). + /// + /// Database context. + /// Entities to update. + /// Options. + /// + /// Selects the result, for example row => new { row.Inserted.Id, row.Inserted.Name }. row.Inserted is the row after the operation. + /// Only the properties that the expression reads are requested from the database. + /// + /// Cancellation token. + /// One result per updated row. The order is not defined, it is not the order of . + /// Entity type. + /// Type of the result. + /// , , or is null. + /// The database provider cannot return the rows of a bulk operation, or reads a member that is not a scalar property mapped to a column. + public static Task> BulkUpdateAsync( + this DbContext ctx, + IEnumerable entities, + IBulkUpdateOptions options, + Expression, TResult>> output, + CancellationToken cancellationToken = default) + where T : class + { + return GetOutputExecutor(ctx).BulkUpdateAsync(entities, options, output, cancellationToken); + } + + private static IBulkOperationOutputExecutor GetOutputExecutor(DbContext ctx) + { + ArgumentNullException.ThrowIfNull(ctx); + + return ((IInfrastructure)ctx).Instance.GetService() + ?? throw new NotSupportedException("The database provider of the context cannot return the rows of a bulk operation."); + } /// /// Copies into a temp table and returns the query for accessing the inserted records. /// diff --git a/src/Thinktecture.EntityFrameworkCore.BulkOperations/Extensions/Internal/BulkOperationsSqlExecutor.cs b/src/Thinktecture.EntityFrameworkCore.BulkOperations/Extensions/Internal/BulkOperationsSqlExecutor.cs index 16b55a99..1e78cb22 100644 --- a/src/Thinktecture.EntityFrameworkCore.BulkOperations/Extensions/Internal/BulkOperationsSqlExecutor.cs +++ b/src/Thinktecture.EntityFrameworkCore.BulkOperations/Extensions/Internal/BulkOperationsSqlExecutor.cs @@ -1,5 +1,6 @@ using System.Collections.ObjectModel; using System.ComponentModel; +using System.Data.Common; using System.Diagnostics.CodeAnalysis; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Infrastructure; @@ -32,6 +33,50 @@ public static Task ExecuteNonQueryAsync(DatabaseFacade database, string sql return ExecuteNonQueryAsync(database, database.GetService().Build(sql), ReadOnlyDictionary.Empty, cancellationToken); } + /// + /// Executes a statement without parameters and reads its result with . + /// The text is sent unchanged, see . + /// The statement runs through the command pipeline of EF Core, so logging, interceptors, the current transaction and the command timeout of the context apply. + /// + /// The database facade of the context. + /// The statement. + /// Reads the result; the reader is disposed afterwards. + /// Cancellation token. + /// Type of the result. + /// The result of . + /// , or is null. + [SuppressMessage("Usage", "EF1001", MessageId = "Internal EF Core API usage.")] + public static async Task ExecuteReaderAsync( + DatabaseFacade database, + string sql, + Func> readAsync, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(database); + ArgumentNullException.ThrowIfNull(sql); + ArgumentNullException.ThrowIfNull(readAsync); + + var accessor = (IDatabaseFacadeDependenciesAccessor)database; + var dependencies = (IRelationalDatabaseFacadeDependencies)accessor.Dependencies; + var criticalSection = dependencies.CoreOptions.AreThreadSafetyChecksEnabled ? dependencies.ConcurrencyDetector.EnterCriticalSection() : (ConcurrencyDetectorCriticalSectionDisposer?)null; + + try + { + var command = database.GetService().Build(sql); + var parameterObject = new RelationalCommandParameterObject(dependencies.RelationalConnection, ReadOnlyDictionary.Empty, null, accessor.Context, dependencies.CommandLogger, CommandSource.ExecuteSqlRaw); + var reader = await command.ExecuteReaderAsync(parameterObject, cancellationToken).ConfigureAwait(false); + + await using (reader.ConfigureAwait(false)) + { + return await readAsync(reader.DbDataReader, cancellationToken).ConfigureAwait(false); + } + } + finally + { + criticalSection?.Dispose(); + } + } + /// /// Executes a command. Same as ExecuteSqlRawAsync, but with a command and the parameter values of EF Core. /// diff --git a/src/Thinktecture.EntityFrameworkCore.PostgreSQL/EntityFrameworkCore/BulkOperations/NpgsqlBulkOperationExecutor.Returning.cs b/src/Thinktecture.EntityFrameworkCore.PostgreSQL/EntityFrameworkCore/BulkOperations/NpgsqlBulkOperationExecutor.Returning.cs new file mode 100644 index 00000000..762ec985 --- /dev/null +++ b/src/Thinktecture.EntityFrameworkCore.PostgreSQL/EntityFrameworkCore/BulkOperations/NpgsqlBulkOperationExecutor.Returning.cs @@ -0,0 +1,57 @@ +using System.Linq.Expressions; +using Thinktecture.EntityFrameworkCore.BulkOperations.Internal; +using Thinktecture.Internal; + +namespace Thinktecture.EntityFrameworkCore.BulkOperations; + +public sealed partial class NpgsqlBulkOperationExecutor +{ + /// + public async Task> BulkInsertOrUpdateAsync( + IEnumerable entities, + IBulkInsertOrUpdateOptions options, + Expression, TResult>> output, + CancellationToken cancellationToken = default) + where T : class + { + ArgumentNullException.ThrowIfNull(entities); + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(output); + + if (options is not NpgsqlBulkInsertOrUpdateOptions npgsqlOptions) + npgsqlOptions = new NpgsqlBulkInsertOrUpdateOptions(options); + + var projection = BulkOperationReturningProjection.Create(_ctx.Model.GetEntityTypeOrTempTableEntityType(), output); + + return await BulkInsertOrUpdateAsync(entities, npgsqlOptions, projection.ColumnNames, (statement, token) => ExecuteReaderAsync(projection, statement, token), cancellationToken); + } + + /// + public async Task> BulkUpdateAsync( + IEnumerable entities, + IBulkUpdateOptions options, + Expression, TResult>> output, + CancellationToken cancellationToken = default) + where T : class + { + ArgumentNullException.ThrowIfNull(entities); + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(output); + + if (options is not NpgsqlBulkUpdateOptions npgsqlOptions) + npgsqlOptions = new NpgsqlBulkUpdateOptions(options); + + var projection = BulkOperationReturningProjection.Create(_ctx.Model.GetEntityTypeOrTempTableEntityType(), output); + + return await BulkUpdateAsync(entities, npgsqlOptions, projection.ColumnNames, (statement, token) => ExecuteReaderAsync(projection, statement, token), cancellationToken); + } + + private Task> ExecuteReaderAsync( + BulkOperationReturningProjection projection, + string statement, + CancellationToken cancellationToken) + where T : class + { + return BulkOperationsSqlExecutor.ExecuteReaderAsync(_ctx.Database, statement, projection.ReadAllAsync, cancellationToken); + } +} diff --git a/src/Thinktecture.EntityFrameworkCore.PostgreSQL/EntityFrameworkCore/BulkOperations/NpgsqlBulkOperationExecutor.cs b/src/Thinktecture.EntityFrameworkCore.PostgreSQL/EntityFrameworkCore/BulkOperations/NpgsqlBulkOperationExecutor.cs index 8e68497d..6144f792 100644 --- a/src/Thinktecture.EntityFrameworkCore.PostgreSQL/EntityFrameworkCore/BulkOperations/NpgsqlBulkOperationExecutor.cs +++ b/src/Thinktecture.EntityFrameworkCore.PostgreSQL/EntityFrameworkCore/BulkOperations/NpgsqlBulkOperationExecutor.cs @@ -23,7 +23,7 @@ namespace Thinktecture.EntityFrameworkCore.BulkOperations; [SuppressMessage("Usage", "EF1001:Internal EF Core API usage.")] public sealed partial class NpgsqlBulkOperationExecutor : IBulkInsertExecutor, ITempTableBulkInsertExecutor, IBulkUpdateExecutor, - IBulkInsertOrUpdateExecutor, INpgsqlTruncateTableExecutor + IBulkInsertOrUpdateExecutor, INpgsqlTruncateTableExecutor, IBulkOperationOutputExecutor { private readonly DbContext _ctx; private readonly IDiagnosticsLogger _logger; @@ -516,10 +516,20 @@ public async Task BulkUpdateAsync( if (options is not NpgsqlBulkUpdateOptions npgsqlOptions) npgsqlOptions = new NpgsqlBulkUpdateOptions(options); - return await BulkUpdateAsync(entities, npgsqlOptions, cancellationToken); + return await BulkUpdateAsync(entities, npgsqlOptions, null, ExecuteStatementAsync, cancellationToken); } - private async Task BulkUpdateAsync(IEnumerable entities, NpgsqlBulkUpdateOptions options, CancellationToken cancellationToken) + private Task ExecuteStatementAsync(string statement, CancellationToken cancellationToken) + { + return BulkOperationsSqlExecutor.ExecuteNonQueryAsync(_ctx.Database, statement, cancellationToken); + } + + private async Task BulkUpdateAsync( + IEnumerable entities, + NpgsqlBulkUpdateOptions options, + IReadOnlyList? returningColumns, + Func> executeAsync, + CancellationToken cancellationToken) where T : class { var entityType = _ctx.Model.GetEntityTypeOrTempTableEntityType(); @@ -533,9 +543,9 @@ private async Task BulkUpdateAsync(IEnumerable entities, NpgsqlBulkUp var tempTableOptions = options.GetTempTableBulkInsertOptions(); await using var tempTable = await BulkInsertIntoTempTableAsync(entities, tempTableOptions, cancellationToken); - var updateStatement = CreateUpdateCommand(entityType, tableName.Schema, tableName.Name, tempTable.Name, propertiesForUpdate, options.KeyProperties.DetermineKeyProperties(entityType)); + var updateStatement = CreateUpdateCommand(entityType, tableName.Schema, tableName.Name, tempTable.Name, propertiesForUpdate, options.KeyProperties.DetermineKeyProperties(entityType), returningColumns); - return await BulkOperationsSqlExecutor.ExecuteNonQueryAsync(_ctx.Database, updateStatement, cancellationToken); + return await executeAsync(updateStatement, cancellationToken); } /// @@ -551,10 +561,15 @@ public async Task BulkInsertOrUpdateAsync( if (options is not NpgsqlBulkInsertOrUpdateOptions npgsqlOptions) npgsqlOptions = new NpgsqlBulkInsertOrUpdateOptions(options); - return await BulkInsertOrUpdateAsync(entities, npgsqlOptions, cancellationToken); + return await BulkInsertOrUpdateAsync(entities, npgsqlOptions, null, ExecuteStatementAsync, cancellationToken); } - private async Task BulkInsertOrUpdateAsync(IEnumerable entities, NpgsqlBulkInsertOrUpdateOptions options, CancellationToken cancellationToken) + private async Task BulkInsertOrUpdateAsync( + IEnumerable entities, + NpgsqlBulkInsertOrUpdateOptions options, + IReadOnlyList? returningColumns, + Func> executeAsync, + CancellationToken cancellationToken) where T : class { var entityType = _ctx.Model.GetEntityTypeOrTempTableEntityType(); @@ -570,9 +585,9 @@ private async Task BulkInsertOrUpdateAsync(IEnumerable entities, Npgs await using var tempTable = await BulkInsertIntoTempTableAsync(entities, tempTableOptions, cancellationToken); var keyProperties = options.KeyProperties.DetermineKeyProperties(entityType); - var upsertStatement = CreateInsertOrUpdateCommand(entityType, tableName.Schema, tableName.Name, tempTable.Name, propertiesForInsert, propertiesForUpdate, keyProperties, options.ConflictDoNothing); + var upsertStatement = CreateInsertOrUpdateCommand(entityType, tableName.Schema, tableName.Name, tempTable.Name, propertiesForInsert, propertiesForUpdate, keyProperties, options.ConflictDoNothing, returningColumns); - return await BulkOperationsSqlExecutor.ExecuteNonQueryAsync(_ctx.Database, upsertStatement, cancellationToken); + return await executeAsync(upsertStatement, cancellationToken); } private string CreateUpdateCommand( @@ -581,7 +596,8 @@ private string CreateUpdateCommand( string tableName, string sourceTempTableName, IReadOnlyList propertiesToUpdate, - IReadOnlyList keyProperties) + IReadOnlyList keyProperties, + IReadOnlyList? returningColumns) { var sb = _stringBuilderPool.Get(); @@ -636,6 +652,9 @@ private string CreateUpdateCommand( isFirstIteration = false; } + // The source temp table has the same columns, so the columns of the target are qualified. + AppendReturning(sb, returningColumns, "d."); + sb.Append(_sqlGenerationHelper.StatementTerminator); return sb.ToString(); @@ -646,6 +665,22 @@ private string CreateUpdateCommand( } } + private void AppendReturning(StringBuilder sb, IReadOnlyList? returningColumns, string qualifier) + { + if (returningColumns is null) + return; + + sb.AppendLine().Append("RETURNING "); + + for (var i = 0; i < returningColumns.Count; i++) + { + if (i != 0) + sb.Append(", "); + + sb.Append(qualifier).Append(_sqlGenerationHelper.DelimitIdentifier(returningColumns[i])); + } + } + /// /// Performs a bulk update using a server-side query as the source. /// @@ -706,7 +741,8 @@ private string CreateInsertOrUpdateCommand( IReadOnlyList propertiesToInsert, IReadOnlyList propertiesToUpdate, IReadOnlyList keyProperties, - bool conflictDoNothing) + bool conflictDoNothing, + IReadOnlyList? returningColumns) { var sb = _stringBuilderPool.Get(); @@ -792,6 +828,8 @@ private string CreateInsertOrUpdateCommand( } } + AppendReturning(sb, returningColumns, string.Empty); + sb.Append(_sqlGenerationHelper.StatementTerminator); return sb.ToString(); diff --git a/src/Thinktecture.EntityFrameworkCore.PostgreSQL/EntityFrameworkCore/Infrastructure/NpgsqlDbContextOptionsExtension.cs b/src/Thinktecture.EntityFrameworkCore.PostgreSQL/EntityFrameworkCore/Infrastructure/NpgsqlDbContextOptionsExtension.cs index d61ce4a2..cabad468 100644 --- a/src/Thinktecture.EntityFrameworkCore.PostgreSQL/EntityFrameworkCore/Infrastructure/NpgsqlDbContextOptionsExtension.cs +++ b/src/Thinktecture.EntityFrameworkCore.PostgreSQL/EntityFrameworkCore/Infrastructure/NpgsqlDbContextOptionsExtension.cs @@ -149,6 +149,7 @@ public void ApplyServices(IServiceCollection services) services.TryAddScoped(provider => provider.GetRequiredService()); services.TryAddScoped(provider => provider.GetRequiredService()); services.TryAddScoped(provider => provider.GetRequiredService()); + services.TryAddScoped(provider => provider.GetRequiredService()); services.TryAddScoped(provider => provider.GetRequiredService()); services.TryAddScoped(provider => provider.GetRequiredService()); } diff --git a/src/Thinktecture.EntityFrameworkCore.SqlServer/EntityFrameworkCore/BulkOperations/SqlServerBulkOperationExecutor.MergeOutput.cs b/src/Thinktecture.EntityFrameworkCore.SqlServer/EntityFrameworkCore/BulkOperations/SqlServerBulkOperationExecutor.MergeOutput.cs new file mode 100644 index 00000000..9fecb964 --- /dev/null +++ b/src/Thinktecture.EntityFrameworkCore.SqlServer/EntityFrameworkCore/BulkOperations/SqlServerBulkOperationExecutor.MergeOutput.cs @@ -0,0 +1,132 @@ +using System.Linq.Expressions; +using Thinktecture.EntityFrameworkCore.BulkOperations.Internal; +using Thinktecture.Internal; + +namespace Thinktecture.EntityFrameworkCore.BulkOperations; + +public sealed partial class SqlServerBulkOperationExecutor : IBulkOperationOutputExecutor +{ + /// + /// Updates existing rows and inserts the missing ones (MERGE) and returns the OUTPUT rows selected by . + /// + /// Entities to insert or update. + /// Options. + /// Selects the result, for example row => new { row.Inserted.Id, row.Action }. Only the properties that the expression reads are returned by the database. + /// Cancellation token. + /// Type of the entity. + /// Type of the result. + /// One result per inserted or updated row. The order is not defined, it is not the order of . + /// , or is null. + /// reads a member that is not a scalar property mapped to a column. + public async Task> BulkInsertOrUpdateAsync( + IEnumerable entities, + SqlServerBulkInsertOrUpdateOptions options, + Expression, TResult>> output, + CancellationToken cancellationToken = default) + where T : class + { + ArgumentNullException.ThrowIfNull(entities); + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(output); + + var plan = SqlServerMergeOutputPlan.Create(_ctx.Model.GetEntityTypeOrTempTableEntityType(), _sqlGenerationHelper, output); + + return await BulkInsertOrUpdateAsync(entities, options, plan.Sql, (statement, token) => ExecuteMergeAsync(plan, statement, token), cancellationToken); + } + + /// + /// Updates existing rows (MERGE) and returns the OUTPUT rows selected by . + /// + /// Entities to update. + /// Options. + /// Selects the result, for example row => new { row.Inserted.Id, OldName = row.Deleted.Name }. Only the properties that the expression reads are returned by the database. + /// Cancellation token. + /// Type of the entity. + /// Type of the result. + /// One result per updated row. The order is not defined, it is not the order of . + /// , or is null. + /// reads a member that is not a scalar property mapped to a column. + public async Task> BulkUpdateAsync( + IEnumerable entities, + SqlServerBulkUpdateOptions options, + Expression, TResult>> output, + CancellationToken cancellationToken = default) + where T : class + { + ArgumentNullException.ThrowIfNull(entities); + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(output); + + var plan = SqlServerMergeOutputPlan.Create(_ctx.Model.GetEntityTypeOrTempTableEntityType(), _sqlGenerationHelper, output); + + return await BulkUpdateAsync(entities, options, plan.Sql, (statement, token) => ExecuteMergeAsync(plan, statement, token), cancellationToken); + } + + /// + Task> IBulkOperationOutputExecutor.BulkInsertOrUpdateAsync( + IEnumerable entities, + IBulkInsertOrUpdateOptions options, + Expression, TResult>> output, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(options); + + if (options is not SqlServerBulkInsertOrUpdateOptions sqlServerOptions) + sqlServerOptions = new SqlServerBulkInsertOrUpdateOptions(options); + + return BulkInsertOrUpdateAsync(entities, sqlServerOptions, ToMergeOutput(output), cancellationToken); + } + + /// + Task> IBulkOperationOutputExecutor.BulkUpdateAsync( + IEnumerable entities, + IBulkUpdateOptions options, + Expression, TResult>> output, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(options); + + if (options is not SqlServerBulkUpdateOptions sqlServerOptions) + sqlServerOptions = new SqlServerBulkUpdateOptions(options); + + return BulkUpdateAsync(entities, sqlServerOptions, ToMergeOutput(output), cancellationToken); + } + + // BulkOperationOutput offers "Inserted" only, which SqlServerMergeOutput offers as well. + private static Expression, TResult>> ToMergeOutput(Expression, TResult>> output) + where T : class + { + ArgumentNullException.ThrowIfNull(output); + + var mergeOutput = Expression.Parameter(typeof(SqlServerMergeOutput), output.Parameters[0].Name); + var body = new InsertedRewriter(output.Parameters[0], mergeOutput).Visit(output.Body); + + return Expression.Lambda, TResult>>(body, mergeOutput); + } + + private sealed class InsertedRewriter(ParameterExpression from, ParameterExpression to) : ExpressionVisitor + { + protected override Expression VisitMember(MemberExpression node) + { + return node.Expression == from + ? Expression.Property(to, nameof(SqlServerMergeOutput<>.Inserted)) + : base.VisitMember(node); + } + + protected override Expression VisitParameter(ParameterExpression node) + { + return node == from + ? throw new NotSupportedException("The projection must read the properties of the 'Inserted' member of the output row, the output row itself cannot be used on SQL Server.") + : node; + } + } + + private Task> ExecuteMergeAsync( + SqlServerMergeOutputPlan plan, + string mergeStatement, + CancellationToken cancellationToken) + where T : class + { + return BulkOperationsSqlExecutor.ExecuteReaderAsync(_ctx.Database, mergeStatement, plan.ReadAsync, cancellationToken); + } +} diff --git a/src/Thinktecture.EntityFrameworkCore.SqlServer/EntityFrameworkCore/BulkOperations/SqlServerBulkOperationExecutor.cs b/src/Thinktecture.EntityFrameworkCore.SqlServer/EntityFrameworkCore/BulkOperations/SqlServerBulkOperationExecutor.cs index 00d23c56..3544aca2 100644 --- a/src/Thinktecture.EntityFrameworkCore.SqlServer/EntityFrameworkCore/BulkOperations/SqlServerBulkOperationExecutor.cs +++ b/src/Thinktecture.EntityFrameworkCore.SqlServer/EntityFrameworkCore/BulkOperations/SqlServerBulkOperationExecutor.cs @@ -473,10 +473,20 @@ public async Task BulkUpdateAsync( if (options is not SqlServerBulkUpdateOptions sqlServerOptions) sqlServerOptions = new SqlServerBulkUpdateOptions(options); - return await BulkUpdateAsync(entities, sqlServerOptions, cancellationToken); + return await BulkUpdateAsync(entities, sqlServerOptions, null, ExecuteMergeAsync, cancellationToken); } - private async Task BulkUpdateAsync(IEnumerable entities, SqlServerBulkUpdateOptions options, CancellationToken cancellationToken) + private Task ExecuteMergeAsync(string mergeStatement, CancellationToken cancellationToken) + { + return BulkOperationsSqlExecutor.ExecuteNonQueryAsync(_ctx.Database, mergeStatement, cancellationToken); + } + + private async Task BulkUpdateAsync( + IEnumerable entities, + SqlServerBulkUpdateOptions options, + SqlServerMergeOutputSql? output, + Func> executeMergeAsync, + CancellationToken cancellationToken) where T : class { var entityType = _ctx.Model.GetEntityTypeOrTempTableEntityType(); @@ -490,9 +500,9 @@ private async Task BulkUpdateAsync(IEnumerable entities, SqlServerBul var tempTableOptions = options.GetTempTableBulkInsertOptions(); await using var tempTable = await BulkInsertIntoTempTableAsync(entities, tempTableOptions, cancellationToken); - var mergeStatement = CreateMergeCommand(entityType, tableName.Schema, tableName.Name, tempTable.Name, options, null, propertiesForUpdate, options.KeyProperties.DetermineKeyProperties(entityType)); + var mergeStatement = CreateMergeCommand(entityType, tableName.Schema, tableName.Name, tempTable.Name, options, null, propertiesForUpdate, options.KeyProperties.DetermineKeyProperties(entityType), output); - return await BulkOperationsSqlExecutor.ExecuteNonQueryAsync(_ctx.Database, mergeStatement, cancellationToken); + return await executeMergeAsync(mergeStatement, cancellationToken); } /// @@ -508,10 +518,15 @@ public async Task BulkInsertOrUpdateAsync( if (options is not SqlServerBulkInsertOrUpdateOptions sqlServerOptions) sqlServerOptions = new SqlServerBulkInsertOrUpdateOptions(options); - return await BulkInsertOrUpdateAsync(entities, sqlServerOptions, cancellationToken); + return await BulkInsertOrUpdateAsync(entities, sqlServerOptions, null, ExecuteMergeAsync, cancellationToken); } - private async Task BulkInsertOrUpdateAsync(IEnumerable entities, SqlServerBulkInsertOrUpdateOptions options, CancellationToken cancellationToken) + private async Task BulkInsertOrUpdateAsync( + IEnumerable entities, + SqlServerBulkInsertOrUpdateOptions options, + SqlServerMergeOutputSql? output, + Func> executeMergeAsync, + CancellationToken cancellationToken) where T : class { var entityType = _ctx.Model.GetEntityTypeOrTempTableEntityType(); @@ -526,9 +541,9 @@ private async Task BulkInsertOrUpdateAsync(IEnumerable entities, SqlS var tempTableOptions = options.GetTempTableBulkInsertOptions(); await using var tempTable = await BulkInsertIntoTempTableAsync(entities, tempTableOptions, cancellationToken); - var mergeStatement = CreateMergeCommand(entityType, tableName.Schema, tableName.Name, tempTable.Name, options, propertiesForInsert, propertiesForUpdate, options.KeyProperties.DetermineKeyProperties(entityType)); + var mergeStatement = CreateMergeCommand(entityType, tableName.Schema, tableName.Name, tempTable.Name, options, propertiesForInsert, propertiesForUpdate, options.KeyProperties.DetermineKeyProperties(entityType), output); - return await BulkOperationsSqlExecutor.ExecuteNonQueryAsync(_ctx.Database, mergeStatement, cancellationToken); + return await executeMergeAsync(mergeStatement, cancellationToken); } private string CreateMergeCommand( @@ -539,7 +554,8 @@ private string CreateMergeCommand( T options, IReadOnlyList? propertiesToInsert, IReadOnlyList propertiesToUpdate, - IReadOnlyList keyProperties) + IReadOnlyList keyProperties, + SqlServerMergeOutputSql? output) where T : ISqlServerMergeOperationOptions { var sb = _stringBuilderPool.Get(); @@ -549,6 +565,9 @@ private string CreateMergeCommand( var storeObject = StoreObjectIdentifier.Create(entityType, StoreObjectType.Table) ?? throw new Exception($"Could not create StoreObjectIdentifier for table '{entityType.Name}'."); + if (output is not null) + sb.AppendLine(output.Declaration); + sb.Append("MERGE INTO ") .Append(_sqlGenerationHelper.DelimitIdentifier(tableName, schema)); @@ -655,8 +674,14 @@ private string CreateMergeCommand( sb.Append(")"); } + if (output is not null) + sb.AppendLine().Append(output.OutputClause); + sb.Append(_sqlGenerationHelper.StatementTerminator); + if (output is not null) + sb.AppendLine().Append(output.Select); + return sb.ToString(); } finally diff --git a/src/Thinktecture.EntityFrameworkCore.SqlServer/EntityFrameworkCore/BulkOperations/SqlServerMergeAction.cs b/src/Thinktecture.EntityFrameworkCore.SqlServer/EntityFrameworkCore/BulkOperations/SqlServerMergeAction.cs new file mode 100644 index 00000000..aa7a510d --- /dev/null +++ b/src/Thinktecture.EntityFrameworkCore.SqlServer/EntityFrameworkCore/BulkOperations/SqlServerMergeAction.cs @@ -0,0 +1,17 @@ +namespace Thinktecture.EntityFrameworkCore.BulkOperations; + +/// +/// The action a SQL Server MERGE statement executed for a row ($action). +/// +public enum SqlServerMergeAction +{ + /// + /// The row was inserted. + /// + Insert, + + /// + /// The row was updated. + /// + Update +} diff --git a/src/Thinktecture.EntityFrameworkCore.SqlServer/EntityFrameworkCore/BulkOperations/SqlServerMergeOutput.cs b/src/Thinktecture.EntityFrameworkCore.SqlServer/EntityFrameworkCore/BulkOperations/SqlServerMergeOutput.cs new file mode 100644 index 00000000..703c6be3 --- /dev/null +++ b/src/Thinktecture.EntityFrameworkCore.SqlServer/EntityFrameworkCore/BulkOperations/SqlServerMergeOutput.cs @@ -0,0 +1,34 @@ +namespace Thinktecture.EntityFrameworkCore.BulkOperations; + +/// +/// One row of the OUTPUT clause of a SQL Server MERGE statement. +/// Use it in the projection of BulkInsertOrUpdateAsync and BulkUpdateAsync to select the columns to return: +/// output => new { output.Inserted.Id, OldName = output.Deleted.Name, output.Action }. +/// +/// Type of the entity. +public sealed class SqlServerMergeOutput + where T : class +{ + /// + /// The action the MERGE statement executed for the row. + /// + public SqlServerMergeAction Action { get; internal set; } + + /// + /// The row after the operation (inserted.*). + /// + /// + /// Only the properties that the projection reads are loaded; the other properties keep their default values. + /// + public T Inserted { get; internal set; } = null!; + + /// + /// The row before the operation (deleted.*). + /// For a row that was inserted the database returns NULL for all columns, so nullable properties are null + /// and the other properties keep their default values. Use to tell the cases apart. + /// + /// + /// Only the properties that the projection reads are loaded; the other properties keep their default values. + /// + public T Deleted { get; internal set; } = null!; +} diff --git a/src/Thinktecture.EntityFrameworkCore.SqlServer/EntityFrameworkCore/BulkOperations/SqlServerMergeOutputPlan.cs b/src/Thinktecture.EntityFrameworkCore.SqlServer/EntityFrameworkCore/BulkOperations/SqlServerMergeOutputPlan.cs new file mode 100644 index 00000000..ceabc0a4 --- /dev/null +++ b/src/Thinktecture.EntityFrameworkCore.SqlServer/EntityFrameworkCore/BulkOperations/SqlServerMergeOutputPlan.cs @@ -0,0 +1,219 @@ +using System.Data.Common; +using System.Linq.Expressions; +using System.Text; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Storage; +using Thinktecture.EntityFrameworkCore.BulkOperations.Internal; + +namespace Thinktecture.EntityFrameworkCore.BulkOperations; + +/// +/// The parts of the SQL batch that return the OUTPUT rows of a MERGE statement. +/// +/// Declares the table variable that receives the rows; precedes the MERGE statement. +/// The OUTPUT ... INTO clause; ends the MERGE statement. +/// Selects the rows of the table variable; follows the MERGE statement. +internal sealed record SqlServerMergeOutputSql(string Declaration, string OutputClause, string Select); + +/// +/// Translates the projection of a MERGE result to an OUTPUT clause and materializes the returned rows. +/// +/// +/// The rows are written into a table variable first (OUTPUT ... INTO), because SQL Server rejects OUTPUT without INTO if the target table has enabled triggers. +/// The columns of the table variable are the action, the columns of inserted and the columns of deleted, in this order. +/// +internal sealed class SqlServerMergeOutputPlan + where T : class +{ + private const string _TABLE_VARIABLE = "@MergeOutput"; + private const string _ACTION_COLUMN = "Action"; + + private readonly BulkOperationOutputMapper? _inserted; + private readonly BulkOperationOutputMapper? _deleted; + private readonly int _deletedOrdinal; + private readonly Func, TResult> _projection; + + public SqlServerMergeOutputSql Sql { get; } + + private SqlServerMergeOutputPlan( + BulkOperationOutputMapper? inserted, + BulkOperationOutputMapper? deleted, + Func, TResult> projection, + SqlServerMergeOutputSql sql) + { + _inserted = inserted; + _deleted = deleted; + // The first column is the action. + _deletedOrdinal = 1 + (inserted?.Columns.Count ?? 0); + _projection = projection; + Sql = sql; + } + + public static SqlServerMergeOutputPlan Create( + IEntityType entityType, + ISqlGenerationHelper sqlGenerationHelper, + Expression, TResult>> output) + { + var storeObject = StoreObjectIdentifier.Create(entityType, StoreObjectType.Table) + ?? throw new InvalidOperationException($"Could not create StoreObjectIdentifier for table '{entityType.Name}'."); + + var collector = new MemberCollector(output.Parameters[0]); + collector.Visit(output.Body); + + var inserted = collector.UsesInserted ? BulkOperationOutputMapper.Create(entityType, storeObject, collector.AllInserted, collector.InsertedMembers) : null; + var deleted = collector.UsesDeleted ? BulkOperationOutputMapper.Create(entityType, storeObject, collector.AllDeleted, collector.DeletedMembers) : null; + + return new SqlServerMergeOutputPlan(inserted, deleted, output.Compile(), CreateSql(sqlGenerationHelper, inserted, deleted)); + } + + public async Task> ReadAsync(DbDataReader reader, CancellationToken cancellationToken) + { + var results = new List(); + + while (await reader.ReadAsync(cancellationToken).ConfigureAwait(false)) + { + var row = new SqlServerMergeOutput { Action = ParseAction(reader.GetString(0)) }; + + if (_inserted is not null) + row.Inserted = _inserted.Read(reader, 1); + + if (_deleted is not null) + row.Deleted = _deleted.Read(reader, _deletedOrdinal); + + results.Add(_projection(row)); + } + + return results; + } + + private static SqlServerMergeAction ParseAction(string action) + { + return action switch + { + "INSERT" => SqlServerMergeAction.Insert, + "UPDATE" => SqlServerMergeAction.Update, + _ => throw new InvalidOperationException($"The MERGE statement returned the unexpected action '{action}'.") + }; + } + + private static SqlServerMergeOutputSql CreateSql( + ISqlGenerationHelper sqlGenerationHelper, + BulkOperationOutputMapper? inserted, + BulkOperationOutputMapper? deleted) + { + var action = sqlGenerationHelper.DelimitIdentifier(_ACTION_COLUMN); + + var declaration = new StringBuilder("DECLARE ").Append(_TABLE_VARIABLE).Append(" TABLE (").Append(action).Append(" nvarchar(10) NOT NULL"); + var output = new StringBuilder("OUTPUT $action"); + var into = new StringBuilder(action); + var select = new StringBuilder("SELECT ").Append(action); + var ordinal = 1; + + foreach (var (mapper, prefix, alias) in new[] { (inserted, "inserted.", 'i'), (deleted, "deleted.", 'd') }) + { + if (mapper is null) + continue; + + foreach (var column in mapper.Columns) + { + var name = sqlGenerationHelper.DelimitIdentifier($"{alias}{ordinal++}"); + + declaration.Append(", ").Append(name).Append(' ').Append(GetStoreType(column.StoreType)).Append(" NULL"); + output.Append(", ").Append(prefix).Append(sqlGenerationHelper.DelimitIdentifier(column.ColumnName)); + into.Append(", ").Append(name); + select.Append(", ").Append(name); + } + } + + return new SqlServerMergeOutputSql( + declaration.Append(");").ToString(), + output.Append(" INTO ").Append(_TABLE_VARIABLE).Append(" (").Append(into).Append(')').ToString(), + select.Append(" FROM ").Append(_TABLE_VARIABLE).Append(';').ToString()); + } + + // A rowversion/timestamp column cannot receive an explicit value. + private static string GetStoreType(string storeType) + { + return storeType.Equals("rowversion", StringComparison.OrdinalIgnoreCase) || storeType.Equals("timestamp", StringComparison.OrdinalIgnoreCase) + ? "binary(8)" + : storeType; + } + + // Collects the members of "output.Inserted" and "output.Deleted" that the projection reads. + private sealed class MemberCollector(ParameterExpression parameter) : ExpressionVisitor + { + public HashSet InsertedMembers { get; } = []; + public HashSet DeletedMembers { get; } = []; + public bool AllInserted { get; private set; } + public bool AllDeleted { get; private set; } + public bool UsesInserted { get; private set; } + public bool UsesDeleted { get; private set; } + + protected override Expression VisitMember(MemberExpression node) + { + // output.Inserted.Name + if (IsSide(node.Expression, out var isInserted)) + { + (isInserted ? InsertedMembers : DeletedMembers).Add(node.Member.Name); + Use(isInserted); + return node; + } + + // output.Inserted: the whole entity + if (IsSide(node, out isInserted)) + { + if (isInserted) + AllInserted = true; + else + AllDeleted = true; + + Use(isInserted); + return node; + } + + // output.Action + if (node.Expression == parameter) + return node; + + return base.VisitMember(node); + } + + protected override Expression VisitParameter(ParameterExpression node) + { + // The output row is used as a whole, for example passed to a method: load everything. + if (node == parameter) + { + AllInserted = true; + AllDeleted = true; + UsesInserted = true; + UsesDeleted = true; + } + + return node; + } + + private void Use(bool isInserted) + { + if (isInserted) + UsesInserted = true; + else + UsesDeleted = true; + } + + private bool IsSide(Expression? expression, out bool isInserted) + { + isInserted = false; + + if (expression is not MemberExpression { Expression: ParameterExpression owner } member || owner != parameter) + return false; + + if (member.Member.Name == nameof(SqlServerMergeOutput.Inserted)) + { + isInserted = true; + return true; + } + + return member.Member.Name == nameof(SqlServerMergeOutput.Deleted); + } + } +} diff --git a/src/Thinktecture.EntityFrameworkCore.SqlServer/EntityFrameworkCore/Infrastructure/SqlServerDbContextOptionsExtension.cs b/src/Thinktecture.EntityFrameworkCore.SqlServer/EntityFrameworkCore/Infrastructure/SqlServerDbContextOptionsExtension.cs index 2f460236..87ed4cb7 100644 --- a/src/Thinktecture.EntityFrameworkCore.SqlServer/EntityFrameworkCore/Infrastructure/SqlServerDbContextOptionsExtension.cs +++ b/src/Thinktecture.EntityFrameworkCore.SqlServer/EntityFrameworkCore/Infrastructure/SqlServerDbContextOptionsExtension.cs @@ -163,6 +163,7 @@ public void ApplyServices(IServiceCollection services) services.TryAddScoped(provider => provider.GetRequiredService()); services.TryAddScoped(provider => provider.GetRequiredService()); services.TryAddScoped(provider => provider.GetRequiredService()); + services.TryAddScoped(provider => provider.GetRequiredService()); services.TryAddScoped(provider => provider.GetRequiredService()); } diff --git a/src/Thinktecture.EntityFrameworkCore.SqlServer/Extensions/SqlServerMergeOutputDbContextExtensions.cs b/src/Thinktecture.EntityFrameworkCore.SqlServer/Extensions/SqlServerMergeOutputDbContextExtensions.cs new file mode 100644 index 00000000..3f04e1b5 --- /dev/null +++ b/src/Thinktecture.EntityFrameworkCore.SqlServer/Extensions/SqlServerMergeOutputDbContextExtensions.cs @@ -0,0 +1,73 @@ +using System.Linq.Expressions; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Thinktecture.EntityFrameworkCore.BulkOperations; + +// ReSharper disable once CheckNamespace +namespace Thinktecture; + +/// +/// Extension methods for that return the OUTPUT rows (inserted.*, deleted.*) of a SQL Server MERGE statement. +/// +public static class SqlServerMergeOutputDbContextExtensions +{ + /// + /// Updates existing rows and inserts the missing ones (MERGE) and returns the OUTPUT rows selected by . + /// + /// Database context to use. + /// Entities to insert or update. + /// Options. + /// + /// Selects the result, for example row => new { row.Inserted.Id, OldName = row.Deleted.Name, row.Action }. + /// row.Inserted maps to inserted.*, row.Deleted to deleted.* and row.Action to $action. + /// Only the properties that the expression reads are requested from the database. + /// The deleted columns of an inserted row are NULL, so nullable properties are null and the others keep their default value. + /// + /// Cancellation token. + /// Type of the entity. + /// Type of the result. + /// One result per inserted or updated row. The order is not defined, it is not the order of . + /// , , or is null. + /// reads a member that is not a scalar property mapped to a column. + public static Task> BulkInsertOrUpdateAsync( + this DbContext ctx, + IEnumerable entities, + SqlServerBulkInsertOrUpdateOptions options, + Expression, TResult>> output, + CancellationToken cancellationToken = default) + where T : class + { + ArgumentNullException.ThrowIfNull(ctx); + + return ctx.GetService().BulkInsertOrUpdateAsync(entities, options, output, cancellationToken); + } + + /// + /// Updates existing rows (MERGE) and returns the OUTPUT rows selected by . + /// + /// Database context to use. + /// Entities to update. + /// Options. + /// + /// Selects the result, for example row => new { row.Inserted.Id, OldName = row.Deleted.Name }. + /// row.Inserted maps to inserted.*, row.Deleted to deleted.* and row.Action to $action. + /// Only the properties that the expression reads are requested from the database. + /// + /// Cancellation token. + /// Type of the entity. + /// Type of the result. + /// One result per updated row. The order is not defined, it is not the order of . + /// , , or is null. + /// reads a member that is not a scalar property mapped to a column. + public static Task> BulkUpdateAsync( + this DbContext ctx, + IEnumerable entities, + SqlServerBulkUpdateOptions options, + Expression, TResult>> output, + CancellationToken cancellationToken = default) + where T : class + { + ArgumentNullException.ThrowIfNull(ctx); + + return ctx.GetService().BulkUpdateAsync(entities, options, output, cancellationToken); + } +} diff --git a/src/Thinktecture.EntityFrameworkCore.Sqlite.Core/EntityFrameworkCore/BulkOperations/SqliteBulkOperationExecutor.Returning.cs b/src/Thinktecture.EntityFrameworkCore.Sqlite.Core/EntityFrameworkCore/BulkOperations/SqliteBulkOperationExecutor.Returning.cs new file mode 100644 index 00000000..9add8814 --- /dev/null +++ b/src/Thinktecture.EntityFrameworkCore.Sqlite.Core/EntityFrameworkCore/BulkOperations/SqliteBulkOperationExecutor.Returning.cs @@ -0,0 +1,49 @@ +using System.Linq.Expressions; +using Thinktecture.EntityFrameworkCore.BulkOperations.Internal; + +namespace Thinktecture.EntityFrameworkCore.BulkOperations; + +public sealed partial class SqliteBulkOperationExecutor +{ + /// + public async Task> BulkInsertOrUpdateAsync( + IEnumerable entities, + IBulkInsertOrUpdateOptions options, + Expression, TResult>> output, + CancellationToken cancellationToken = default) + where T : class + { + ArgumentNullException.ThrowIfNull(entities); + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(output); + + if (options is not ISqliteBulkInsertOrUpdateOptions sqliteOptions) + sqliteOptions = new SqliteBulkInsertOrUpdateOptions(options); + + var returning = new SqliteReturning(BulkOperationReturningProjection.Create(_ctx.Model.GetEntityTypeOrTempTableEntityType(), output)); + await BulkInsertOrUpdateAsync(entities, sqliteOptions, returning, cancellationToken); + + return returning.Results; + } + + /// + public async Task> BulkUpdateAsync( + IEnumerable entities, + IBulkUpdateOptions options, + Expression, TResult>> output, + CancellationToken cancellationToken = default) + where T : class + { + ArgumentNullException.ThrowIfNull(entities); + ArgumentNullException.ThrowIfNull(options); + ArgumentNullException.ThrowIfNull(output); + + if (options is not SqliteBulkUpdateOptions sqliteOptions) + sqliteOptions = new SqliteBulkUpdateOptions(options); + + var returning = new SqliteReturning(BulkOperationReturningProjection.Create(_ctx.Model.GetEntityTypeOrTempTableEntityType(), output)); + await BulkUpdateAsync(entities, sqliteOptions, returning, cancellationToken); + + return returning.Results; + } +} diff --git a/src/Thinktecture.EntityFrameworkCore.Sqlite.Core/EntityFrameworkCore/BulkOperations/SqliteBulkOperationExecutor.cs b/src/Thinktecture.EntityFrameworkCore.Sqlite.Core/EntityFrameworkCore/BulkOperations/SqliteBulkOperationExecutor.cs index b5ab6d47..6a2919e4 100644 --- a/src/Thinktecture.EntityFrameworkCore.Sqlite.Core/EntityFrameworkCore/BulkOperations/SqliteBulkOperationExecutor.cs +++ b/src/Thinktecture.EntityFrameworkCore.Sqlite.Core/EntityFrameworkCore/BulkOperations/SqliteBulkOperationExecutor.cs @@ -23,7 +23,7 @@ namespace Thinktecture.EntityFrameworkCore.BulkOperations; [SuppressMessage("Usage", "EF1001:Internal EF Core API usage.")] public sealed partial class SqliteBulkOperationExecutor : IBulkInsertExecutor, ITempTableBulkInsertExecutor, IBulkUpdateExecutor, - IBulkInsertOrUpdateExecutor, ITruncateTableExecutor + IBulkInsertOrUpdateExecutor, ITruncateTableExecutor, IBulkOperationOutputExecutor { private readonly DbContext _ctx; private readonly IDiagnosticsLogger _logger; @@ -130,7 +130,7 @@ private async Task BulkInsertAsync( var tableName = tableNameProvider.GetValidTableName(entityType); var ctx = bulkOperationContextFactory.CreateForBulkInsert(_ctx, entityType, options, properties); - return await ExecuteBulkOperationAsync(entitiesOrValues, tableName.Schema, tableName.Name, ctx, tableNameProvider, cancellationToken); + return await ExecuteBulkOperationAsync(entitiesOrValues, tableName.Schema, tableName.Name, ctx, tableNameProvider, null, cancellationToken); } /// @@ -146,19 +146,29 @@ public async Task BulkUpdateAsync( if (options is not SqliteBulkUpdateOptions sqliteOptions) sqliteOptions = new SqliteBulkUpdateOptions(options); + return await BulkUpdateAsync(entities, sqliteOptions, null, cancellationToken); + } + + private async Task BulkUpdateAsync( + IEnumerable entities, + SqliteBulkUpdateOptions sqliteOptions, + SqliteReturning? returning, + CancellationToken cancellationToken) + where T : class + { var entityType = _ctx.Model.GetEntityTypeOrTempTableEntityType(); - var propertiesToUpdate = options.PropertiesToUpdate.DeterminePropertiesForUpdate(entityType, null); + var propertiesToUpdate = sqliteOptions.PropertiesToUpdate.DeterminePropertiesForUpdate(entityType, null); var tableNameProvider = sqliteOptions.TableNameProvider; var tableName = tableNameProvider.GetValidTableName(entityType); var ctx = new BulkUpdateContext(_ctx, entityType, _ctx.GetService(), (SqliteConnection)_ctx.Database.GetDbConnection(), - options.KeyProperties.DetermineKeyProperties(entityType), + sqliteOptions.KeyProperties.DetermineKeyProperties(entityType), propertiesToUpdate, sqliteOptions.AutoIncrementBehavior); - return await ExecuteBulkOperationAsync(entities, tableName.Schema, tableName.Name, ctx, tableNameProvider, cancellationToken); + return await ExecuteBulkOperationAsync(entities, tableName.Schema, tableName.Name, ctx, tableNameProvider, returning, cancellationToken); } /// @@ -174,6 +184,16 @@ public async Task BulkInsertOrUpdateAsync( if (!(options is ISqliteBulkInsertOrUpdateOptions sqliteOptions)) sqliteOptions = new SqliteBulkInsertOrUpdateOptions(options); + return await BulkInsertOrUpdateAsync(entities, sqliteOptions, null, cancellationToken); + } + + private async Task BulkInsertOrUpdateAsync( + IEnumerable entities, + ISqliteBulkInsertOrUpdateOptions sqliteOptions, + SqliteReturning? returning, + CancellationToken cancellationToken) + where T : class + { var entityType = _ctx.Model.GetEntityTypeOrTempTableEntityType(); var propertiesToInsert = sqliteOptions.PropertiesToInsert.DeterminePropertiesForInsert(entityType, null); var propertiesToUpdate = sqliteOptions.PropertiesToUpdate.DeterminePropertiesForUpdate(entityType, true); @@ -188,7 +208,7 @@ public async Task BulkInsertOrUpdateAsync( propertiesToUpdate, sqliteOptions.AutoIncrementBehavior); - return await ExecuteBulkOperationAsync(entities, tableName.Schema, tableName.Name, ctx, tableNameProvider, cancellationToken); + return await ExecuteBulkOperationAsync(entities, tableName.Schema, tableName.Name, ctx, tableNameProvider, returning, cancellationToken); } private async Task ExecuteBulkOperationAsync( @@ -197,6 +217,7 @@ private async Task ExecuteBulkOperationAsync( string tableName, ISqliteBulkOperationContext bulkOperationContext, IBulkOperationTableNameProvider tableNameProvider, + SqliteReturning? returning, CancellationToken cancellationToken) { await _ctx.Database.OpenConnectionAsync(cancellationToken).ConfigureAwait(false); @@ -211,7 +232,7 @@ private async Task ExecuteBulkOperationAsync( var tableIdentifier = _sqlGenerationHelper.DelimitIdentifier(tableName, schema); using var reader = bulkOperationContext.CreateReader(entitiesOrValues); - var numberOfAffectedRows = await ExecuteBulkOperationAsync(reader, bulkOperationContext, tableIdentifier, cancellationToken).ConfigureAwait(false); + var numberOfAffectedRows = await ExecuteBulkOperationAsync(reader, bulkOperationContext, tableIdentifier, returning, cancellationToken).ConfigureAwait(false); if (bulkOperationContext.HasExternalProperties) { @@ -245,7 +266,7 @@ private async Task ExecuteBulkOperationForSeparatedOwnedEntitiesAsync( { var tableName = tableNameProvider.GetValidTableName(childContext.EntityType); - numberOfAffectedRows += await ExecuteBulkOperationAsync(childContext.Entities, tableName.Schema, tableName.Name, childContext, tableNameProvider, cancellationToken).ConfigureAwait(false); + numberOfAffectedRows += await ExecuteBulkOperationAsync(childContext.Entities, tableName.Schema, tableName.Name, childContext, tableNameProvider, null, cancellationToken).ConfigureAwait(false); } return numberOfAffectedRows; @@ -255,11 +276,12 @@ private async Task ExecuteBulkOperationAsync( IEntityDataReader reader, ISqliteBulkOperationContext bulkOperationContext, string tableIdentifier, + SqliteReturning? returning, CancellationToken cancellationToken) { await using var command = bulkOperationContext.Connection.CreateCommand(); - command.CommandText = bulkOperationContext.CreateCommandBuilder().GetStatement(_sqlGenerationHelper, _stringBuilderPool, reader, tableIdentifier); + command.CommandText = bulkOperationContext.CreateCommandBuilder().GetStatement(_sqlGenerationHelper, _stringBuilderPool, reader, tableIdentifier, returning?.ColumnNames); var parameterInfos = CreateParameters(reader, command); try @@ -288,7 +310,21 @@ private async Task ExecuteBulkOperationAsync( paramInfo.Parameter.Value = value ?? DBNull.Value; } - numberOfAffectedRows += await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false); + if (returning is null) + { + numberOfAffectedRows += await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false); + } + else + { + await using var dataReader = await command.ExecuteReaderAsync(cancellationToken).ConfigureAwait(false); + + // The statement returns no row if a conflicting row is not updated or if the key is not found. + while (await dataReader.ReadAsync(cancellationToken).ConfigureAwait(false)) + { + returning.Read(dataReader); + numberOfAffectedRows++; + } + } } stopwatch.Stop(); diff --git a/src/Thinktecture.EntityFrameworkCore.Sqlite.Core/EntityFrameworkCore/BulkOperations/SqliteCommandBuilder.cs b/src/Thinktecture.EntityFrameworkCore.Sqlite.Core/EntityFrameworkCore/BulkOperations/SqliteCommandBuilder.cs index dd7fcf77..8e4a281a 100644 --- a/src/Thinktecture.EntityFrameworkCore.Sqlite.Core/EntityFrameworkCore/BulkOperations/SqliteCommandBuilder.cs +++ b/src/Thinktecture.EntityFrameworkCore.Sqlite.Core/EntityFrameworkCore/BulkOperations/SqliteCommandBuilder.cs @@ -65,7 +65,24 @@ public abstract string GetStatement( ISqlGenerationHelper sqlGenerationHelper, ObjectPool stringBuilderPool, IEntityDataReader reader, - string tableIdentifier); + string tableIdentifier, + IReadOnlyList? returningColumns); + + private static void AppendReturning(StringBuilder sb, ISqlGenerationHelper sqlGenerationHelper, IReadOnlyList? returningColumns) + { + if (returningColumns is null) + return; + + sb.AppendLine().Append("RETURNING "); + + for (var i = 0; i < returningColumns.Count; i++) + { + if (i != 0) + sb.Append(", "); + + sb.Append(sqlGenerationHelper.DelimitIdentifier(returningColumns[i])); + } + } private class SqliteInsertBuilder : SqliteCommandBuilder { @@ -81,7 +98,8 @@ public override string GetStatement( ISqlGenerationHelper sqlGenerationHelper, ObjectPool stringBuilderPool, IEntityDataReader reader, - string tableIdentifier) + string tableIdentifier, + IReadOnlyList? returningColumns) { var sb = stringBuilderPool.Get(); @@ -89,6 +107,7 @@ public override string GetStatement( { GenerateInsertStatement(sb, sqlGenerationHelper, reader, tableIdentifier, _propertiesToInsert); + AppendReturning(sb, sqlGenerationHelper, returningColumns); sb.Append(sqlGenerationHelper.StatementTerminator); return sb.ToString(); @@ -117,7 +136,8 @@ public override string GetStatement( ISqlGenerationHelper sqlGenerationHelper, ObjectPool stringBuilderPool, IEntityDataReader reader, - string tableIdentifier) + string tableIdentifier, + IReadOnlyList? returningColumns) { var sb = stringBuilderPool.Get(); @@ -127,6 +147,7 @@ public override string GetStatement( GenerateSetAndWhereClause(sb, sqlGenerationHelper, reader, _propertiesToUpdate, _keyProperties); + AppendReturning(sb, sqlGenerationHelper, returningColumns); sb.Append(sqlGenerationHelper.StatementTerminator); return sb.ToString(); @@ -217,7 +238,8 @@ public override string GetStatement( ISqlGenerationHelper sqlGenerationHelper, ObjectPool stringBuilderPool, IEntityDataReader reader, - string tableIdentifier) + string tableIdentifier, + IReadOnlyList? returningColumns) { var sb = stringBuilderPool.Get(); @@ -256,6 +278,7 @@ public override string GetStatement( sb.Append("\tNOTHING"); } + AppendReturning(sb, sqlGenerationHelper, returningColumns); sb.Append(sqlGenerationHelper.StatementTerminator); return sb.ToString(); diff --git a/src/Thinktecture.EntityFrameworkCore.Sqlite.Core/EntityFrameworkCore/BulkOperations/SqliteReturning.cs b/src/Thinktecture.EntityFrameworkCore.Sqlite.Core/EntityFrameworkCore/BulkOperations/SqliteReturning.cs new file mode 100644 index 00000000..de7d1c36 --- /dev/null +++ b/src/Thinktecture.EntityFrameworkCore.Sqlite.Core/EntityFrameworkCore/BulkOperations/SqliteReturning.cs @@ -0,0 +1,34 @@ +using System.Data.Common; +using Thinktecture.EntityFrameworkCore.BulkOperations.Internal; + +namespace Thinktecture.EntityFrameworkCore.BulkOperations; + +/// +/// Collects the rows that the RETURNING clause of the statements of a bulk operation returns. +/// +internal abstract class SqliteReturning +{ + public abstract IReadOnlyList ColumnNames { get; } + + public abstract void Read(DbDataReader reader); +} + +internal sealed class SqliteReturning : SqliteReturning + where T : class +{ + private readonly BulkOperationReturningProjection _projection; + + public List Results { get; } = []; + + public override IReadOnlyList ColumnNames => _projection.ColumnNames; + + public SqliteReturning(BulkOperationReturningProjection projection) + { + _projection = projection; + } + + public override void Read(DbDataReader reader) + { + Results.Add(_projection.Read(reader)); + } +} diff --git a/src/Thinktecture.EntityFrameworkCore.Sqlite.Core/EntityFrameworkCore/Infrastructure/SqliteDbContextOptionsExtension.cs b/src/Thinktecture.EntityFrameworkCore.Sqlite.Core/EntityFrameworkCore/Infrastructure/SqliteDbContextOptionsExtension.cs index 6f722ddd..526c5225 100644 --- a/src/Thinktecture.EntityFrameworkCore.Sqlite.Core/EntityFrameworkCore/Infrastructure/SqliteDbContextOptionsExtension.cs +++ b/src/Thinktecture.EntityFrameworkCore.Sqlite.Core/EntityFrameworkCore/Infrastructure/SqliteDbContextOptionsExtension.cs @@ -139,6 +139,7 @@ public void ApplyServices(IServiceCollection services) services.TryAddScoped(provider => provider.GetRequiredService()); services.TryAddScoped(provider => provider.GetRequiredService()); services.TryAddScoped(provider => provider.GetRequiredService()); + services.TryAddScoped(provider => provider.GetRequiredService()); services.TryAddScoped(provider => provider.GetRequiredService()); } } diff --git a/tests/Thinktecture.EntityFrameworkCore.BulkOperations.Tests/EntityFrameworkCore/BulkOperations/BulkOperationOutputMapperTests.cs b/tests/Thinktecture.EntityFrameworkCore.BulkOperations.Tests/EntityFrameworkCore/BulkOperations/BulkOperationOutputMapperTests.cs new file mode 100644 index 00000000..8808a0d4 --- /dev/null +++ b/tests/Thinktecture.EntityFrameworkCore.BulkOperations.Tests/EntityFrameworkCore/BulkOperations/BulkOperationOutputMapperTests.cs @@ -0,0 +1,71 @@ +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Storage; +using Thinktecture.EntityFrameworkCore.BulkOperations.Internal; +using Thinktecture.TestDatabaseContext; + +namespace Thinktecture.EntityFrameworkCore.BulkOperations; + +public class BulkOperationOutputMapperTests +{ + [Fact] + public void Should_reject_the_whole_entity_if_it_has_a_complex_property() + { + var (entityType, storeObject) = GetEntityType(TestEntityWithComplexType.Configure); + + var act = () => BulkOperationOutputMapper.Create(entityType, storeObject, true, []); + + act.Should().Throw().WithMessage("*complex property 'Boundary'*"); + } + + [Fact] + public void Should_allow_scalar_properties_of_an_entity_with_a_complex_property() + { + var (entityType, storeObject) = GetEntityType(TestEntityWithComplexType.Configure); + + var mapper = BulkOperationOutputMapper.Create(entityType, storeObject, false, [nameof(TestEntityWithComplexType.Id)]); + + mapper.Columns.Select(column => column.ColumnName).Should().Equal("Id"); + } + + [Fact] + public void Should_reject_the_whole_entity_if_it_has_an_owned_type_in_the_same_table() + { + var options = new DbContextOptionsBuilder().UseSqlite("Data Source=:memory:").Options; + using var context = new TestDbContext(options); + var entityType = context.Model.GetEntityType(typeof(Vehicle)); + var storeObject = StoreObjectIdentifier.Create(entityType, StoreObjectType.Table)!.Value; + + var act = () => BulkOperationOutputMapper.Create(entityType, storeObject, true, []); + + act.Should().Throw().WithMessage("*owned type 'Inline'*"); + } + + [Fact] + public void Should_reject_the_whole_entity_if_an_owned_type_in_the_same_table_is_inherited() + { + var options = new DbContextOptionsBuilder().UseSqlite("Data Source=:memory:").Options; + using var context = new TestDbContext(options); + var entityType = context.Model.GetEntityType(typeof(Car)); + var storeObject = StoreObjectIdentifier.Create(entityType, StoreObjectType.Table)!.Value; + + // Vehicle owns Inline, Car inherits it. + var act = () => BulkOperationOutputMapper.Create(entityType, storeObject, true, []); + + act.Should().Throw().WithMessage("*owned type 'Inline'*"); + } + + private static (IEntityType EntityType, StoreObjectIdentifier StoreObject) GetEntityType(Action configure) + { + var options = new DbContextOptionsBuilder().UseSqlite("Data Source=:memory:").Options; + using var context = new MapperDbContext(options, configure); + + var entityType = context.Model.FindEntityType(typeof(T))!; + + return (entityType, StoreObjectIdentifier.Create(entityType, StoreObjectType.Table)!.Value); + } + + private sealed class MapperDbContext(DbContextOptions options, Action configure) : DbContext(options) + { + protected override void OnModelCreating(ModelBuilder modelBuilder) => configure(modelBuilder); + } +} \ No newline at end of file diff --git a/tests/Thinktecture.EntityFrameworkCore.BulkOperations.Tests/Thinktecture.EntityFrameworkCore.BulkOperations.Tests.csproj b/tests/Thinktecture.EntityFrameworkCore.BulkOperations.Tests/Thinktecture.EntityFrameworkCore.BulkOperations.Tests.csproj index 8ab3273a..ded3c38a 100644 --- a/tests/Thinktecture.EntityFrameworkCore.BulkOperations.Tests/Thinktecture.EntityFrameworkCore.BulkOperations.Tests.csproj +++ b/tests/Thinktecture.EntityFrameworkCore.BulkOperations.Tests/Thinktecture.EntityFrameworkCore.BulkOperations.Tests.csproj @@ -10,6 +10,7 @@ + diff --git a/tests/Thinktecture.EntityFrameworkCore.PostgreSQL.Tests/EntityFrameworkCore/BulkOperations/BulkOperationOutputMapperScalarTypeTests.cs b/tests/Thinktecture.EntityFrameworkCore.PostgreSQL.Tests/EntityFrameworkCore/BulkOperations/BulkOperationOutputMapperScalarTypeTests.cs new file mode 100644 index 00000000..2268d5a2 --- /dev/null +++ b/tests/Thinktecture.EntityFrameworkCore.PostgreSQL.Tests/EntityFrameworkCore/BulkOperations/BulkOperationOutputMapperScalarTypeTests.cs @@ -0,0 +1,48 @@ +using Microsoft.EntityFrameworkCore.Metadata; +using Thinktecture.EntityFrameworkCore.BulkOperations.Internal; + +namespace Thinktecture.EntityFrameworkCore.BulkOperations; + +// No database is needed: the failure happened while the mapper was created. +public class BulkOperationOutputMapperScalarTypeTests +{ + [Fact] + public void Should_create_the_mapper_for_all_scalar_types_of_the_provider() + { + var options = new DbContextOptionsBuilder().UseNpgsql("Host=localhost;Database=NotUsed").Options; + using var context = new ScalarDbContext(options); + + var entityType = context.Model.FindEntityType(typeof(ScalarEntity))!; + var storeObject = StoreObjectIdentifier.Create(entityType, StoreObjectType.Table)!.Value; + + var mapper = BulkOperationOutputMapper.Create(entityType, storeObject, true, []); + + mapper.Columns.Should().HaveCount(entityType.GetProperties().Count()); + } + + private sealed class ScalarEntity + { + public Guid Id { get; set; } + public DateTimeOffset At { get; set; } + public TimeSpan Span { get; set; } + public DateTime Moment { get; set; } + public DateOnly Day { get; set; } + public TimeOnly Time { get; set; } + public decimal Amount { get; set; } + public double Ratio { get; set; } + public float Small { get; set; } + public bool Flag { get; set; } + public short Short { get; set; } + public long Big { get; set; } + public char Letter { get; set; } + public byte[] Bytes { get; set; } = []; + public string Text { get; set; } = string.Empty; + public int[] Numbers { get; set; } = []; + public List Names { get; set; } = []; + } + + private sealed class ScalarDbContext(DbContextOptions options) : DbContext(options) + { + protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity().ToTable("Scalar"); + } +} \ No newline at end of file diff --git a/tests/Thinktecture.EntityFrameworkCore.PostgreSQL.Tests/EntityFrameworkCore/BulkOperations/NpgsqlBulkOperationExecutorTests/BulkOperationOutputAsync.cs b/tests/Thinktecture.EntityFrameworkCore.PostgreSQL.Tests/EntityFrameworkCore/BulkOperations/NpgsqlBulkOperationExecutorTests/BulkOperationOutputAsync.cs new file mode 100644 index 00000000..50df0f5e --- /dev/null +++ b/tests/Thinktecture.EntityFrameworkCore.PostgreSQL.Tests/EntityFrameworkCore/BulkOperations/NpgsqlBulkOperationExecutorTests/BulkOperationOutputAsync.cs @@ -0,0 +1,156 @@ +using Microsoft.EntityFrameworkCore.Infrastructure; +using Thinktecture.TestDatabaseContext; + +namespace Thinktecture.EntityFrameworkCore.BulkOperations.NpgsqlBulkOperationExecutorTests; + +public class BulkOperationOutputAsync : IntegrationTestsBase +{ + private static readonly Guid _EXISTING_ID = new("79DA4171-C90B-4A5D-B0B5-D0A1E1BDF966"); + private static readonly Guid _NEW_ID = new("3DAEA618-B732-4BCA-A5A1-D1E075022DEC"); + + public BulkOperationOutputAsync(ITestOutputHelper testOutputHelper, NpgsqlFixture fixture) + : base(testOutputHelper, fixture) + { + } + + [Fact] + public async Task BulkInsertOrUpdate_should_return_the_inserted_and_the_updated_rows() + { + var existingEntity = new TestEntity { Id = _EXISTING_ID, RequiredName = "Old", Count = 1 }; + ArrangeDbContext.Add(existingEntity); + await ArrangeDbContext.SaveChangesAsync(); + + existingEntity.RequiredName = "New"; + existingEntity.Count = 2; + var newEntity = new TestEntity { Id = _NEW_ID, RequiredName = "Inserted", Count = 3 }; + + var result = await ActDbContext.BulkInsertOrUpdateAsync(new[] { existingEntity, newEntity }, + new NpgsqlBulkInsertOrUpdateOptions(), + row => new { row.Inserted.Id, row.Inserted.RequiredName, row.Inserted.Count }); + + result.Should().BeEquivalentTo(new[] + { + new { Id = _EXISTING_ID, RequiredName = "New", Count = 2 }, + new { Id = _NEW_ID, RequiredName = "Inserted", Count = 3 } + }); + } + + [Fact] + public async Task BulkInsertOrUpdate_should_return_the_whole_entity_including_converted_properties_and_fields() + { + var entity = new TestEntity { Id = _NEW_ID, Name = "Name", RequiredName = "RequiredName", Count = 3, ConvertibleClass = new ConvertibleClass(42), PropertyWithBackingField = 7 }; + entity.SetPrivateField(5); + + var result = await ActDbContext.BulkInsertOrUpdateAsync(new[] { entity }, new NpgsqlBulkInsertOrUpdateOptions(), row => row.Inserted); + + var inserted = result.Should().ContainSingle().Subject; + inserted.Should().BeEquivalentTo(entity, options => options.Excluding(e => e.Parent).Excluding(e => e.Children)); + inserted.GetPrivateField().Should().Be(5); + } + + [Fact] + public async Task BulkInsertOrUpdate_should_request_only_the_columns_that_the_projection_reads() + { + var entity = new TestEntity { Id = _NEW_ID, RequiredName = "Name", Count = 3 }; + + var result = await ActDbContext.BulkInsertOrUpdateAsync(new[] { entity }, new NpgsqlBulkInsertOrUpdateOptions(), row => row.Inserted.Count); + + result.Should().Equal(3); + + ExecutedCommands.Should().Contain(command => command.Contains("RETURNING \"Count\"", StringComparison.Ordinal)) + .And.NotContain(command => command.Contains("RETURNING \"Id\"", StringComparison.Ordinal)); + } + + [Fact] + public async Task BulkInsertOrUpdate_should_return_an_empty_list_if_entities_is_empty() + { + var result = await ActDbContext.BulkInsertOrUpdateAsync(new List(), new NpgsqlBulkInsertOrUpdateOptions(), row => row.Inserted.Id); + + result.Should().BeEmpty(); + } + + [Fact] + public async Task BulkUpdate_should_return_the_updated_rows_only() + { + var existingEntity = new TestEntity { Id = _EXISTING_ID, RequiredName = "Old", Count = 1 }; + ArrangeDbContext.Add(existingEntity); + await ArrangeDbContext.SaveChangesAsync(); + + existingEntity.Count = 2; + var missingEntity = new TestEntity { Id = _NEW_ID, RequiredName = "Missing", Count = 9 }; + + var result = await ActDbContext.BulkUpdateAsync(new[] { existingEntity, missingEntity }, + new NpgsqlBulkUpdateOptions(), + row => new { row.Inserted.Id, row.Inserted.Count }); + + result.Should().BeEquivalentTo(new[] { new { Id = _EXISTING_ID, Count = 2 } }); + } + + [Fact] + public async Task Should_throw_if_the_projection_reads_a_navigation() + { + var entity = new TestEntity { Id = _NEW_ID, RequiredName = "Name" }; + + await ActDbContext.Awaiting(ctx => ctx.BulkInsertOrUpdateAsync(new[] { entity }, new NpgsqlBulkInsertOrUpdateOptions(), row => row.Inserted.Parent)) + .Should().ThrowAsync() + .WithMessage("'Parent' is not a scalar property*"); + } + + [Fact] + public async Task Should_return_the_concrete_types_of_a_TPH_hierarchy_with_a_concrete_base_type() + { + var shapes = TphTestData.CreateShapes(); + + var result = await ActDbContext.BulkInsertOrUpdateAsync(shapes, new NpgsqlBulkInsertOrUpdateOptions(), row => row.Inserted); + + result.Should().BeEquivalentTo(shapes.Cast(), options => options.PreferringRuntimeMemberTypes()); + result.Select(shape => shape.GetType()).Should().BeEquivalentTo(shapes.Select(shape => shape.GetType())); + } + + [Fact] + public async Task Should_return_the_stored_type_if_it_differs_from_the_type_of_the_input() + { + ArrangeDbContext.AddRange(TphTestData.CreateShapes()); + await ArrangeDbContext.SaveChangesAsync(); + + // The row is a circle. The input is a plain shape that only renames it, so the stored discriminator is kept. + var input = new Shape { Id = TphTestData.C1Id, Name = "renamed" }; + var options = new NpgsqlBulkInsertOrUpdateOptions { PropertiesToUpdate = IEntityPropertiesProvider.Include(shape => shape.Name) }; + + var result = await ActDbContext.BulkInsertOrUpdateAsync(new[] { input }, options, row => row.Inserted); + + var circle = result.Should().ContainSingle().Which.Should().BeOfType().Subject; + circle.Name.Should().Be("renamed"); + circle.Radius.Should().Be(3); + circle.Color.Should().Be("red"); + } + + [Fact] + public async Task Should_return_the_properties_of_an_abstract_TPH_base_type() + { + var documents = new List + { + new Invoice { Id = new Guid("5A0B1C2D-0031-4000-8000-000000000001"), Kind = 1, Title = "invoice", Total = 5 }, + new Report { Id = new Guid("5A0B1C2D-0031-4000-8000-000000000002"), Kind = 2, Title = "report", Pages = 3 } + }; + + var ids = await ActDbContext.BulkInsertOrUpdateAsync(documents, new NpgsqlBulkInsertOrUpdateOptions(), row => row.Inserted.Id); + + ids.Should().BeEquivalentTo(documents.Select(document => document.Id)); + + var whole = await ActDbContext.BulkInsertOrUpdateAsync(documents, new NpgsqlBulkInsertOrUpdateOptions(), row => row.Inserted); + + whole.Should().BeEquivalentTo(documents.Cast(), options => options.PreferringRuntimeMemberTypes()); + whole.Select(document => document.GetType()).Should().BeEquivalentTo(new[] { typeof(Invoice), typeof(Report) }); + } + + [Fact] + public async Task Should_throw_if_the_projection_reads_a_navigation_besides_the_whole_entity() + { + var entity = new TestEntity { Id = _NEW_ID, RequiredName = "Name" }; + + await ActDbContext.Awaiting(ctx => ctx.BulkInsertOrUpdateAsync(new[] { entity }, new NpgsqlBulkInsertOrUpdateOptions(), row => new { Entity = row.Inserted, row.Inserted.Parent })) + .Should().ThrowAsync() + .WithMessage("'Parent' is not a scalar property*"); + } +} diff --git a/tests/Thinktecture.EntityFrameworkCore.SqlServer.Tests/EntityFrameworkCore/BulkOperations/BulkOperationOutputMapperScalarTypeTests.cs b/tests/Thinktecture.EntityFrameworkCore.SqlServer.Tests/EntityFrameworkCore/BulkOperations/BulkOperationOutputMapperScalarTypeTests.cs new file mode 100644 index 00000000..8971c286 --- /dev/null +++ b/tests/Thinktecture.EntityFrameworkCore.SqlServer.Tests/EntityFrameworkCore/BulkOperations/BulkOperationOutputMapperScalarTypeTests.cs @@ -0,0 +1,48 @@ +using Microsoft.EntityFrameworkCore.Metadata; +using Thinktecture.EntityFrameworkCore.BulkOperations.Internal; + +namespace Thinktecture.EntityFrameworkCore.BulkOperations; + +// No database is needed: the failure happened while the mapper was created. +public class BulkOperationOutputMapperScalarTypeTests +{ + [Fact] + public void Should_create_the_mapper_for_all_scalar_types_of_the_provider() + { + var options = new DbContextOptionsBuilder().UseSqlServer("Server=.;Database=NotUsed").Options; + using var context = new TemporalDbContext(options); + + var entityType = context.Model.FindEntityType(typeof(TemporalEntity))!; + var storeObject = StoreObjectIdentifier.Create(entityType, StoreObjectType.Table)!.Value; + + // SqlServerDateTimeOffsetTypeMapping and SqlServerTimeOnlyTypeMapping use methods of SqlDataReader. + var mapper = BulkOperationOutputMapper.Create(entityType, storeObject, true, []); + + mapper.Columns.Select(column => column.ColumnName).Should().HaveCount(16); + } + + private sealed class TemporalEntity + { + public Guid Id { get; set; } + public DateTimeOffset At { get; set; } + public TimeSpan Span { get; set; } + public DateTime Moment { get; set; } + public DateOnly Day { get; set; } + public TimeOnly Time { get; set; } + public decimal Amount { get; set; } + public double Ratio { get; set; } + public float Small { get; set; } + public bool Flag { get; set; } + public byte Tiny { get; set; } + public short Short { get; set; } + public long Big { get; set; } + public char Letter { get; set; } + public byte[] Bytes { get; set; } = []; + public string Text { get; set; } = string.Empty; + } + + private sealed class TemporalDbContext(DbContextOptions options) : DbContext(options) + { + protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity().ToTable("Temporal"); + } +} \ No newline at end of file diff --git a/tests/Thinktecture.EntityFrameworkCore.SqlServer.Tests/EntityFrameworkCore/BulkOperations/SqlServerBulkOperationExecutorTests/MergeOutput.cs b/tests/Thinktecture.EntityFrameworkCore.SqlServer.Tests/EntityFrameworkCore/BulkOperations/SqlServerBulkOperationExecutorTests/MergeOutput.cs new file mode 100644 index 00000000..9737dce1 --- /dev/null +++ b/tests/Thinktecture.EntityFrameworkCore.SqlServer.Tests/EntityFrameworkCore/BulkOperations/SqlServerBulkOperationExecutorTests/MergeOutput.cs @@ -0,0 +1,269 @@ +using Thinktecture.EntityFrameworkCore.TempTables; +using Thinktecture.TestDatabaseContext; + +namespace Thinktecture.EntityFrameworkCore.BulkOperations.SqlServerBulkOperationExecutorTests; + +public class MergeOutput : IntegrationTestsBase +{ + private static readonly Guid _EXISTING_ID = new("79DA4171-C90B-4A5D-B0B5-D0A1E1BDF966"); + private static readonly Guid _NEW_ID = new("3DAEA618-B732-4BCA-A5A1-D1E075022DEC"); + + public MergeOutput(ITestOutputHelper testOutputHelper, SqlServerFixture sqlServerFixture) + : base(testOutputHelper, sqlServerFixture) + { + } + + [Fact] + public async Task Should_return_inserted_and_deleted_values_with_the_action_of_each_row() + { + var existingEntity = new TestEntity { Id = _EXISTING_ID, RequiredName = "Old", Count = 1 }; + ArrangeDbContext.Add(existingEntity); + await ArrangeDbContext.SaveChangesAsync(); + + existingEntity.RequiredName = "New"; + existingEntity.Count = 2; + var newEntity = new TestEntity { Id = _NEW_ID, RequiredName = "Inserted", Count = 3 }; + + var result = await ActDbContext.BulkInsertOrUpdateAsync( + new[] { existingEntity, newEntity }, + new SqlServerBulkInsertOrUpdateOptions(), + row => new { row.Inserted.Id, row.Inserted.Count, OldCount = row.Deleted.Count, OldNullableCount = row.Deleted.NullableCount, row.Action }); + + result.Should().BeEquivalentTo(new[] + { + new { Id = _EXISTING_ID, Count = 2, OldCount = 1, OldNullableCount = (int?)null, Action = SqlServerMergeAction.Update }, + // the deleted columns of an inserted row are NULL: a non-nullable property keeps its default value + new { Id = _NEW_ID, Count = 3, OldCount = 0, OldNullableCount = (int?)null, Action = SqlServerMergeAction.Insert } + }); + } + + [Fact] + public async Task Should_request_only_the_columns_that_the_projection_reads() + { + var entity = new TestEntity { Id = _NEW_ID, RequiredName = "Name", Count = 3 }; + + await ActDbContext.BulkInsertOrUpdateAsync(new[] { entity }, new SqlServerBulkInsertOrUpdateOptions(), row => row.Inserted.Id); + + var mergeStatement = ExecutedCommands.Should().ContainSingle(command => command.Contains("MERGE INTO", StringComparison.Ordinal)).Subject; + mergeStatement.Should().Contain("OUTPUT $action, inserted.[Id] INTO @MergeOutput ([Action], [i1]);") + .And.NotContain("deleted.") + .And.NotContain("inserted.[Count]"); + } + + [Fact] + public async Task Should_return_the_whole_entity_including_converted_properties_and_fields() + { + var entity = new TestEntity { Id = _NEW_ID, Name = "Name", RequiredName = "RequiredName", Count = 3, ConvertibleClass = new ConvertibleClass(42), PropertyWithBackingField = 7 }; + entity.SetPrivateField(5); + + var result = await ActDbContext.BulkInsertOrUpdateAsync(new[] { entity }, new SqlServerBulkInsertOrUpdateOptions(), row => row.Inserted); + + var inserted = result.Should().ContainSingle().Subject; + inserted.Should().BeEquivalentTo(entity, options => options.Excluding(e => e.Parent).Excluding(e => e.Children)); + inserted.GetPrivateField().Should().Be(5); + } + + [Fact] + public async Task Should_return_rows_of_a_table_with_an_enabled_trigger() + { + await ArrangeDbContext.Database.ExecuteSqlRawAsync($"CREATE TRIGGER [{Schema}].[TR_TestEntities_MergeOutput] ON [{Schema}].[TestEntities] AFTER INSERT, UPDATE AS BEGIN SET NOCOUNT ON; END"); + + try + { + var entity = new TestEntity { Id = _NEW_ID, RequiredName = "Name", Count = 3 }; + + var result = await ActDbContext.BulkInsertOrUpdateAsync(new[] { entity }, new SqlServerBulkInsertOrUpdateOptions(), row => row.Inserted.Id); + + result.Should().Equal(_NEW_ID); + } + finally + { + await ArrangeDbContext.Database.ExecuteSqlRawAsync($"DROP TRIGGER [{Schema}].[TR_TestEntities_MergeOutput]"); + } + } + + [Fact] + public async Task Should_return_updated_rows_of_BulkUpdate() + { + var existingEntity = new TestEntity { Id = _EXISTING_ID, RequiredName = "Old", Count = 1 }; + ArrangeDbContext.Add(existingEntity); + await ArrangeDbContext.SaveChangesAsync(); + + existingEntity.Count = 2; + var missingEntity = new TestEntity { Id = _NEW_ID, RequiredName = "Missing", Count = 9 }; + + var result = await ActDbContext.BulkUpdateAsync( + new[] { existingEntity, missingEntity }, + new SqlServerBulkUpdateOptions(), + row => new { row.Inserted.Id, row.Inserted.Count, OldCount = row.Deleted.Count, row.Action }); + + result.Should().BeEquivalentTo(new[] { new { Id = _EXISTING_ID, Count = 2, OldCount = 1, Action = SqlServerMergeAction.Update } }); + } + + [Fact] + public async Task Should_support_the_provider_independent_BulkOperationOutput_for_BulkInsertOrUpdate() + { + var existingEntity = new TestEntity { Id = _EXISTING_ID, RequiredName = "Old", Count = 1 }; + ArrangeDbContext.Add(existingEntity); + await ArrangeDbContext.SaveChangesAsync(); + + existingEntity.Count = 2; + var newEntity = new TestEntity { Id = _NEW_ID, RequiredName = "Inserted", Count = 3 }; + + // The options are typed as the interface, so the overload of BulkOperationOutput is selected. + IBulkInsertOrUpdateOptions options = new SqlServerBulkInsertOrUpdateOptions(); + var result = await ActDbContext.BulkInsertOrUpdateAsync(new[] { existingEntity, newEntity }, options, row => new { row.Inserted.Id, row.Inserted.Count }); + + result.Should().BeEquivalentTo(new[] + { + new { Id = _EXISTING_ID, Count = 2 }, + new { Id = _NEW_ID, Count = 3 } + }); + } + + [Fact] + public async Task Should_support_the_provider_independent_BulkOperationOutput_for_BulkUpdate() + { + var existingEntity = new TestEntity { Id = _EXISTING_ID, RequiredName = "Old", Count = 1 }; + ArrangeDbContext.Add(existingEntity); + await ArrangeDbContext.SaveChangesAsync(); + + existingEntity.Count = 2; + var missingEntity = new TestEntity { Id = _NEW_ID, RequiredName = "Missing", Count = 9 }; + + IBulkUpdateOptions options = new SqlServerBulkUpdateOptions(); + var result = await ActDbContext.BulkUpdateAsync(new[] { existingEntity, missingEntity }, options, row => row.Inserted); + + result.Should().ContainSingle().Which.Should().BeEquivalentTo(existingEntity, o => o.Excluding(e => e.Parent).Excluding(e => e.Children)); + } + + [Fact] + public async Task Should_throw_if_the_provider_independent_projection_uses_the_output_row_as_a_whole() + { + var entity = new TestEntity { Id = _NEW_ID, RequiredName = "Name" }; + IBulkInsertOrUpdateOptions options = new SqlServerBulkInsertOrUpdateOptions(); + + await ActDbContext.Awaiting(ctx => ctx.BulkInsertOrUpdateAsync(new[] { entity }, options, row => row)) + .Should().ThrowAsync() + .WithMessage("The projection must read the properties of the 'Inserted' member*"); + } + + [Fact] + public async Task Should_return_an_empty_list_if_entities_is_empty() + { + var result = await ActDbContext.BulkInsertOrUpdateAsync(new List(), new SqlServerBulkInsertOrUpdateOptions(), row => row.Inserted.Id); + + result.Should().BeEmpty(); + } + + [Fact] + public async Task Should_use_the_table_name_of_the_table_name_provider() + { + await ArrangeDbContext.Database.ExecuteSqlRawAsync($"SELECT TOP 0 * INTO [{Schema}].[TestEntities_MergeOutput] FROM [{Schema}].[TestEntities]"); + + try + { + var entity = new TestEntity { Id = _NEW_ID, RequiredName = "Name", Count = 3 }; + var options = new SqlServerBulkInsertOrUpdateOptions { TableNameProvider = IBulkOperationTableNameProvider.ForRootEntity("TestEntities_MergeOutput", Schema) }; + + var result = await ActDbContext.BulkInsertOrUpdateAsync(new[] { entity }, options, row => row.Inserted.Id); + + result.Should().Equal(_NEW_ID); + (await AssertDbContext.TestEntities.CountAsync()).Should().Be(0); + } + finally + { + await ArrangeDbContext.Database.ExecuteSqlRawAsync($"DROP TABLE [{Schema}].[TestEntities_MergeOutput]"); + } + } + + [Fact] + public async Task Should_throw_if_the_projection_reads_a_navigation() + { + var entity = new TestEntity { Id = _NEW_ID, RequiredName = "Name" }; + + await ActDbContext.Awaiting(ctx => ctx.BulkInsertOrUpdateAsync(new[] { entity }, new SqlServerBulkInsertOrUpdateOptions(), row => row.Inserted.Parent)) + .Should().ThrowAsync() + .WithMessage("'Parent' is not a scalar property*"); + } + + [Fact] + public async Task Should_return_the_concrete_types_of_a_TPH_hierarchy_with_a_concrete_base_type() + { + var shapes = TphTestData.CreateShapes(); + + var result = await ActDbContext.BulkInsertOrUpdateAsync(shapes, new SqlServerBulkInsertOrUpdateOptions(), row => row.Inserted); + + result.Should().BeEquivalentTo(shapes.Cast(), options => options.PreferringRuntimeMemberTypes()); + result.Select(shape => shape.GetType()).Should().BeEquivalentTo(shapes.Select(shape => shape.GetType())); + } + + [Fact] + public async Task Should_return_the_stored_type_if_it_differs_from_the_type_of_the_input() + { + ArrangeDbContext.AddRange(TphTestData.CreateShapes()); + await ArrangeDbContext.SaveChangesAsync(); + + // The row is a circle. The input is a plain shape that only renames it, so the stored discriminator is kept. + var input = new Shape { Id = TphTestData.C1Id, Name = "renamed" }; + var options = new SqlServerBulkInsertOrUpdateOptions { PropertiesToUpdate = IEntityPropertiesProvider.Include(shape => shape.Name) }; + + var result = await ActDbContext.BulkInsertOrUpdateAsync(new[] { input }, options, row => row.Inserted); + + var circle = result.Should().ContainSingle().Which.Should().BeOfType().Subject; + circle.Name.Should().Be("renamed"); + circle.Radius.Should().Be(3); + circle.Color.Should().Be("red"); + } + + [Fact] + public async Task Should_return_the_properties_of_an_abstract_TPH_base_type() + { + var documents = new List + { + new Invoice { Id = new Guid("5A0B1C2D-0031-4000-8000-000000000001"), Kind = 1, Title = "invoice", Total = 5 }, + new Report { Id = new Guid("5A0B1C2D-0031-4000-8000-000000000002"), Kind = 2, Title = "report", Pages = 3 } + }; + + var ids = await ActDbContext.BulkInsertOrUpdateAsync(documents, new SqlServerBulkInsertOrUpdateOptions(), row => row.Inserted.Id); + + ids.Should().BeEquivalentTo(documents.Select(document => document.Id)); + + var whole = await ActDbContext.BulkInsertOrUpdateAsync(documents, new SqlServerBulkInsertOrUpdateOptions(), row => row.Inserted); + + whole.Should().BeEquivalentTo(documents.Cast(), options => options.PreferringRuntimeMemberTypes()); + whole.Select(document => document.GetType()).Should().BeEquivalentTo(new[] { typeof(Invoice), typeof(Report) }); + } + + [Fact] + public async Task Should_throw_if_the_projection_reads_a_navigation_besides_the_whole_entity() + { + var entity = new TestEntity { Id = _NEW_ID, RequiredName = "Name" }; + + await ActDbContext.Awaiting(ctx => ctx.BulkInsertOrUpdateAsync(new[] { entity }, new SqlServerBulkInsertOrUpdateOptions(), row => new { Entity = row.Inserted, row.Inserted.Parent })) + .Should().ThrowAsync() + .WithMessage("'Parent' is not a scalar property*"); + } + [Fact] + public async Task Should_reset_properties_to_null_if_the_database_returns_NULL() + { + var newEntity = new TestEntity { Id = _NEW_ID, RequiredName = "Inserted", Count = 3 }; + + // TestEntity initializes RequiredName with an empty string. The deleted columns of an inserted row are NULL. + var result = await ActDbContext.BulkInsertOrUpdateAsync(new[] { newEntity }, + new SqlServerBulkInsertOrUpdateOptions(), + row => new { OldRequiredName = row.Deleted.RequiredName, OldCount = row.Deleted.Count }); + + result.Should().ContainSingle().Which.Should().Be(new { OldRequiredName = (string?)null, OldCount = 0 }); + } + + [Fact] + public async Task Should_throw_if_the_projection_reads_a_navigation_of_the_deleted_row_besides_the_whole_entity() + { + var entity = new TestEntity { Id = _NEW_ID, RequiredName = "Name" }; + + await ActDbContext.Awaiting(ctx => ctx.BulkInsertOrUpdateAsync(new[] { entity }, new SqlServerBulkInsertOrUpdateOptions(), row => new { Entity = row.Deleted, row.Deleted.Parent })) + .Should().ThrowAsync() + .WithMessage("'Parent' is not a scalar property*"); + } +} diff --git a/tests/Thinktecture.EntityFrameworkCore.Sqlite.Tests/EntityFrameworkCore/BulkOperations/SqliteBulkOperationExecutorTests/BulkOperationOutputAsync.cs b/tests/Thinktecture.EntityFrameworkCore.Sqlite.Tests/EntityFrameworkCore/BulkOperations/SqliteBulkOperationExecutorTests/BulkOperationOutputAsync.cs new file mode 100644 index 00000000..72c81e53 --- /dev/null +++ b/tests/Thinktecture.EntityFrameworkCore.Sqlite.Tests/EntityFrameworkCore/BulkOperations/SqliteBulkOperationExecutorTests/BulkOperationOutputAsync.cs @@ -0,0 +1,153 @@ +using Microsoft.EntityFrameworkCore.Infrastructure; +using Thinktecture.TestDatabaseContext; + +namespace Thinktecture.EntityFrameworkCore.BulkOperations.SqliteBulkOperationExecutorTests; + +public class BulkOperationOutputAsync : IntegrationTestsBase +{ + private static readonly Guid _EXISTING_ID = new("79DA4171-C90B-4A5D-B0B5-D0A1E1BDF966"); + private static readonly Guid _NEW_ID = new("3DAEA618-B732-4BCA-A5A1-D1E075022DEC"); + + public BulkOperationOutputAsync(ITestOutputHelper testOutputHelper, DbContextProviderFactoryFixture fixture) + : base(testOutputHelper, fixture) + { + } + + [Fact] + public async Task BulkInsertOrUpdate_should_return_the_inserted_and_the_updated_rows() + { + var existingEntity = new TestEntity { Id = _EXISTING_ID, RequiredName = "Old", Count = 1 }; + ArrangeDbContext.Add(existingEntity); + await ArrangeDbContext.SaveChangesAsync(); + + existingEntity.RequiredName = "New"; + existingEntity.Count = 2; + var newEntity = new TestEntity { Id = _NEW_ID, RequiredName = "Inserted", Count = 3 }; + + var result = await ActDbContext.BulkInsertOrUpdateAsync(new[] { existingEntity, newEntity }, + new SqliteBulkInsertOrUpdateOptions(), + row => new { row.Inserted.Id, row.Inserted.RequiredName, row.Inserted.Count }); + + result.Should().BeEquivalentTo(new[] + { + new { Id = _EXISTING_ID, RequiredName = "New", Count = 2 }, + new { Id = _NEW_ID, RequiredName = "Inserted", Count = 3 } + }); + } + + [Fact] + public async Task BulkInsertOrUpdate_should_return_the_whole_entity_including_converted_properties_and_fields() + { + var entity = new TestEntity { Id = _NEW_ID, Name = "Name", RequiredName = "RequiredName", Count = 3, ConvertibleClass = new ConvertibleClass(42), PropertyWithBackingField = 7 }; + entity.SetPrivateField(5); + + var result = await ActDbContext.BulkInsertOrUpdateAsync(new[] { entity }, new SqliteBulkInsertOrUpdateOptions(), row => row.Inserted); + + var inserted = result.Should().ContainSingle().Subject; + inserted.Should().BeEquivalentTo(entity, options => options.Excluding(e => e.Parent).Excluding(e => e.Children)); + inserted.GetPrivateField().Should().Be(5); + } + + [Fact] + public async Task BulkInsertOrUpdate_should_request_only_the_columns_that_the_projection_reads() + { + var entity = new TestEntity { Id = _NEW_ID, RequiredName = "Name", Count = 3 }; + + var result = await ActDbContext.BulkInsertOrUpdateAsync(new[] { entity }, new SqliteBulkInsertOrUpdateOptions(), row => row.Inserted.Count); + + result.Should().Equal(3); + } + + [Fact] + public async Task BulkInsertOrUpdate_should_return_an_empty_list_if_entities_is_empty() + { + var result = await ActDbContext.BulkInsertOrUpdateAsync(new List(), new SqliteBulkInsertOrUpdateOptions(), row => row.Inserted.Id); + + result.Should().BeEmpty(); + } + + [Fact] + public async Task BulkUpdate_should_return_the_updated_rows_only() + { + var existingEntity = new TestEntity { Id = _EXISTING_ID, RequiredName = "Old", Count = 1 }; + ArrangeDbContext.Add(existingEntity); + await ArrangeDbContext.SaveChangesAsync(); + + existingEntity.Count = 2; + var missingEntity = new TestEntity { Id = _NEW_ID, RequiredName = "Missing", Count = 9 }; + + var result = await ActDbContext.BulkUpdateAsync(new[] { existingEntity, missingEntity }, + new SqliteBulkUpdateOptions(), + row => new { row.Inserted.Id, row.Inserted.Count }); + + result.Should().BeEquivalentTo(new[] { new { Id = _EXISTING_ID, Count = 2 } }); + } + + [Fact] + public async Task Should_throw_if_the_projection_reads_a_navigation() + { + var entity = new TestEntity { Id = _NEW_ID, RequiredName = "Name" }; + + await ActDbContext.Awaiting(ctx => ctx.BulkInsertOrUpdateAsync(new[] { entity }, new SqliteBulkInsertOrUpdateOptions(), row => row.Inserted.Parent)) + .Should().ThrowAsync() + .WithMessage("'Parent' is not a scalar property*"); + } + + [Fact] + public async Task Should_return_the_concrete_types_of_a_TPH_hierarchy_with_a_concrete_base_type() + { + var shapes = TphTestData.CreateShapes(); + + var result = await ActDbContext.BulkInsertOrUpdateAsync(shapes, new SqliteBulkInsertOrUpdateOptions(), row => row.Inserted); + + result.Should().BeEquivalentTo(shapes.Cast(), options => options.PreferringRuntimeMemberTypes()); + result.Select(shape => shape.GetType()).Should().BeEquivalentTo(shapes.Select(shape => shape.GetType())); + } + + [Fact] + public async Task Should_return_the_stored_type_if_it_differs_from_the_type_of_the_input() + { + ArrangeDbContext.AddRange(TphTestData.CreateShapes()); + await ArrangeDbContext.SaveChangesAsync(); + + // The row is a circle. The input is a plain shape that only renames it, so the stored discriminator is kept. + var input = new Shape { Id = TphTestData.C1Id, Name = "renamed" }; + var options = new SqliteBulkInsertOrUpdateOptions { PropertiesToUpdate = IEntityPropertiesProvider.Include(shape => shape.Name) }; + + var result = await ActDbContext.BulkInsertOrUpdateAsync(new[] { input }, options, row => row.Inserted); + + var circle = result.Should().ContainSingle().Which.Should().BeOfType().Subject; + circle.Name.Should().Be("renamed"); + circle.Radius.Should().Be(3); + circle.Color.Should().Be("red"); + } + + [Fact] + public async Task Should_return_the_properties_of_an_abstract_TPH_base_type() + { + var documents = new List + { + new Invoice { Id = new Guid("5A0B1C2D-0031-4000-8000-000000000001"), Kind = 1, Title = "invoice", Total = 5 }, + new Report { Id = new Guid("5A0B1C2D-0031-4000-8000-000000000002"), Kind = 2, Title = "report", Pages = 3 } + }; + + var ids = await ActDbContext.BulkInsertOrUpdateAsync(documents, new SqliteBulkInsertOrUpdateOptions(), row => row.Inserted.Id); + + ids.Should().BeEquivalentTo(documents.Select(document => document.Id)); + + var whole = await ActDbContext.BulkInsertOrUpdateAsync(documents, new SqliteBulkInsertOrUpdateOptions(), row => row.Inserted); + + whole.Should().BeEquivalentTo(documents.Cast(), options => options.PreferringRuntimeMemberTypes()); + whole.Select(document => document.GetType()).Should().BeEquivalentTo(new[] { typeof(Invoice), typeof(Report) }); + } + + [Fact] + public async Task Should_throw_if_the_projection_reads_a_navigation_besides_the_whole_entity() + { + var entity = new TestEntity { Id = _NEW_ID, RequiredName = "Name" }; + + await ActDbContext.Awaiting(ctx => ctx.BulkInsertOrUpdateAsync(new[] { entity }, new SqliteBulkInsertOrUpdateOptions(), row => new { Entity = row.Inserted, row.Inserted.Parent })) + .Should().ThrowAsync() + .WithMessage("'Parent' is not a scalar property*"); + } +}