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

We love short SQL! #21851

Merged
1 commit merged into from
Jul 30, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions src/EFCore.Cosmos/Properties/CosmosStrings.Designer.cs

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

3 changes: 3 additions & 0 deletions src/EFCore.Cosmos/Properties/CosmosStrings.resx
Original file line number Diff line number Diff line change
Expand Up @@ -198,4 +198,7 @@
<data name="ConnectionStringConflictingConfiguration" xml:space="preserve">
<value>Both the connection string and account key or account endpoint were specified. Only specify one set of connection details.</value>
</data>
<data name="InvalidDerivedTypeInEntityProjection" xml:space="preserve">
<value>'UpdateEntityType' called with '{derivedType}' which is not derived type of '{entityType}'.</value>
</data>
</root>
Original file line number Diff line number Diff line change
Expand Up @@ -711,6 +711,53 @@ protected override ShapedQueryExpression TranslateOfType(ShapedQueryExpression s
Check.NotNull(source, nameof(source));
Check.NotNull(resultType, nameof(resultType));

if (source.ShaperExpression is EntityShaperExpression entityShaperExpression)
{
var entityType = entityShaperExpression.EntityType;
if (entityType.ClrType == resultType)
{
return source;
}

var parameterExpression = Expression.Parameter(entityShaperExpression.Type);
var predicate = Expression.Lambda(Expression.TypeIs(parameterExpression, resultType), parameterExpression);
var translation = TranslateLambdaExpression(source, predicate);
if (translation == null)
{
// EntityType is not part of hierarchy
return null;
}

var selectExpression = (SelectExpression)source.QueryExpression;
if (!(translation is SqlConstantExpression sqlConstantExpression
&& sqlConstantExpression.Value is bool constantValue
&& constantValue))
{
selectExpression.ApplyPredicate(translation);
}

var baseType = entityType.GetAllBaseTypes().SingleOrDefault(et => et.ClrType == resultType);
if (baseType != null)
{
return source.UpdateShaperExpression(entityShaperExpression.WithEntityType(baseType));
}

var derivedType = entityType.GetDerivedTypes().Single(et => et.ClrType == resultType);
var projectionBindingExpression = (ProjectionBindingExpression)entityShaperExpression.ValueBufferExpression;

var projectionMember = projectionBindingExpression.ProjectionMember;
Check.DebugAssert(new ProjectionMember().Equals(projectionMember), "Invalid ProjectionMember when processing OfType");

var entityProjectionExpression = (EntityProjectionExpression)selectExpression.GetMappedProjection(projectionMember);
selectExpression.ReplaceProjectionMapping(
new Dictionary<ProjectionMember, Expression>
{
{ projectionMember, entityProjectionExpression.UpdateEntityType(derivedType) }
});

return source.UpdateShaperExpression(entityShaperExpression.WithEntityType(derivedType));
}

return null;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -598,6 +598,43 @@ protected override Expression VisitUnary(UnaryExpression unaryExpression)
return null;
}

/// <inheritdoc />
protected override Expression VisitTypeBinary(TypeBinaryExpression typeBinaryExpression)
{
Check.NotNull(typeBinaryExpression, nameof(typeBinaryExpression));

var innerExpression = Visit(typeBinaryExpression.Expression);

if (typeBinaryExpression.NodeType == ExpressionType.TypeIs
&& innerExpression is EntityReferenceExpression entityReferenceExpression)
{
var entityType = entityReferenceExpression.EntityType;
if (entityType.GetAllBaseTypesInclusive().Any(et => et.ClrType == typeBinaryExpression.TypeOperand))
{
return _sqlExpressionFactory.Constant(true);
}

var derivedType = entityType.GetDerivedTypes().SingleOrDefault(et => et.ClrType == typeBinaryExpression.TypeOperand);
if (derivedType != null
&& TryBindMember(entityReferenceExpression,
MemberIdentity.Create(entityType.GetDiscriminatorProperty().Name)) is SqlExpression discriminatorColumn)
{
var concreteEntityTypes = derivedType.GetConcreteDerivedTypesInclusive().ToList();

return concreteEntityTypes.Count == 1
? _sqlExpressionFactory.Equal(
discriminatorColumn,
_sqlExpressionFactory.Constant(concreteEntityTypes[0].GetDiscriminatorValue()))
: (SqlExpression)_sqlExpressionFactory.In(
discriminatorColumn,
_sqlExpressionFactory.Constant(concreteEntityTypes.Select(et => et.GetDiscriminatorValue()).ToList()),
negated: false);
}
}

return null;
}

private Expression TryBindMember(Expression source, MemberIdentity member)
{
if (!(source is EntityReferenceExpression entityReferenceExpression))
Expand Down
43 changes: 29 additions & 14 deletions src/EFCore.Cosmos/Query/Internal/EntityProjectionExpression.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using System.Linq.Expressions;
using System.Reflection;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Cosmos.Internal;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Query;
Expand All @@ -22,10 +23,10 @@ namespace Microsoft.EntityFrameworkCore.Cosmos.Query.Internal
/// </summary>
public class EntityProjectionExpression : Expression, IPrintableExpression, IAccessExpression
{
private readonly IDictionary<IProperty, IAccessExpression> _propertyExpressionsCache
private readonly IDictionary<IProperty, IAccessExpression> _propertyExpressionsMap
= new Dictionary<IProperty, IAccessExpression>();

private readonly IDictionary<INavigation, IAccessExpression> _navigationExpressionsCache
private readonly IDictionary<INavigation, IAccessExpression> _navigationExpressionsMap
= new Dictionary<INavigation, IAccessExpression>();

/// <summary>
Expand Down Expand Up @@ -121,10 +122,10 @@ public virtual Expression BindProperty([NotNull] IProperty property, bool client
"GetProperty", nameof(IProperty), EntityType.DisplayName(), $"Property:{property.Name}"));
}

if (!_propertyExpressionsCache.TryGetValue(property, out var expression))
if (!_propertyExpressionsMap.TryGetValue(property, out var expression))
{
expression = new KeyAccessExpression(property, AccessExpression);
_propertyExpressionsCache[property] = expression;
_propertyExpressionsMap[property] = expression;
}

if (!clientEval
Expand Down Expand Up @@ -153,20 +154,15 @@ public virtual Expression BindNavigation([NotNull] INavigation navigation, bool
"GetNavigation", nameof(INavigation), EntityType.DisplayName(), $"Navigation:{navigation.Name}"));
}

if (!_navigationExpressionsCache.TryGetValue(navigation, out var expression))
if (!_navigationExpressionsMap.TryGetValue(navigation, out var expression))
{
if (navigation.IsCollection)
{
expression = new ObjectArrayProjectionExpression(navigation, AccessExpression);
}
else
{
expression = new EntityProjectionExpression(
expression = navigation.IsCollection
? new ObjectArrayProjectionExpression(navigation, AccessExpression)
: (IAccessExpression)new EntityProjectionExpression(
navigation.TargetEntityType,
new ObjectAccessExpression(navigation, AccessExpression));
}

_navigationExpressionsCache[navigation] = expression;
_navigationExpressionsMap[navigation] = expression;
}

if (!clientEval
Expand Down Expand Up @@ -231,6 +227,25 @@ private Expression BindMember(MemberIdentity member, Type entityClrType, bool cl
return null;
}

/// <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 EntityProjectionExpression UpdateEntityType([NotNull] IEntityType derivedType)
{
Check.NotNull(derivedType, nameof(derivedType));
smitpatel marked this conversation as resolved.
Show resolved Hide resolved

if (!derivedType.GetAllBaseTypes().Contains(EntityType))
{
throw new InvalidOperationException(CosmosStrings.InvalidDerivedTypeInEntityProjection(
derivedType.DisplayName(), EntityType.DisplayName()));
}

return new EntityProjectionExpression(derivedType, AccessExpression);
}

/// <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
10 changes: 9 additions & 1 deletion src/EFCore.InMemory/Properties/InMemoryStrings.Designer.cs

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

57 changes: 30 additions & 27 deletions src/EFCore.InMemory/Properties/InMemoryStrings.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 @@ -143,4 +143,7 @@
<data name="DefaultIfEmptyAppliedAfterProjection" xml:space="preserve">
<value>Cannot apply DefaultIfEmpty after a client-evaluated projection.</value>
</data>
<data name="InvalidDerivedTypeInEntityProjection" xml:space="preserve">
<value>'UpdateEntityType' called with '{derivedType}' which is not derived type of '{entityType}'.</value>
</data>
</root>
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.InMemory.Internal;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Query;
using Microsoft.EntityFrameworkCore.Utilities;
Expand Down Expand Up @@ -68,6 +70,12 @@ public EntityProjectionExpression(
/// </summary>
public virtual EntityProjectionExpression UpdateEntityType([NotNull] IEntityType derivedType)
{
if (!derivedType.GetAllBaseTypes().Contains(EntityType))
{
throw new InvalidOperationException(InMemoryStrings.InvalidDerivedTypeInEntityProjection(
derivedType.DisplayName(), EntityType.DisplayName()));
}

var readExpressionMap = new Dictionary<IProperty, Expression>();
foreach (var kvp in _readExpressionMap)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -808,7 +808,7 @@ protected override Expression VisitTypeBinary(TypeBinaryExpression typeBinaryExp
}
}

return Expression.Constant(false);
return null;
}

/// <summary>
Expand Down
Loading