Skip to content

Refactor SqlTranslatingExpressionVisitor - #7663

Closed
tuespetre wants to merge 1 commit into
dotnet:devfrom
tuespetre:sql-translating-visitor
Closed

tuespetre wants to merge 1 commit into
dotnet:devfrom
tuespetre:sql-translating-visitor

Conversation

@tuespetre

@tuespetre tuespetre commented Feb 21, 2017 •

Copy link
Copy Markdown
Contributor

This commit adds the OuterPropertyExpression, which is a dedicated expression to represent expressions bound to parent query models. This expression allows us to defer the decision of whether to bind directly to the parent query (i.e. an AliasExpression) or to bind via an outer parameter. There are several improved generated SQL queries in this PR as a result.

To facilitate this change, other changes take place:

  • Subquery models are now visited only once, meaning no more unnecessary uniquification (things like FROM Orders AS o4 instead of FROM Orders AS o)
  • The _bindParentQueries field/parameter to RelationalQueryModelVisitor and SqlTranslatingExpressionVisitor is now gone, instead being driven by the context of the query model visitor and its ancestors via CanBindOuterProperties, CanBindOuterParameters, and RequiresOuterParameterInjection
  • The _targetSelectExpression field/parameter to SqlTranslatingExpressionVisitor is now gone, being replaced by a _mutateProjections field/parameter. This helps to make it clearer what is being done every time and place the visitor is used (also, there were cases where the _targetSelectExpression comparison bit would hinder things from binding correctly.)

This PR is split from (and integral to) #7650 and #7543, and this PR includes/depends on the changes that make up #7619.

@dnfclas

dnfclas commented Feb 21, 2017

Copy link
Copy Markdown

Hi @tuespetre, I'm your friendly neighborhood .NET Foundation Pull Request Bot (You can call me DNFBOT). Thanks for your contribution!
You've already signed the contribution license agreement. Thanks!

The agreement was validated by .NET Foundation and real humans are currently evaluating your PR.

TTYL, DNFBOT;

@tuespetre

Copy link
Copy Markdown
Contributor Author

List of queries with improved generated SQL (ignoring those that just changed in alias names due to the uniquification):

join l2_inner in context.LevelTwo.ToList() on l1_inner.Id equals l2_inner.Level1_Optional_Id into grouping
from l2_inner in grouping.DefaultIfEmpty()
select l1_inner).Distinct().Count() > 7
select ClientStringMethod(l1_inner.Name)).Count() > 7

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

whoops :)

}

do
{

@maumar maumar Feb 21, 2017 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

possible NRE

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks, will change it from do...while to while

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

actually changed the preceding condition to return early if the ancestor is null instead

|| unwrappedExpression.IsAliasWithColumnExpression();
}

public static Expression MaybeAnonymousSubquery([CanBeNull] this Expression expression)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you elaborate what this would generate and why it is needed?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SqlTranslatingExpressionVisitor.VisitSubQuery could return a SelectExpression, but it was always setting the Alias to string.Empty, which can cause invalid SQL in some cases now that more queries can be inlined. The solution was to only make the resulting SelectExpression into an anonymous subquery when appropriate.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, I see. We need to investigate why it is needed. Ideally, we start with top level select expression without setting any alias. We need alias only when we add it as subquery in another select expression. While flattening can cause one of more select expression to be joined, there is no code path which would cause select expression to split, hence we should not have to set the alias to string.Empty ever. If we are doing so then we are assigning alias incorrectly in first place which should be fixed.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well the string.Empty makes it a parenthesized, anonymous subquery. It's just that with new optimizations, it should only be applied on the right occasion instead of unconditionally like it was before.

where (select count(*) from ....) > 7

and so forth. Sorry for the formatting, on a phone right now

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point. Are all such calls go through single path where we can put it instead of having a function to do it?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

They did go through a single path but now not everything coming out of that single path should have it applied

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I looked into usages of this function. They are being used at various expressions without any corresponding logic around it. We shouldn't have it this way.
Encapsulate this code into the particular code path with condition where this is required. Subquery with empty string as alias is pitfall for many invalid SQL. We should identify the pattern where this is required and apply for those cases only. Ideally this function should be removed.

bool bindParentQueries = false,
bool inProjection = false);
bool inProjection = false,
bool mutateProjections = true);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Purpose of mutateProjections?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There are places where the visitor should not be adding to the projections, like in the projection visitor, some result operator handlers... this prevents every place from having to use a 'projection count map' or whatever

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we name it something different? We are trying to make SelectExpression as less Mutable as possible. 😄

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure!

LEFT JOIN [Level2] AS [l1.OneToOne_Required_FK] ON [l10].[Id] = [l1.OneToOne_Required_FK].[Level1_Required_Id]
WHERE ([l10].[Name] <> N'L1 01') OR [l10].[Name] IS NULL
) AS [t]",
@"SELECT [l10].[Id], [l10].[Date], [l10].[Name], [l10].[OneToMany_Optional_Self_InverseId], [l10].[OneToMany_Required_Self_InverseId], [l10].[OneToOne_Optional_SelfId], [l1.OneToOne_Required_FK].[Id], [l1.OneToOne_Required_FK].[Date], [l1.OneToOne_Required_FK].[Level1_Optional_Id], [l1.OneToOne_Required_FK].[Level1_Required_Id], [l1.OneToOne_Required_FK].[Name], [l1.OneToOne_Required_FK].[OneToMany_Optional_InverseId], [l1.OneToOne_Required_FK].[OneToMany_Optional_Self_InverseId], [l1.OneToOne_Required_FK].[OneToMany_Required_InverseId], [l1.OneToOne_Required_FK].[OneToMany_Required_Self_InverseId], [l1.OneToOne_Required_FK].[OneToOne_Optional_PK_InverseId], [l1.OneToOne_Required_FK].[OneToOne_Optional_SelfId]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think I have a relatively simple fix in progress that makes this better, so that we don't regress here

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this a regression though? The resulting SQL is smaller

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@maumar - Subquery is getting lifted. Better SQL.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh it looks like the selected columns are different. (More being selected.)

