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

Query: Change JSONQuery.Path to be list of PathSegment #28888

Merged
merged 1 commit into from
Sep 8, 2022
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
43 changes: 2 additions & 41 deletions src/EFCore.Relational/Query/EntityProjectionExpression.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public class EntityProjectionExpression : Expression
/// <summary>
/// Creates a new instance of the <see cref="EntityProjectionExpression" /> class.
/// </summary>
/// <param name="entityType">The entity type to shape.</param>
/// <param name="entityType">An entity type to shape.</param>
/// <param name="propertyExpressionMap">A dictionary of column expressions corresponding to properties of the entity type.</param>
/// <param name="discriminatorExpression">A <see cref="SqlExpression" /> to generate discriminator for each concrete entity type in hierarchy.</param>
public EntityProjectionExpression(
Expand Down Expand Up @@ -115,26 +115,15 @@ public virtual EntityProjectionExpression MakeNullable()
discriminatorExpression = ce.MakeNullable();
}

var primaryKeyProperties = GetMappedKeyProperties(EntityType.FindPrimaryKey()!);
var ownedNavigationMap = new Dictionary<INavigation, EntityShaperExpression>();
foreach (var (navigation, shaper) in _ownedNavigationMap)
{
if (shaper.EntityType.IsMappedToJson())
{
// even if shaper is nullable, we need to make sure key property map contains nullable keys,
// if json entity itself is optional, the shaper would be null, but the PK of the owner entity would be non-nullable intially
Debug.Assert(primaryKeyProperties != null, "Json entity type can't be keyless");

var jsonQueryExpression = (JsonQueryExpression)shaper.ValueBufferExpression;
var ownedPrimaryKeyProperties = GetMappedKeyProperties(shaper.EntityType.FindPrimaryKey()!)!;
var nullableKeyPropertyMap = new Dictionary<IProperty, ColumnExpression>();
for (var i = 0; i < primaryKeyProperties.Count; i++)
{
nullableKeyPropertyMap[ownedPrimaryKeyProperties[i]] = propertyExpressionMap[primaryKeyProperties[i]];
}

// reuse key columns from owner (that we just made nullable), so that the references are the same
var newJsonQueryExpression = jsonQueryExpression.MakeNullable(nullableKeyPropertyMap);
var newJsonQueryExpression = jsonQueryExpression.MakeNullable();
var newShaper = shaper.Update(newJsonQueryExpression).MakeNullable();
ownedNavigationMap[navigation] = newShaper;
}
Expand All @@ -145,34 +134,6 @@ public virtual EntityProjectionExpression MakeNullable()
propertyExpressionMap,
ownedNavigationMap,
discriminatorExpression);

static IReadOnlyList<IProperty>? GetMappedKeyProperties(IKey? key)
{
if (key == null)
{
return null;
}

if (!key.DeclaringEntityType.IsMappedToJson())
{
return key.Properties;
}

// TODO: fix this once we enable json entity being owned by another owned non-json entity (issue #28441)

// for json collections we need to filter out the ordinal key as it's not mapped to any column
// there could be multiple of these in deeply nested structures,
// so we traverse to the outermost owner to see how many mapped keys there are
var currentEntity = key.DeclaringEntityType;
while (currentEntity.IsMappedToJson())
{
currentEntity = currentEntity.FindOwnership()!.PrincipalEntityType;
}

var count = currentEntity.FindPrimaryKey()!.Properties.Count;

return key.Properties.Take(count).ToList();
}
}

/// <summary>
Expand Down
106 changes: 42 additions & 64 deletions src/EFCore.Relational/Query/JsonQueryExpression.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,48 +3,53 @@

using Microsoft.EntityFrameworkCore.Query.SqlExpressions;

namespace Microsoft.EntityFrameworkCore.Query
{
namespace Microsoft.EntityFrameworkCore.Query;

/// <summary>
/// Expression representing an entity or a collection of entities mapped to a JSON column and the path to access it.
/// <para>
/// An expression representing an entity or a collection of entities mapped to a JSON column and the path to access it.
/// </para>
/// <para>
/// This type is typically used by database providers (and other extensions). It is generally
/// not used in application code.
/// </para>
/// </summary>
public class JsonQueryExpression : Expression, IPrintableExpression
{
private readonly IReadOnlyDictionary<IProperty, ColumnExpression> _keyPropertyMap;
private readonly bool _nullable;

/// <summary>
/// Creates a new instance of the <see cref="JsonQueryExpression" /> class.
/// </summary>
/// <param name="entityType">An entity type being represented by this expression.</param>
/// <param name="jsonColumn">A column containing JSON.</param>
/// <param name="collection">A value indicating whether this expression represents a collection.</param>
/// <param name="jsonColumn">A column containing JSON value.</param>
/// <param name="keyPropertyMap">A map of key properties and columns they map to in the database.</param>
/// <param name="type">A type of the element represented by this expression.</param>
/// <param name="collection">A value indicating whether this expression represents a collection or not.</param>
public JsonQueryExpression(
IEntityType entityType,
ColumnExpression jsonColumn,
bool collection,
IReadOnlyDictionary<IProperty, ColumnExpression> keyPropertyMap,
Type type)
Type type,
bool collection)
: this(
entityType,
jsonColumn,
collection,
keyPropertyMap,
path: new List<PathSegment> { new("$") },
type,
path: new SqlConstantExpression(Constant("$"), typeMapping: null),
collection,
jsonColumn.IsNullable)
{
}

private JsonQueryExpression(
IEntityType entityType,
ColumnExpression jsonColumn,
bool collection,
IReadOnlyDictionary<IProperty, ColumnExpression> keyPropertyMap,
IReadOnlyList<PathSegment> path,
Type type,
SqlExpression path,
bool collection,
bool nullable)
{
Check.DebugAssert(entityType.FindPrimaryKey() != null, "primary key is null.");
Expand All @@ -55,16 +60,16 @@ private JsonQueryExpression(
_keyPropertyMap = keyPropertyMap;
Type = type;
Path = path;
_nullable = nullable;
IsNullable = nullable;
}

/// <summary>
/// The entity type being projected out.
/// The entity type being represented by this expression.
/// </summary>
public virtual IEntityType EntityType { get; }

/// <summary>
/// The column containg JSON value on which the path is applied.
/// The column containg JSON value.
/// </summary>
public virtual ColumnExpression JsonColumn { get; }

Expand All @@ -74,14 +79,14 @@ private JsonQueryExpression(
public virtual bool IsCollection { get; }

/// <summary>
/// The JSON path leading to the entity from the root of the JSON stored in the column.
/// The list of path segments leading to the entity from the root of the JSON stored in the column.
/// </summary>
public virtual SqlExpression Path { get; }
public virtual IReadOnlyList<PathSegment> Path { get; }

/// <summary>
/// The value indicating whether this expression is nullable.
/// </summary>
public virtual bool IsNullable => _nullable;
public virtual bool IsNullable { get; }

/// <inheritdoc />
public override ExpressionType NodeType => ExpressionType.Extension;
Expand All @@ -106,22 +111,14 @@ public virtual SqlExpression BindProperty(IProperty property)
return match;
}

var pathSegment = new SqlConstantExpression(
Constant(property.GetJsonPropertyName()),
typeMapping: null);

var newPath = new SqlBinaryExpression(
ExpressionType.Add,
Path,
pathSegment,
typeof(string),
typeMapping: null);
var newPath = Path.ToList();
newPath.Add(new PathSegment(property.GetJsonPropertyName()!));

return new JsonScalarExpression(
JsonColumn,
property,
newPath,
_nullable || property.IsNullable);
IsNullable || property.IsNullable);
}

/// <summary>
Expand All @@ -142,16 +139,8 @@ public virtual JsonQueryExpression BindNavigation(INavigation navigation)
}

var targetEntityType = navigation.TargetEntityType;
var pathSegment = new SqlConstantExpression(
Constant(navigation.TargetEntityType.GetJsonPropertyName()),
typeMapping: null);

var newJsonPath = new SqlBinaryExpression(
ExpressionType.Add,
Path,
pathSegment,
typeof(string),
typeMapping: null);
var newPath = Path.ToList();
newPath.Add(new PathSegment(targetEntityType.GetJsonPropertyName()!));

var newKeyPropertyMap = new Dictionary<IProperty, ColumnExpression>();
var targetPrimaryKeyProperties = targetEntityType.FindPrimaryKey()!.Properties.Take(_keyPropertyMap.Count);
Expand All @@ -164,11 +153,11 @@ public virtual JsonQueryExpression BindNavigation(INavigation navigation)
return new JsonQueryExpression(
targetEntityType,
JsonColumn,
navigation.IsCollection,
newKeyPropertyMap,
newPath,
navigation.ClrType,
newJsonPath,
_nullable || !navigation.ForeignKey.IsRequiredDependent);
navigation.IsCollection,
IsNullable || !navigation.ForeignKey.IsRequiredDependent);
}

/// <summary>
Expand All @@ -183,36 +172,31 @@ public virtual JsonQueryExpression MakeNullable()
keyPropertyMap[property] = columnExpression.MakeNullable();
}

return MakeNullable(keyPropertyMap);
}

/// <summary>
/// Makes this JSON query expression nullable re-using existing nullable key properties
/// </summary>
/// <returns>A new expression which has <see cref="IsNullable" /> property set to true.</returns>
internal virtual JsonQueryExpression MakeNullable(IReadOnlyDictionary<IProperty, ColumnExpression> nullableKeyPropertyMap)
=> Update(
return new JsonQueryExpression(
EntityType,
JsonColumn.MakeNullable(),
nullableKeyPropertyMap,
keyPropertyMap,
Path,
Type,
IsCollection,
nullable: true);
}

