-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Support conflicting partition key predicates in Cosmos queries #38240
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
Open
lorenacr
wants to merge
7
commits into
dotnet:main
Choose a base branch
from
lorenacr:Issue38238
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+313
−36
Open
Changes from 5 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
ee3c440
Support conflicting partition key predicates in Cosmos queries
lorenacr 5ad8aa4
Enhance partition key conflict validation in Cosmos queries
lorenacr dca176f
Add using directive for internal Cosmos functionality in ReadItemPart…
lorenacr 056d94d
Enhance partition key conflict handling in Cosmos queries
lorenacr 805c185
Refactor ReadItem optimization logic in Cosmos queries
lorenacr 81f8ba6
Refactor handling of conflicting partition key predicates in Cosmos q…
lorenacr f073862
Merge upstream/main into Issue38238
lorenacr File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,7 @@ | ||
| // 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.Cosmos.Internal; | ||
| using Microsoft.EntityFrameworkCore.Cosmos.Metadata.Internal; | ||
|
|
||
| namespace Microsoft.EntityFrameworkCore.Cosmos.Query.Internal; | ||
|
|
@@ -55,6 +56,22 @@ public virtual Expression ExtractPartitionKeysAndId( | |
|
|
||
| _rootAlias = rootSource.Alias; | ||
|
|
||
| Expression UnwrapShaperForReadItem(Expression shaper) | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Any reason for this rename and move of Unwrap()? At least keep it in the same place to reduce the diff? |
||
| { | ||
| if (shaper is UnaryExpression { NodeType: ExpressionType.Convert } convert | ||
| && convert.Type == typeof(object)) | ||
| { | ||
| shaper = convert.Operand; | ||
| } | ||
|
|
||
| while (shaper is IncludeExpression { EntityExpression: var nested }) | ||
| { | ||
| shaper = nested; | ||
| } | ||
|
|
||
| return shaper; | ||
| } | ||
|
|
||
| // We're going to be looking for equality comparisons on the JSON id definition properties and the partition key properties of the | ||
| // entity type; build a dictionary where the properties are the keys, and where the values are expressions that will get populated | ||
| // from the tree (either constants or parameters). | ||
|
|
@@ -88,6 +105,15 @@ public virtual Expression ExtractPartitionKeysAndId( | |
| var allIdPropertiesSpecified = | ||
| _jsonIdPropertyValues.Values.All(p => p is not null) && _jsonIdPropertyValues.Count > 0; | ||
|
|
||
| // WithPartitionKey will clear _partitionKeyPropertyValues during the lift pass below; snapshot predicate partition key | ||
| // comparisons first so we can validate conflicts against WithPartitionKey when using ReadItem (see #38238). | ||
| var hadWithPartitionKey = queryCompilationContext.PartitionKeyPropertyValues.Count > 0; | ||
| Dictionary<IProperty, (Expression? ValueExpression, Expression? OriginalExpression)>? predicatePartitionKeySnapshot = null; | ||
| if (hadWithPartitionKey) | ||
| { | ||
| predicatePartitionKeySnapshot = new Dictionary<IProperty, (Expression?, Expression?)>(_partitionKeyPropertyValues); | ||
| } | ||
|
|
||
| // First, go over the partition key properties and lift them from the predicate to the query compilation context, as possible. | ||
| // We do this only as long as all partition key values are provided; the moment there's a gap we stop (so if PK1 and PK3 are | ||
| // provided but not PK2, only PK1 will be lifted out). | ||
|
|
@@ -111,9 +137,7 @@ public virtual Expression ExtractPartitionKeysAndId( | |
| } | ||
| } | ||
|
|
||
| // Now, attempt to also transform the query to ReadItem form; this is only possible if all JSON ID properties were compared in the | ||
| // predicate, and *all* partition key values are specified(in the predicate or via WithPartitionKey) | ||
| if (_isPredicateCompatibleWithReadItem | ||
| var willUseReadItemOptimization = _isPredicateCompatibleWithReadItem | ||
| && allIdPropertiesSpecified | ||
| && queryCompilationContext.PartitionKeyPropertyValues.Count == partitionKeyProperties.Count | ||
| && select is | ||
|
|
@@ -123,8 +147,20 @@ public virtual Expression ExtractPartitionKeysAndId( | |
| } | ||
| // We only transform to ReadItem if the entire document (i.e. root entity type) is being projected out. | ||
| // Using ReadItem even when a projection is present is tracked by #34163. | ||
| && Unwrap(shapedQuery.ShaperExpression) is StructuralTypeShaperExpression { StructuralType: var projectedStructuralType } | ||
| && projectedStructuralType == _entityType) | ||
| && UnwrapShaperForReadItem(shapedQuery.ShaperExpression) is StructuralTypeShaperExpression { StructuralType: var projectedStructuralType } | ||
| && projectedStructuralType == _entityType; | ||
|
|
||
| if (hadWithPartitionKey && predicatePartitionKeySnapshot is not null && willUseReadItemOptimization) | ||
| { | ||
| ValidateNoWithPartitionKeyConflict( | ||
| queryCompilationContext, | ||
| partitionKeyProperties, | ||
| predicatePartitionKeySnapshot); | ||
| } | ||
|
|
||
| // Now, attempt to also transform the query to ReadItem form; this is only possible if all JSON ID properties were compared in the | ||
| // predicate, and *all* partition key values are specified(in the predicate or via WithPartitionKey) | ||
| if (willUseReadItemOptimization) | ||
| { | ||
| return shapedQuery.UpdateQueryExpression(select.WithReadItemInfo(new ReadItemInfo(_jsonIdPropertyValues!))); | ||
| } | ||
|
|
@@ -152,21 +188,87 @@ public virtual Expression ExtractPartitionKeysAndId( | |
| } | ||
|
|
||
| return shapedQuery; | ||
| } | ||
|
|
||
| Expression Unwrap(Expression shaper) | ||
| private void ValidateNoWithPartitionKeyConflict( | ||
| CosmosQueryCompilationContext queryCompilationContext, | ||
| IReadOnlyList<IProperty> partitionKeyProperties, | ||
| IReadOnlyDictionary<IProperty, (Expression? ValueExpression, Expression? OriginalExpression)> | ||
| predicatePartitionKeyPropertyValues) | ||
| { | ||
| // WithPartitionKey(...) already populated partition key values in the query compilation context. | ||
| // If the predicate also contains partition key comparisons, we must validate that they match; otherwise, a ReadItem | ||
| // optimization would execute with the WithPartitionKey partition key and ignore the conflicting predicate. | ||
| for (var i = 0; i < partitionKeyProperties.Count; i++) | ||
| { | ||
| if (shaper is UnaryExpression { NodeType: ExpressionType.Convert } convert | ||
| && convert.Type == typeof(object)) | ||
| var property = partitionKeyProperties[i]; | ||
| var predicateValueExpression = predicatePartitionKeyPropertyValues[property].ValueExpression; | ||
| if (predicateValueExpression is null) | ||
| { | ||
| shaper = convert.Operand; | ||
| continue; | ||
| } | ||
|
|
||
| while (shaper is IncludeExpression { EntityExpression: var nested }) | ||
| if (queryCompilationContext.PartitionKeyPropertyValues.Count <= i) | ||
| { | ||
| shaper = nested; | ||
| // Shouldn't happen: WithPartitionKey doesn't specify enough PK components; let the existing missing-PK flow handle it. | ||
| break; | ||
| } | ||
|
|
||
| return shaper; | ||
| var withPartitionKeyValueExpression = queryCompilationContext.PartitionKeyPropertyValues[i]; | ||
|
|
||
| if (!PartitionKeySqlValuesMatch( | ||
| predicateValueExpression, | ||
| withPartitionKeyValueExpression, | ||
| property)) | ||
| { | ||
| throw new InvalidOperationException(CosmosStrings.WithPartitionKeyConflictingPartitionKeyPredicate); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private static bool PartitionKeySqlValuesMatch(Expression left, Expression right, IProperty partitionKeyProperty) | ||
| { | ||
| if (ReferenceEquals(left, right)) | ||
| { | ||
| return true; | ||
| } | ||
|
|
||
| left = UnwrapPartitionKeySqlExpression(left); | ||
| right = UnwrapPartitionKeySqlExpression(right); | ||
|
|
||
| if (ReferenceEquals(left, right)) | ||
| { | ||
| return true; | ||
| } | ||
|
|
||
| if (left is SqlExpression sqlLeft && right is SqlExpression sqlRight && sqlLeft.Equals(sqlRight)) | ||
| { | ||
| return true; | ||
| } | ||
|
|
||
| var comparer = partitionKeyProperty.GetValueComparer(); | ||
|
|
||
| switch (left, right) | ||
| { | ||
| case (SqlConstantExpression { Value: var leftValue }, SqlConstantExpression { Value: var rightValue }): | ||
| return comparer.Equals(leftValue, rightValue); | ||
|
|
||
| case (SqlParameterExpression { Name: var leftName }, SqlParameterExpression { Name: var rightName }): | ||
| return leftName == rightName; | ||
|
|
||
| default: | ||
| return false; | ||
| } | ||
|
|
||
| static Expression UnwrapPartitionKeySqlExpression(Expression expression) | ||
| { | ||
| while (expression is SqlUnaryExpression { OperatorType: ExpressionType.Convert or ExpressionType.ConvertChecked } unary | ||
| && unary.Operand is SqlExpression operand) | ||
| { | ||
| expression = operand; | ||
| } | ||
|
|
||
| return expression; | ||
| } | ||
| } | ||
|
|
||
|
|
@@ -320,7 +422,8 @@ void ProcessPropertyComparison(string propertyName, SqlExpression propertyValue, | |
| // call. Note that this is always considered a compatible comparison for ReadItem. | ||
| if (propertyName == property.GetJsonPropertyName() | ||
| && _partitionKeyPropertyValues.TryGetValue(property, out var previousValues) | ||
| && (previousValues.ValueExpression is null || previousValues.Equals(propertyValue))) | ||
| && (previousValues.ValueExpression is null | ||
| || PartitionKeySqlValuesMatch(previousValues.ValueExpression, propertyValue, property))) | ||
| { | ||
| _partitionKeyPropertyValues[property] = (ValueExpression: propertyValue, OriginalExpression: originalExpression); | ||
| return; | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.