Skip to content

Query: Relational: only push down subqueries when needed. - #7771

Closed
tuespetre wants to merge 1 commit into
dotnet:devfrom
tuespetre:pushdown-subqueries-when-needed
Closed

tuespetre wants to merge 1 commit into
dotnet:devfrom
tuespetre:pushdown-subqueries-when-needed

Conversation

@tuespetre

Copy link
Copy Markdown
Contributor

Fixes #7766

@dnfclas

dnfclas commented Mar 3, 2017

Copy link
Copy Markdown

@tuespetre,
Thanks for having already signed the Contribution License Agreement. Your agreement was validated by .NET Foundation. We will now review your pull request.
Thanks,
.NET Foundation Pull Request Bot

{
Check.NotNull(predicate, nameof(predicate));

if (_limit != null || _offset != null)

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.

AddToPredicate is supposed to be a simple function. This logic should not be here at all.

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 placed this logic here to be consistent with the several other 'simple' methods (and even setters) that use similar logic to ensure that a SelectExpression is pushed down into a subquery when appropriate: set_Limit, set_Offset, SetProjectionExpression, etc., but also because it is applicable in several places.

SELECT CASE
WHEN NOT EXISTS (
SELECT [t].[c0]
SELECT 1

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 avoid this here? (previous query was better)

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.

@maumar, the previous query generated for this test was incorrect but the test was not producing the proper conditions to show how it was incorrect.

After changing the test from cs.OrderBy(c => c.ContactName).Skip(5).Take(10).All(p => p.CustomerID.Length == 5) to cs.OrderBy(c => c.ContactName).Skip(5).Take(10).All(p => !p.CustomerID.StartsWith("A"))

Old query, returns 1:

SELECT CASE
    WHEN NOT EXISTS (
        SELECT [t].[c0]
        FROM (
            SELECT 1 AS [c0], ROW_NUMBER() OVER(ORDER BY [c].[ContactName]) AS [__RowNumber__]
            FROM [Customers] AS [c]
            WHERE [c].[CustomerID] LIKE N'A' + N'%' AND (CHARINDEX(N'A', [c].[CustomerID]) = 1)
        ) AS [t]
        WHERE ([t].[__RowNumber__] > 5) AND ([t].[__RowNumber__] <= (15)))
    THEN CAST(1 AS BIT) ELSE CAST(0 AS BIT)
END

New query, returns 0:

SELECT CASE
    WHEN NOT EXISTS (
        SELECT 1
        FROM (
            SELECT [t0].*
            FROM (
                SELECT [c].*, ROW_NUMBER() OVER(ORDER BY [c].[ContactName]) AS [__RowNumber__]
                FROM [Customers] AS [c]
            ) AS [t0]
            WHERE ([t0].[__RowNumber__] > 5) AND ([t0].[__RowNumber__] <= (15))
        ) AS [t]        
        WHERE [t].[CustomerID] LIKE N'A' + N'%' AND (CHARINDEX(N'A', [t].[CustomerID]) = 1))
    THEN CAST(1 AS BIT) ELSE CAST(0 AS BIT)
END

@tuespetre
tuespetre force-pushed the pushdown-subqueries-when-needed branch 2 times, most recently from 2253b57 to bb73b98 Compare March 3, 2017 22:26
@tuespetre tuespetre mentioned this pull request Mar 7, 2017
@tuespetre
tuespetre force-pushed the pushdown-subqueries-when-needed branch from bb73b98 to d7f5c64 Compare March 8, 2017 04:13
@tuespetre

Copy link
Copy Markdown
Contributor Author

🆙📅, rebased onto latest

@tuespetre
tuespetre force-pushed the pushdown-subqueries-when-needed branch from d7f5c64 to d5174d4 Compare March 8, 2017 04:41
@smitpatel

Copy link
Copy Markdown
Contributor

@tuespetre
Previously we lifted subqueries only if a certain set of conditions were met (mainly depicted by IsIdentityQuery). While those conditions were much more restrictive in nature, this approach handles with problem from other direction i.e. lift select expression always and push down when needed. That brings in extra checks in AddToOrderBy & AddToPredicate, ideally which would have simple methods because Limit/Offset are result operators and applied after orderby/where translation. Though since this change lift select expression much freely, we need those checks which were already a subquery in query model.

I understand the original thing was not perfect and much more restrictive but is this approach better than that in some way? Can we improve lifting scenarios by applying appropriate conditions in LiftSubquery and avoid lifting rather than pushing down later?
The reason I ask this is because, when you do pushdown while adding orderby/where, you need to update the sql translation (LiftPredicate visitor) because when you were translating the expression you used incorrect SelectExpression (the one before push down). If we push down before actually running sqltranslatingexpressionvisitor then we don't need to deal with this overhead.

Further I am working refactoring SelectExpression to make it more consistent and referentially integral, which also removes UpdateColumnExpression and bunch of other methods. After my changes, the best way to bind a column with SelectExpression would become through member binder which is part of SqlTranslatingExpressionVisitor. And ad-hoc creation of ColumnExpression/AliasExpression are stopped which would introduce complexity in updating already translated SqlExpressions.

@tuespetre

tuespetre commented Mar 8, 2017 •

Copy link
Copy Markdown
Contributor Author

Previously we lifted subqueries only if a certain set of conditions were met (mainly depicted by IsIdentityQuery). ... Though since this change lift select expression much freely, we need those checks which were already a subquery in query model.

To be clear, this PR doesn't change which subqueries are lifted, just which SelectExpressions get pushed down into subqueries during lifting.

I understand the original thing was not perfect and much more restrictive but is this approach better than that in some way?

Tighter SQL statements, especially when GROUP BY is thrown into the mix. This is not only for aesthetics but for performance -- much less bytes over the wire as can be seen from a number of the changed test results.

Further I am working refactoring SelectExpression to make it more consistent and referentially integral, which also removes UpdateColumnExpression and bunch of other methods. After my changes, the best way to bind a column with SelectExpression would become through member binder which is part of SqlTranslatingExpressionVisitor. And ad-hoc creation of ColumnExpression/AliasExpression are stopped which would introduce complexity in updating already translated SqlExpressions.

I am really interested to see what you are doing with that, especially in relation to GROUP BY, because many of those cases turn out to be very complex. Example:

from c in context.Customers
join og in (from o in context.Orders group o by o.CustomerID)
    on c.CustomerID equals og.Key
select new { c.ContactName, og.Max(o => o.Total) }

By the time you get to translate the Max part of the projection to SQL, the GROUP BY query is pushed down and you have this:

SELECT [c].[ContactName]
FROM [Customers] AS [c]
JOIN (
    SELECT [o].[CustomerID]
    FROM [Orders] AS [o]
    GROUP BY [o].[CustomerID]
) AS [og]

...and you have to both successfully translate MAX([o].[Total]) AS [o.Total.Max] and [og].[o.Total.Max] out of that.

That's not necessarily this PR's problem, but something to consider alongside the work you are doing

@smitpatel

Copy link
Copy Markdown
Contributor

To be clear, this PR doesn't change which subqueries are lifted, just which SelectExpressions get pushed down into subqueries during lifting.

Tighter SQL statements, especially when GROUP BY is thrown into the mix. This is not only for aesthetics but for performance -- much less bytes over the wire as can be seen from a number of the changed test results.

The pushdowns which were happening during LiftSubquery are happening at later stage now. If you don't pushdown a subquery then you are basically lifting it up. This is certainly improvement over generated SQL. My point is can we include some logic inside LiftSubQuery to do pushdown at appropriate places so that we don't have to pushdown later.

Taking simple example from tests added:

AssertQuery<OrderDetail>(ods => 
                ods.OrderBy(d => d.Quantity).ThenBy(d => d.OrderID).Take(2).OrderBy(d => d.ProductID).ThenBy(d => d.Quantity), 
                entryCount: 2); 

The generated query model is as follows:

  Optimized query model: 
  'from OrderDetail d in 
      (from OrderDetail d in DbSet<OrderDetail>
      order by d.Quantity asc, d.OrderID asc
      select d)
      .Take(__p_0)
  order by d.ProductID asc, d.Quantity asc
  select d'

Now in this case if we don't lift the subquery and have the SelectExpression inside it appear in a subquery select then while adding outer order by we don't need to do push down. (btw above query works correctly in current dev)

Having pushdown inside orderby/where means that we made a flat select expression for a subquery model instead of making a subquery select expression as it was required.
So there becomes 2 approaches to reach above improvement,

  1. Either we don't pushdown till we need like in this PR.
  2. We identify cases where we need to pushdown eagerly and of course much accurately. (this is the logic which is inaccurate atm).

So which approach would be better for us? After changes to SelectExpression 1 may be more complex than 2. But if 2 cannot solve everything for us then 1 is also fine.

While discussing in team, based on the Sql which are improving, there is another way to do this in QueryOptimizer.
Following is the query model for one such improved query

  'from Level2 l2 in 
      (from Level2 l2 in DbSet<Level2>
      where l2.OneToOne_Required_FK_Inverse.Name == "L1 03"
      select l2)
      .Take(__p_0)
  select l2.Name'

In this case since we have only select in outer query model, we can combine it with subquery and flatten the query. Optimizing at query model level makes things much easier while translating. Would you like to tackle this issue in query optimizer?

As for group by query you posted, lets discuss on group by PR.

@tuespetre

Copy link
Copy Markdown
Contributor Author

@smitpatel good call on the pattern of the improved queries. I may not tackle this in the optimizer right now but since you have pointed that out I would say I am okay with backing off from this. If it's agreeable to you I will amend the commit to include the new test cases as well as the fix to the incorrect query that I discovered.

@smitpatel

Copy link
Copy Markdown
Contributor

fix to the incorrect query that I discovered.
Which incorrect queries?

SELECT CASE
WHEN NOT EXISTS (
SELECT [t].[c0]
SELECT 1

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 this one that @maumar commented on previously

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.

Test changed. Original SQL looks fine.

Sql);
}

public override void Skip_Skip_Take()

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 IIRC this test would also fail without a fix

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 could potentially fail. Though looking at generated SQL. It doesn't look very good given it has * at top level select. We should have proper column projected out. The reason we never generate SelectExpression with * at top level is you cannot accurately bind the valuebuffer to properties with star projection.

WHERE LEN([c].[CustomerID]) <> 5
ORDER BY [c].[ContactName]
OFFSET @__p_0 ROWS FETCH NEXT @__p_1 ROWS ONLY)
FROM (

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 this one

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.

What is wrong with the original query here? The test itself was changed causing different SQL.

@tuespetre tuespetre Mar 9, 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 changed the All predicate within the test to demonstrate the issue. The predicate that was used before was hiding the issue. A subquery with Limit/Offset has to be pushed down before adding another predicate.

EDIT: In other words, if you changed the data in the database so that there actually were some customers with a customer ID that was not 5 characters long, the original query would have produced incorrect results

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 catch. It indeed is incorrect query. The modifying AddToPredicate does not seem to be right way to fix it.
This situation arises because of multiple result operators. And it should be fixed in same manner as done in #7578 . i.e. Result operators should be taking care of other result operators which may come before. Do you want to submit a fix for it in HandleAll?

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.

Yes, do you have any objections to also fixing the .Skip().Skip() issue and including the new test cases in the same PR?

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.

No objection as long as they are localized in handling result operators.

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.

OK, great. Thanks!

@smitpatel

Copy link
Copy Markdown
Contributor

We can certainly use the tests here. Also the improvement around LiftSubquery function is decent. Lets take this in once changes to Select Expression are merged in.

@tuespetre

Copy link
Copy Markdown
Contributor Author

@smitpatel we'll see how the other PRs go; besides those, what would be left in this PR is not really substantial so I am going to close it.

Thanks! 🐢

@tuespetre tuespetre closed this Mar 9, 2017
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