Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add nullability check to In-Memory Database #23094

Merged
merged 4 commits into from
Nov 9, 2020
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,8 @@ public static DbContextOptionsBuilder UseInMemoryDatabase(
extension = extension.WithDatabaseRoot(databaseRoot);
}

extension = extension.WithNullabilityCheckEnabled(true);

ConfigureWarnings(optionsBuilder);

((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension(extension);
Expand All @@ -133,6 +135,48 @@ public static DbContextOptionsBuilder UseInMemoryDatabase(
return optionsBuilder;
}

/// <summary>
/// <para>
/// Enables nullability check for all properties across all entities within the in-memory database.
/// </para>
/// </summary>
/// <typeparam name="TContext"> The type of context being configured. </typeparam>
/// <param name="optionsBuilder"> The builder being used to configure the context. </param>
/// <param name="nullabilityCheckEnabled"> If <see langword="true" />, then nullability check is enforced. </param>
/// <returns> The same builder instance so that multiple calls can be chained. </returns>
public static DbContextOptionsBuilder<TContext> EnableNullabilityCheck<TContext>(
[NotNull] this DbContextOptionsBuilder<TContext> optionsBuilder,
bool nullabilityCheckEnabled = true)
where TContext : DbContext
=> (DbContextOptionsBuilder<TContext>)EnableNullabilityCheck(
(DbContextOptionsBuilder)optionsBuilder, nullabilityCheckEnabled);

/// <summary>
/// <para>
/// Enables nullability check for all properties across all entities within the in-memory database.
/// </para>
/// </summary>
/// <param name="optionsBuilder"> The builder being used to configure the context. </param>
/// <param name="nullabilityCheckEnabled"> If <see langword="true" />, then nullability check is enforced. </param>
/// <returns> The same builder instance so that multiple calls can be chained. </returns>
public static DbContextOptionsBuilder EnableNullabilityCheck(
[NotNull] this DbContextOptionsBuilder optionsBuilder,
bool nullabilityCheckEnabled = true)
{
Check.NotNull(optionsBuilder, nameof(optionsBuilder));

var extension = optionsBuilder.Options.FindExtension<InMemoryOptionsExtension>()
?? new InMemoryOptionsExtension();

extension = extension.WithNullabilityCheckEnabled(nullabilityCheckEnabled);

ConfigureWarnings(optionsBuilder);

((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension(extension);

return optionsBuilder;
}

private static void ConfigureWarnings(DbContextOptionsBuilder optionsBuilder)
{
// Set warnings defaults
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,5 +30,13 @@ public interface IInMemorySingletonOptions : ISingletonOptions
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
InMemoryDatabaseRoot DatabaseRoot { get; }

/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
bool IsNullabilityCheckEnabled { get; }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ namespace Microsoft.EntityFrameworkCore.InMemory.Infrastructure.Internal
public class InMemoryOptionsExtension : IDbContextOptionsExtension
{
private string _storeName;
private bool _nullabilityCheckEnabled;
private InMemoryDatabaseRoot _databaseRoot;
private DbContextOptionsExtensionInfo _info;

Expand Down Expand Up @@ -72,6 +73,15 @@ protected virtual InMemoryOptionsExtension Clone()
public virtual string StoreName
=> _storeName;

/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual bool IsNullabilityCheckEnabled
=> _nullabilityCheckEnabled;

/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
Expand All @@ -87,6 +97,21 @@ public virtual InMemoryOptionsExtension WithStoreName([NotNull] string storeName
return clone;
}

/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual InMemoryOptionsExtension WithNullabilityCheckEnabled(bool nullabilityCheckEnabled)
{
var clone = Clone();

clone._nullabilityCheckEnabled = nullabilityCheckEnabled;

return clone;
}

/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ public virtual void Initialize(IDbContextOptions options)
if (inMemoryOptions != null)
{
DatabaseRoot = inMemoryOptions.DatabaseRoot;
IsNullabilityCheckEnabled = inMemoryOptions.IsNullabilityCheckEnabled;
}
}

Expand Down Expand Up @@ -68,5 +69,13 @@ public virtual void Validate(IDbContextOptions options)
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual InMemoryDatabaseRoot DatabaseRoot { get; private set; }

/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual bool IsNullabilityCheckEnabled { get; private set; }
}
}
16 changes: 16 additions & 0 deletions src/EFCore.InMemory/Properties/InMemoryStrings.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions src/EFCore.InMemory/Properties/InMemoryStrings.resx
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,12 @@
<data name="NoQueryStrings" xml:space="preserve">
<value>There is no query string because the in-memory provider does not use a string-based query language.</value>
</data>
<data name="NullabilityErrorException" xml:space="preserve">
<value>Required properties '{requiredProperties}' are missing for the instance of entity type '{entityType}'. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the entity key value.</value>
</data>
<data name="NullabilityErrorExceptionSensitive" xml:space="preserve">
<value>Required properties '{requiredProperties}' are missing for the instance of entity type '{entityType}' with the key value '{keyValue}'.</value>
</data>
<data name="UnableToBindMemberToEntityProjection" xml:space="preserve">
<value>Unable to bind '{memberType}' '{member}' to entity projection of '{entityType}'.</value>
</data>
Expand Down
82 changes: 76 additions & 6 deletions src/EFCore.InMemory/Storage/Internal/InMemoryTable.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ public class InMemoryTable<TKey> : IInMemoryTable
{
private readonly IPrincipalKeyValueFactory<TKey> _keyValueFactory;
private readonly bool _sensitiveLoggingEnabled;
private readonly bool _nullabilityCheckEnabled;
private readonly Dictionary<TKey, object[]> _rows;
private readonly IList<(int, ValueConverter)> _valueConverters;
private readonly IList<(int, ValueComparer)> _valueComparers;
Expand All @@ -39,12 +40,13 @@ public class InMemoryTable<TKey> : IInMemoryTable
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public InMemoryTable([NotNull] IEntityType entityType, [CanBeNull] IInMemoryTable baseTable, bool sensitiveLoggingEnabled)
public InMemoryTable([NotNull] IEntityType entityType, [CanBeNull] IInMemoryTable baseTable, bool sensitiveLoggingEnabled, bool nullabilityCheckEnabled)
{
EntityType = entityType;
BaseTable = baseTable;
_keyValueFactory = entityType.FindPrimaryKey().GetPrincipalKeyValueFactory<TKey>();
_sensitiveLoggingEnabled = sensitiveLoggingEnabled;
_nullabilityCheckEnabled = nullabilityCheckEnabled;
_rows = new Dictionary<TKey, object[]>(_keyValueFactory.EqualityComparer);

foreach (var property in entityType.GetProperties())
Expand Down Expand Up @@ -184,13 +186,26 @@ private static List<ValueComparer> GetKeyComparers(IEnumerable<IProperty> proper
/// </summary>
public virtual void Create(IUpdateEntry entry)
{
var row = entry.EntityType.GetProperties()
.Select(p => SnapshotValue(p, p.GetKeyValueComparer(), entry))
.ToArray();
var properties = entry.EntityType.GetProperties().ToList();
var rows = new object[properties.Count];
var nullabilityErrors = new List<IProperty>();

_rows.Add(CreateKey(entry), row);
for (var index = 0; index < properties.Count; index++)
fagnercarvalho marked this conversation as resolved.
Show resolved Hide resolved
{
var row = SnapshotValue(properties[index], properties[index].GetKeyValueComparer(), entry);
fagnercarvalho marked this conversation as resolved.
Show resolved Hide resolved

rows[index] = row;
HasNullabilityError(properties[index], row, nullabilityErrors);
}

if (nullabilityErrors.Count > 0)
{
ThrowNullabilityErrorException(entry, nullabilityErrors);
}

_rows.Add(CreateKey(entry), rows);

BumpValueGenerators(row);
BumpValueGenerators(rows);
}

/// <summary>
Expand Down Expand Up @@ -265,6 +280,7 @@ public virtual void Update(IUpdateEntry entry)
var comparers = GetKeyComparers(properties);
var valueBuffer = new object[properties.Count];
var concurrencyConflicts = new Dictionary<IProperty, object>();
var nullabilityErrors = new List<IProperty>();

for (var index = 0; index < valueBuffer.Length; index++)
{
Expand All @@ -273,6 +289,11 @@ public virtual void Update(IUpdateEntry entry)
continue;
}

if (HasNullabilityError(properties[index], row[index], nullabilityErrors))
{
continue;
}

valueBuffer[index] = entry.IsModified(properties[index])
? SnapshotValue(properties[index], comparers[index], entry)
: row[index];
Expand All @@ -283,6 +304,11 @@ public virtual void Update(IUpdateEntry entry)
ThrowUpdateConcurrencyException(entry, concurrencyConflicts);
}

if (nullabilityErrors.Count > 0)
{
ThrowNullabilityErrorException(entry, nullabilityErrors);
}

_rows[key] = valueBuffer;

BumpValueGenerators(valueBuffer);
Expand Down Expand Up @@ -336,6 +362,50 @@ private static object SnapshotValue(IProperty property, ValueComparer comparer,
private static object SnapshotValue(ValueComparer comparer, object value)
=> comparer == null ? value : comparer.Snapshot(value);

private bool HasNullabilityError(
IProperty property,
object rowValue,
IList<IProperty> nullabilityErrors)
{
if (!_nullabilityCheckEnabled)
{
return false;
}

if (!property.IsNullable && rowValue == null)
{
nullabilityErrors.Add(property);

return true;
}

return false;
}

private void ThrowNullabilityErrorException(
[NotNull] IUpdateEntry entry,
[NotNull] IList<IProperty> nullabilityErrors)
{
Check.NotNull(entry, nameof(entry));
Check.NotNull(nullabilityErrors, nameof(nullabilityErrors));

if (_sensitiveLoggingEnabled)
{
throw new DbUpdateException(
InMemoryStrings.NullabilityErrorExceptionSensitive(
nullabilityErrors.Format(),
entry.EntityType.DisplayName(),
entry.BuildCurrentValuesString(entry.EntityType.FindPrimaryKey().Properties)),
new[] { entry });
}

throw new DbUpdateException(
InMemoryStrings.NullabilityErrorException(
nullabilityErrors.Format(),
entry.EntityType.DisplayName()),
new[] { entry });
}

/// <summary>
/// Throws an exception indicating that concurrency conflicts were detected.
/// </summary>
Expand Down
17 changes: 13 additions & 4 deletions src/EFCore.InMemory/Storage/Internal/InMemoryTableFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,12 @@

using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Reflection;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.InMemory.Infrastructure.Internal;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Utilities;

Expand All @@ -20,6 +23,7 @@ namespace Microsoft.EntityFrameworkCore.InMemory.Storage.Internal
public class InMemoryTableFactory : IInMemoryTableFactory
{
private readonly bool _sensitiveLoggingEnabled;
private readonly bool _nullabilityCheckEnabled;

private readonly ConcurrentDictionary<(IEntityType EntityType, IInMemoryTable BaseTable), Func<IInMemoryTable>> _factories
= new ConcurrentDictionary<(IEntityType, IInMemoryTable), Func<IInMemoryTable>>();
Expand All @@ -30,11 +34,15 @@ public class InMemoryTableFactory : IInMemoryTableFactory
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public InMemoryTableFactory([NotNull] ILoggingOptions loggingOptions)
public InMemoryTableFactory(
[NotNull] ILoggingOptions loggingOptions,
[NotNull] IInMemorySingletonOptions options)
{
Check.NotNull(loggingOptions, nameof(loggingOptions));
Check.NotNull(options, nameof(options));

_sensitiveLoggingEnabled = loggingOptions.IsSensitiveDataLoggingEnabled;
_nullabilityCheckEnabled = options.IsNullabilityCheckEnabled;
}

/// <summary>
Expand All @@ -50,13 +58,14 @@ private Func<IInMemoryTable> CreateTable([NotNull] IEntityType entityType, IInMe
=> (Func<IInMemoryTable>)typeof(InMemoryTableFactory).GetTypeInfo()
.GetDeclaredMethod(nameof(CreateFactory))
.MakeGenericMethod(entityType.FindPrimaryKey().GetKeyType())
.Invoke(null, new object[] { entityType, baseTable, _sensitiveLoggingEnabled });
.Invoke(null, new object[] { entityType, baseTable, _sensitiveLoggingEnabled, _nullabilityCheckEnabled });

[UsedImplicitly]
private static Func<IInMemoryTable> CreateFactory<TKey>(
IEntityType entityType,
IInMemoryTable baseTable,
bool sensitiveLoggingEnabled)
=> () => new InMemoryTable<TKey>(entityType, baseTable, sensitiveLoggingEnabled);
bool sensitiveLoggingEnabled,
bool nullabilityCheckEnabled)
=> () => new InMemoryTable<TKey>(entityType, baseTable, sensitiveLoggingEnabled, nullabilityCheckEnabled);
}
}
6 changes: 6 additions & 0 deletions test/EFCore.InMemory.FunctionalTests/InMemoryFixture.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,12 @@ public class InMemoryFixture
public static IServiceProvider DefaultSensitiveServiceProvider { get; }
= BuildServiceProvider();

public static IServiceProvider DefaultNullabilityCheckProvider { get; }
= BuildServiceProvider();

public static IServiceProvider DefaultNullabilitySensitiveCheckProvider { get; }
= BuildServiceProvider();

public readonly IServiceProvider ServiceProvider;

public InMemoryFixture()
Expand Down
Loading