Skip to content

Commit

Permalink
Update handling for bools and enums with database defaults
Browse files Browse the repository at this point in the history
Fixes #15070

- Warn for enums like we do for bools
- Don't warn if a sentinel value has been configured
- Update warning message to mention sentinel value
- Set the sentinel by convention for non-nullable bools with a default value
  • Loading branch information
ajcvickers committed May 9, 2023
1 parent a9a2411 commit 161b71c
Show file tree
Hide file tree
Showing 11 changed files with 300 additions and 72 deletions.
19 changes: 16 additions & 3 deletions src/EFCore.Relational/Diagnostics/RelationalLoggerExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2505,7 +2505,14 @@ private static string ModelValidationKeyDefaultValueWarning(EventDefinitionBase

if (diagnostics.ShouldLog(definition))
{
definition.Log(diagnostics, property.Name, property.DeclaringEntityType.DisplayName());
var defaultValue = property.ClrType.GetDefaultValue();
definition.Log(
diagnostics,
property.ClrType.ShortDisplayName(),
property.Name,
property.DeclaringEntityType.DisplayName(),
defaultValue == null ? "null" : defaultValue.ToString()!,
property.ClrType.ShortDisplayName());
}

if (diagnostics.NeedsEventData(definition, out var diagnosticSourceEnabled, out var simpleLogEnabled))
Expand All @@ -2521,9 +2528,15 @@ private static string ModelValidationKeyDefaultValueWarning(EventDefinitionBase

private static string BoolWithDefaultWarning(EventDefinitionBase definition, EventData payload)
{
var d = (EventDefinition<string, string>)definition;
var d = (EventDefinition<string, string, string, string, string>)definition;
var p = (PropertyEventData)payload;
return d.GenerateMessage(p.Property.Name, p.Property.DeclaringEntityType.DisplayName());
var defaultValue = p.Property.ClrType.GetDefaultValue();
return d.GenerateMessage(
p.Property.ClrType.ShortDisplayName(),
p.Property.Name,
p.Property.DeclaringEntityType.DisplayName(),
defaultValue == null ? "null" : defaultValue.ToString()!,
p.Property.ClrType.ShortDisplayName());
}

/// <summary>
Expand Down
15 changes: 9 additions & 6 deletions src/EFCore.Relational/Infrastructure/RelationalModelValidator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -675,21 +675,24 @@ public override void Validate(IModel model, IDiagnosticsLogger<DbLoggerCategory.
{
foreach (var property in entityType.GetDeclaredProperties())
{
if (property.ClrType == typeof(bool)
if (!property.ClrType.IsNullableType()
&& (property.ClrType.IsEnum || property.ClrType == typeof(bool))
&& property.ValueGenerated != ValueGenerated.Never
&& property.FieldInfo?.FieldType != typeof(bool?)
&& property.FieldInfo?.FieldType.IsNullableType() != true
&& !((IConventionProperty)property).GetSentinelConfigurationSource().HasValue
&& (StoreObjectIdentifier.Create(property.DeclaringEntityType, StoreObjectType.Table) is { } table
&& (IsNotNullAndFalse(property.GetDefaultValue(table))
&& (IsNotNullAndNotDefault(property.GetDefaultValue(table))
|| property.GetDefaultValueSql(table) != null)))
{
logger.BoolWithDefaultWarning(property);
}

bool IsNotNullAndNotDefault(object? value)
=> value != null
&& !property.ClrType.IsDefaultValue(value);
}
}

static bool IsNotNullAndFalse(object? value)
=> value != null
&& (value is not bool asBool || asBool);
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,16 @@ public class RelationalValueGenerationConvention :
switch (name)
{
case RelationalAnnotationNames.DefaultValue:
if ((((IProperty)property).TryGetMemberInfo(forMaterialization: false, forSet: false, out var member, out _)
? member!.GetMemberType()
: property.ClrType)
== typeof(bool)
&& Equals(true, property.GetDefaultValue()))
{
propertyBuilder.HasSentinel(true);
}

goto case RelationalAnnotationNames.DefaultValueSql;
case RelationalAnnotationNames.DefaultValueSql:
case RelationalAnnotationNames.ComputedColumnSql:
propertyBuilder.ValueGenerated(GetValueGenerated(property));
Expand Down
10 changes: 5 additions & 5 deletions src/EFCore.Relational/Properties/RelationalStrings.Designer.cs

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

58 changes: 29 additions & 29 deletions src/EFCore.Relational/Properties/RelationalStrings.resx
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
Expand All @@ -26,36 +26,36 @@
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
Expand Down Expand Up @@ -593,8 +593,8 @@
<comment>Debug RelationalEventId.TransactionStarting string</comment>
</data>
<data name="LogBoolWithDefaultWarning" xml:space="preserve">
<value>The 'bool' property '{property}' on entity type '{entityType}' is configured with a database-generated default. This default will always be used for inserts when the property has the value 'false', since this is the CLR default for the 'bool' type. Consider using the nullable 'bool?' type instead, so that the default will only be used for inserts when the property value is 'null'.</value>
<comment>Warning RelationalEventId.BoolWithDefaultWarning string string</comment>
<value>The '{type}' property '{property}' on entity type '{entityType}' is configured with a database-generated default, but has no configured sentinel value. The database-generated default will always be used for inserts when the property has the value '{defaultValue}', since this is the CLR default for the '{type2}' type. Consider using a nullable type, using a nullable backing field, or setting the sentinel value for the property to ensure the database default is used when, and only when, appropriate. See https://aka.ms/efcore-docs-default-values for more information.</value>
<comment>Warning RelationalEventId.BoolWithDefaultWarning string string string string string</comment>
</data>
<data name="LogClosedConnection" xml:space="preserve">
<value>Closed connection to database '{database}' on server '{server}' ({elapsed}ms).</value>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,15 +112,14 @@ public override void Detects_missing_discriminator_property()
[ConditionalFact]
public virtual void Ignores_bool_with_default_value_false()
{
var modelBuilder = CreateConventionlessModelBuilder();
var modelBuilder = CreateConventionModelBuilder();
var model = modelBuilder.Model;

var entityType = model.AddEntityType(typeof(E));
SetPrimaryKey(entityType);
entityType.AddProperty("ImNot", typeof(bool?)).SetDefaultValue(false);
entityType.AddProperty("ImNotUsed", typeof(bool)).SetDefaultValue(false);
entityType.FindProperty("ImNot")!.SetDefaultValue(false);
entityType.FindProperty("ImNotUsed")!.SetDefaultValue(false);

var property = entityType.AddProperty("ImBool", typeof(bool));
var property = entityType.FindProperty("ImBool")!;
property.SetDefaultValue(false);
property.ValueGenerated = ValueGenerated.OnAdd;

Expand All @@ -130,61 +129,134 @@ public virtual void Ignores_bool_with_default_value_false()
}

[ConditionalFact]
public virtual void Detects_bool_with_default_value_not_false()
public virtual void Bool_with_true_default_value_okay_because_sentinel_set_to_true()
{
var modelBuilder = CreateConventionlessModelBuilder();
var modelBuilder = CreateConventionModelBuilder();
var model = modelBuilder.Model;

var entityType = model.AddEntityType(typeof(E));
SetPrimaryKey(entityType);
entityType.AddProperty("ImNot", typeof(bool?)).SetDefaultValue(true);
entityType.AddProperty("ImNotUsed", typeof(bool)).SetDefaultValue(true);
entityType.FindProperty("ImNot")!.SetDefaultValue(true);
entityType.FindProperty("ImNotUsed")!.SetDefaultValue(true);

var property = entityType.AddProperty("ImBool", typeof(bool));
var property = entityType.FindProperty("ImBool")!;
property.SetDefaultValue(true);
property.ValueGenerated = ValueGenerated.OnAdd;

VerifyWarning(
RelationalResources.LogBoolWithDefaultWarning(new TestLogger<TestRelationalLoggingDefinitions>())
.GenerateMessage("ImBool", "E"), modelBuilder);
Assert.True((bool)property.Sentinel!);

Assert.DoesNotContain(LoggerFactory.Log, l => l.Level == LogLevel.Warning);
}

[ConditionalFact] // Issue #28509
public virtual void Bool_with_default_value_and_nullable_backing_field_is_fine()
{
var modelBuilder = CreateConventionlessModelBuilder();
var modelBuilder = CreateConventionModelBuilder();
var model = modelBuilder.Model;

var entityType = model.AddEntityType(typeof(E2));
SetPrimaryKey(entityType);
var property = entityType.AddProperty(typeof(E2).GetAnyProperty("ImBool")!);
var property = entityType.FindProperty("ImBool")!;
property.SetField("_imBool");
property.SetDefaultValue(true);
property.ValueGenerated = ValueGenerated.OnAdd;

VerifyLogDoesNotContain(
RelationalResources.LogBoolWithDefaultWarning(new TestLogger<TestRelationalLoggingDefinitions>())
.GenerateMessage("ImBool", "E2"), modelBuilder);
Assert.DoesNotContain(LoggerFactory.Log, l => l.Level == LogLevel.Warning);
}

[ConditionalFact]
public virtual void Detects_bool_with_default_expression()
{
var modelBuilder = CreateConventionlessModelBuilder();
var modelBuilder = CreateConventionModelBuilder();
var model = modelBuilder.Model;

var entityType = model.AddEntityType(typeof(E));
SetPrimaryKey(entityType);
entityType.AddProperty("ImNot", typeof(bool?)).SetDefaultValueSql("TRUE");
entityType.AddProperty("ImNotUsed", typeof(bool)).SetDefaultValueSql("TRUE");

var property = entityType.AddProperty("ImBool", typeof(bool));
entityType.FindProperty("ImNot")!.SetDefaultValueSql("TRUE");
var property = entityType.FindProperty("ImBool")!;
property.SetDefaultValueSql("TRUE");
property.ValueGenerated = ValueGenerated.OnAddOrUpdate;

VerifyWarning(
RelationalResources.LogBoolWithDefaultWarning(new TestLogger<TestRelationalLoggingDefinitions>())
.GenerateMessage("ImBool", "E"), modelBuilder);
.GenerateMessage("bool", "ImBool", "E", "False", "bool"), modelBuilder);
}

[ConditionalFact]
public virtual void Ignores_enum_with_default_value_matching_CLR_default()
{
var modelBuilder = CreateConventionModelBuilder();
var model = modelBuilder.Model;

var entityType = model.AddEntityType(typeof(WithEnum));
entityType.FindProperty(nameof(WithEnum.EnumWithDefaultConstraint))!.SetDefaultValue(X.A);
entityType.FindProperty(nameof(WithEnum.NullableEnum))!.SetDefaultValue(X.B);

Validate(modelBuilder);

Assert.DoesNotContain(LoggerFactory.Log, l => l.Level == LogLevel.Warning);
}

[ConditionalFact]
public virtual void Detects_enum_with_database_default_not_set_to_CLR_default()
{
var modelBuilder = CreateConventionModelBuilder();
var model = modelBuilder.Model;

var entityType = model.AddEntityType(typeof(WithEnum));
entityType.FindProperty(nameof(WithEnum.EnumWithDefaultConstraint))!.SetDefaultValue(X.B);
entityType.FindProperty(nameof(WithEnum.NullableEnum))!.SetDefaultValue(X.B);

Validate(modelBuilder);

VerifyWarning(
RelationalResources.LogBoolWithDefaultWarning(new TestLogger<TestRelationalLoggingDefinitions>())
.GenerateMessage("X", "EnumWithDefaultConstraint", "WithEnum", "A", "X"), modelBuilder);
}

[ConditionalFact]
public virtual void Enum_with_database_default_not_set_to_CLR_default_okay_if_sentinel_set()
{
var modelBuilder = CreateConventionModelBuilder();
var model = modelBuilder.Model;

var entityType = model.AddEntityType(typeof(WithEnum));
var property = entityType.FindProperty(nameof(WithEnum.EnumWithDefaultConstraint))!;
property.SetDefaultValue(X.B);
property.Sentinel = X.B;
entityType.FindProperty(nameof(WithEnum.NullableEnum))!.SetDefaultValue(X.B);

Validate(modelBuilder);

Assert.DoesNotContain(LoggerFactory.Log, l => l.Level == LogLevel.Warning);
}

[ConditionalFact]
public virtual void Enum_with_database_default_not_set_to_CLR_default_and_nullable_backing_field_is_fine()
{
var modelBuilder = CreateConventionModelBuilder();
var model = modelBuilder.Model;

var entityType = model.AddEntityType(typeof(WithEnum2));
entityType.FindProperty(nameof(WithEnum2.EnumWithDefaultConstraint))!.SetDefaultValue(X.B);

Validate(modelBuilder);

Assert.DoesNotContain(LoggerFactory.Log, l => l.Level == LogLevel.Warning);
}

[ConditionalFact]
public virtual void Detects_enum_with_default_expression()
{
var modelBuilder = CreateConventionModelBuilder();
var model = modelBuilder.Model;

var entityType = model.AddEntityType(typeof(WithEnum));
entityType.FindProperty(nameof(WithEnum.EnumWithDefaultConstraint))!.SetDefaultValueSql("SQL");
entityType.FindProperty(nameof(WithEnum.NullableEnum))!.SetDefaultValueSql("SQL");

Validate(modelBuilder);

VerifyWarning(
RelationalResources.LogBoolWithDefaultWarning(new TestLogger<TestRelationalLoggingDefinitions>())
.GenerateMessage("X", "EnumWithDefaultConstraint", "WithEnum", "A", "X"), modelBuilder);
}

[ConditionalFact]
Expand All @@ -195,10 +267,10 @@ public virtual void Detects_primary_key_with_default_value()

var entityA = model.AddEntityType(typeof(A));
SetPrimaryKey(entityA);
entityA.FindProperty("Id").SetDefaultValue(1);
entityA.FindProperty("Id")!.SetDefaultValue(1);
AddProperties(entityA);

entityA.FindProperty("Id").SetDefaultValue(1);
entityA.FindProperty("Id")!.SetDefaultValue(1);

VerifyWarning(
RelationalResources.LogKeyHasDefaultValue(
Expand Down
Loading

0 comments on commit 161b71c

Please sign in to comment.