/// <inheritdoc />
public virtual void Print(ExpressionPrinter expressionPrinter)
{
expressionPrinter.Append("JsonQueryExpression(");
expressionPrinter.Visit(JsonColumn);
expressionPrinter.Append($", \"{string.Join(".", Path)}\")");
expressionPrinter.Append($", {string.Join("", Path.Select(e => e.ToString()))})");
}

/// <inheritdoc />
protected override Expression VisitChildren(ExpressionVisitor visitor)
{
var jsonColumn = (ColumnExpression)visitor.Visit(JsonColumn);
var jsonPath = (SqlExpression)visitor.Visit(Path);

// TODO: also visit columns in the _keyPropertyMap?
return Update(jsonColumn, _keyPropertyMap, jsonPath, IsNullable);
return Update(jsonColumn, _keyPropertyMap);
}

/// <summary>
Expand All @@ -221,19 +205,14 @@ protected override Expression VisitChildren(ExpressionVisitor visitor)
/// </summary>
/// <param name="jsonColumn">The <see cref="JsonColumn" /> property of the result.</param>
/// <param name="keyPropertyMap">The map of key properties and columns they map to.</param>
/// <param name="path">The <see cref="Path" /> property of the result.</param>
/// <param name="nullable">The <see cref="IsNullable" /> property of the result.</param>
/// <returns>This expression if no children changed, or an expression with the updated children.</returns>
public virtual JsonQueryExpression Update(
ColumnExpression jsonColumn,
IReadOnlyDictionary<IProperty, ColumnExpression> keyPropertyMap,
SqlExpression path,
bool nullable)
IReadOnlyDictionary<IProperty, ColumnExpression> keyPropertyMap)
=> jsonColumn != JsonColumn
|| keyPropertyMap.Count != _keyPropertyMap.Count
|| keyPropertyMap.Zip(_keyPropertyMap, (n, o) => n.Value != o.Value).Any(x => x)
|| path != Path
? new JsonQueryExpression(EntityType, jsonColumn, IsCollection, keyPropertyMap, Type, path, nullable)
? new JsonQueryExpression(EntityType, jsonColumn, keyPropertyMap, Path, Type, IsCollection, IsNullable)
: this;

/// <inheritdoc />
Expand All @@ -247,8 +226,8 @@ private bool Equals(JsonQueryExpression jsonQueryExpression)
=> EntityType.Equals(jsonQueryExpression.EntityType)
&& JsonColumn.Equals(jsonQueryExpression.JsonColumn)
&& IsCollection.Equals(jsonQueryExpression.IsCollection)
&& Path.Equals(jsonQueryExpression.Path)
&& IsNullable == jsonQueryExpression.IsNullable
&& Path.SequenceEqual(jsonQueryExpression.Path)
&& KeyPropertyMapEquals(jsonQueryExpression._keyPropertyMap);

private bool KeyPropertyMapEquals(IReadOnlyDictionary<IProperty, ColumnExpression> other)
Expand All @@ -274,4 +253,3 @@ public override int GetHashCode()
// not incorporating _keyPropertyMap into the hash, too much work
=> HashCode.Combine(EntityType, JsonColumn, IsCollection, Path, IsNullable);
}
}
49 changes: 49 additions & 0 deletions src/EFCore.Relational/Query/PathSegment.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using Microsoft.EntityFrameworkCore.Query.SqlExpressions;

namespace Microsoft.EntityFrameworkCore.Query;

/// <summary>
/// <para>
/// A class representing a component of JSON path used in <see cref="JsonQueryExpression"/> or <see cref="JsonScalarExpression"/>.
/// </para>
/// <para>
/// This type is typically used by database providers (and other extensions). It is generally
/// not used in application code.
/// </para>
/// </summary>
public class PathSegment
{
/// <summary>
/// Creates a new instance of the <see cref="PathSegment" /> class.
/// </summary>
/// <param name="key">A key which is being accessed in the JSON.</param>
public PathSegment(string key)
{
Key = key;
}

/// <summary>
/// The key which is being accessed in the JSON.
/// </summary>
public virtual string Key { get; }

/// <inheritdoc />
public override string ToString() => (Key == "$" ? "" : ".") + Key;

/// <inheritdoc />
public override bool Equals(object? obj)
=> obj != null
&& (ReferenceEquals(this, obj)
|| obj is PathSegment pathSegment
&& Equals(pathSegment));

private bool Equals(PathSegment pathSegment)
=> Key == pathSegment.Key;

/// <inheritdoc />
public override int GetHashCode()
=> HashCode.Combine(Key);
}
Loading