@tuespetre
tuespetre force-pushed the sql-translating-visitor branch from 29c71b0 to 1876724 Compare February 22, 2017 04:09
@tuespetre

tuespetre commented Feb 22, 2017 •

Copy link
Copy Markdown
Contributor Author

🆙📅

Inventory of regressed tests (all from ComplexNavigationsQuerySqlServerTest):

On these, the subquery is lifted, more columns selected than before -- not sure why, but the main from clauses do show up as 'requires materialization' so I'm sure that has something to do with it:

  • GroupJoin_on_complex_subquery_and_set_operation_on_grouping_but_nothing_from_grouping_is_projected
  • Null_protection_logic_work_for_inner_key_access_of_manually_created_GroupJoin1
  • Null_protection_logic_work_for_inner_key_access_of_manually_created_GroupJoin2

On this one, this is related to a workaround for group join query sources being forced to materialize, which I had to implement to get a number of other tests passing:

  • GroupJoin_in_subquery_with_client_projection_nested2

return handledPropertyExpression;
}

var handledMemberExpression

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use null propagation.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✔️

var handledPropertyExpression
= TryHandlePropertyExpression(
node,
node.Arguments.FirstOrDefault().RemoveConvert(),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Possible NRE.
Also why we need to use FirstOrDefault instead of direct indexes? Property method always have 2 args.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't need to, that should be an indexer ✔️

{
private readonly IRequiresMaterializationExpressionVisitorFactory _requiresMaterializationExpressionVisitorFactory;
private readonly IEntityQueryModelVisitorFactory _entityQueryModelVisitorFactory;
private readonly IDictionary<QueryModel, EntityQueryModelVisitor> _entityQueryModelVisitors

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This change is good in a way that we have reference to QMV which visited this QM already. Hence avoiding revising same QM again. @anpete - Any side effects of this? (like visiting a QM adding something to SelectExpression of some other QM)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@tuespetre - This change would improve perf for query compiler though there is a slight chance of side-effects of caching querymodelvisitors if there are any changed flags in parent qmv in between multiple visits of same QM. The only way to verify is to just make caching changes and see if no tests change. Can you submit a separate PR for that?

@tuespetre tuespetre Feb 22, 2017 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have approached it that way before (it was one of the first split-out PRs I tried to do) but it does not work (a lot of stuff breaks without other changes made in this PR). 🐔 ➕ 🥚; also with these changes there is no multiple visiting of the same query model.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If caching QMVs is breaking tests that means it has unintentional side-effects and we cannot cache it. While binding/lifting, QMV peeks into parent QMV and even though same query model is being visited it can produce different results. Mostly, caching is not usable here.

@tuespetre tuespetre Feb 22, 2017 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

even though same query model is being visited it can produce different results

That's my point, the same query model will not be visited more than once

@tuespetre tuespetre Feb 22, 2017 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If caching QMVs is breaking tests that means it has unintentional side-effects

The problem I found was not with the caching itself, but that introducing caching actually prevents the query models from being visited more than once, and once you do that, you have to use/account for new and different flags on the parent QMV, such as CanBindOuterProperties, RequiresOuterParameterBinding, etc. in order for that one-and-only visit of the query model to produce the desired result

@tuespetre tuespetre Feb 22, 2017 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I will try removing the caching from this PR and see if it breaks anything. If it doesn't break, I will push up a commit that doesn't have the caching. Does that sound good to you

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I tested out caching part and it breaks many tests. In current pipeline, visiting a QM not only dependent on outer qmv flags but also mutates the QM itself. When we fail to translate the QM, we have to revert the QM. We have methods like PopulateQueryModelMapping & RecreateQueryModelFromMapping for that. That is enough evidence to say that current pipeline generate different results while visiting same query model again.

Before we introduce caching on QMVs, we need to make sure that pipeline can generate the required translation of QM which can be used under any circumstances later.

Remove the caching part from this PR. We can add it when we reach above stage.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ohhh you gave me an idea for how to deal with all the unnecessary uniquification without the caching bits (for another PR, another time) and also I think I know how to get around the removal of the caching for this PR.


var newNewExpression = base.VisitNew(expression);
if (QueryModelVisitor.QueryCompilationContext.QuerySourceRequiresMaterialization(_querySource))
{

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@smitpatel, regarding MaybeAnonymousSubquery():

I added this condition as a workaround for not being able to always inline a subquery into a projection (due to an EntityShaper being present, or otherwise.) It looks like maybe this takes care of the reason I had put in MaybeAnonymousSubquery so I can remove it after all. 🎉

@tuespetre
tuespetre force-pushed the sql-translating-visitor branch from 1876724 to 70c70b9 Compare February 22, 2017 14:14
@tuespetre

Copy link
Copy Markdown
Contributor Author

🆙📅

Was able to remove MaybeAnonymousSubquery()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants