Skip to content

Add more left join support #2737

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

Merged
merged 7 commits into from
Apr 28, 2022
Merged
Show file tree
Hide file tree
Changes from 4 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
97 changes: 93 additions & 4 deletions src/NHibernate.Test/Async/Linq/ByMethod/JoinTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,7 @@
//------------------------------------------------------------------------------


using System;
using System.Linq;
using System.Reflection;
using NHibernate.Cfg;
using NHibernate.Engine.Query;
using NHibernate.Linq;
using NHibernate.Util;
using NSubstitute;
Expand All @@ -21,6 +17,7 @@
namespace NHibernate.Test.Linq.ByMethod
{
using System.Threading.Tasks;
using System.Threading;
[TestFixture]
public class JoinTestsAsync : LinqTestCase
{
Expand Down Expand Up @@ -114,6 +111,98 @@ public async Task LeftJoinExtensionMethodWithMultipleKeyPropertiesAsync()
}
}

[Test]
public async Task LeftJoinExtensionMethodWithOuterReferenceInWhereClauseOnlyAsync()
{
using (var sqlSpy = new SqlLogSpy())
{
var animals = await (db.Animals
.LeftJoin(
db.Mammals,
x => x.Id,
x => x.Id,
(animal, mammal) => new { animal, mammal })
.Where(x => x.mammal.SerialNumber.StartsWith("9"))
.Select(x => new { SerialNumber = x.animal.SerialNumber })
.ToListAsync());

var sql = sqlSpy.GetWholeLog();
Assert.That(animals.Count, Is.EqualTo(1));
Assert.That(GetTotalOccurrences(sql, "left outer join"), Is.EqualTo(1));
}
}

[KnownBug("GH-2379")]
public async Task NestedLeftJoinExtensionMethodWithOuterReferenceInWhereClauseOnlyAsync(CancellationToken cancellationToken = default(CancellationToken))
{
using (var sqlSpy = new SqlLogSpy())
{
var innerAnimals = db.Animals
.LeftJoin(
db.Mammals,
x => x.Id,
x => x.Id,
(animal, mammal) => new { animal, mammal })
.Where(x => x.mammal.SerialNumber.StartsWith("9"))
.Select(x=>x.animal);

var animals = await (db.Animals
.LeftJoin(
innerAnimals,
x => x.Id,
x => x.Id,
(animal, animal2) => new { animal, animal2 })
.Select(x => new { SerialNumber = x.animal2.SerialNumber })
.ToListAsync(cancellationToken));

var sql = sqlSpy.GetWholeLog();
Assert.That(animals.Count, Is.EqualTo(1));
Assert.That(GetTotalOccurrences(sql, "left outer join"), Is.EqualTo(1));
}
}

[Test]
public async Task LeftJoinExtensionMethodWithNoUseOfOuterReferenceAsync()
{
using (var sqlSpy = new SqlLogSpy())
{
var animals = await (db.Animals
.LeftJoin(
db.Mammals,
x => x.Id,
x => x.Id,
(animal, mammal) => new { animal, mammal })
.Select(x => x.animal)
.ToListAsync());

var sql = sqlSpy.GetWholeLog();
Assert.That(animals.Count, Is.EqualTo(6));
Assert.That(GetTotalOccurrences(sql, "left outer join"), Is.EqualTo(5));
}
}

[Test]
public async Task LeftJoinExtensionMethodWithOuterReferenceInOrderByClauseOnlyAsync()
{
using (var sqlSpy = new SqlLogSpy())
{
var animals = await (db.Animals
.LeftJoin(
db.Mammals,
x => x.Id,
x => x.Id,
(animal, mammal) => new { animal, mammal })
.OrderBy(x => x.mammal.SerialNumber ?? "z")
.Select(x => new { SerialNumber = x.animal.SerialNumber })
.ToListAsync());

var sql = sqlSpy.GetWholeLog();
Assert.That(animals.Count, Is.EqualTo(6));
Assert.That(animals[0].SerialNumber, Is.EqualTo("1121"));
Assert.That(GetTotalOccurrences(sql, "left outer join"), Is.EqualTo(1));
}
}

[TestCase(false)]
[TestCase(true)]
public async Task CrossJoinWithPredicateInWhereStatementAsync(bool useCrossJoin)
Expand Down
98 changes: 93 additions & 5 deletions src/NHibernate.Test/Linq/ByMethod/JoinTests.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
using System;
using System.Linq;
using System.Reflection;
using NHibernate.Cfg;
using NHibernate.Engine.Query;
using System.Linq;
using NHibernate.Linq;
using NHibernate.Util;
using NSubstitute;
Expand Down Expand Up @@ -103,6 +99,98 @@ public void LeftJoinExtensionMethodWithMultipleKeyProperties()
}
}

[Test]
public void LeftJoinExtensionMethodWithOuterReferenceInWhereClauseOnly()
{
using (var sqlSpy = new SqlLogSpy())
{
var animals = db.Animals
.LeftJoin(
db.Mammals,
x => x.Id,
x => x.Id,
(animal, mammal) => new { animal, mammal })
.Where(x => x.mammal.SerialNumber.StartsWith("9"))
.Select(x => new { SerialNumber = x.animal.SerialNumber })
.ToList();

var sql = sqlSpy.GetWholeLog();
Assert.That(animals.Count, Is.EqualTo(1));
Assert.That(GetTotalOccurrences(sql, "left outer join"), Is.EqualTo(1));
}
}

[KnownBug("GH-2379")]
public void NestedLeftJoinExtensionMethodWithOuterReferenceInWhereClauseOnly()
{
using (var sqlSpy = new SqlLogSpy())
{
var innerAnimals = db.Animals
.LeftJoin(
db.Mammals,
x => x.Id,
x => x.Id,
(animal, mammal) => new { animal, mammal })
.Where(x => x.mammal.SerialNumber.StartsWith("9"))
.Select(x=>x.animal);

var animals = db.Animals
.LeftJoin(
innerAnimals,
x => x.Id,
x => x.Id,
(animal, animal2) => new { animal, animal2 })
.Select(x => new { SerialNumber = x.animal2.SerialNumber })
.ToList();

var sql = sqlSpy.GetWholeLog();
Assert.That(animals.Count, Is.EqualTo(1));
Assert.That(GetTotalOccurrences(sql, "left outer join"), Is.EqualTo(1));
}
}

[Test]
public void LeftJoinExtensionMethodWithNoUseOfOuterReference()
{
using (var sqlSpy = new SqlLogSpy())
{
var animals = db.Animals
.LeftJoin(
db.Mammals,
x => x.Id,
x => x.Id,
(animal, mammal) => new { animal, mammal })
.Select(x => x.animal)
.ToList();

var sql = sqlSpy.GetWholeLog();
Assert.That(animals.Count, Is.EqualTo(6));
Assert.That(GetTotalOccurrences(sql, "left outer join"), Is.EqualTo(5));
}
}

[Test]
public void LeftJoinExtensionMethodWithOuterReferenceInOrderByClauseOnly()
{
using (var sqlSpy = new SqlLogSpy())
{
var animals = db.Animals
.LeftJoin(
db.Mammals,
x => x.Id,
x => x.Id,
(animal, mammal) => new { animal, mammal })
.OrderBy(x => x.mammal.SerialNumber ?? "z")
.Select(x => new { SerialNumber = x.animal.SerialNumber })
.ToList();

var sql = sqlSpy.GetWholeLog();
Assert.That(animals.Count, Is.EqualTo(6));
Assert.That(animals[0].SerialNumber, Is.EqualTo("1121"));
Assert.That(GetTotalOccurrences(sql, "left outer join"), Is.EqualTo(1));
}
}

[TestCase(false)]
[TestCase(true)]
public void CrossJoinWithPredicateInWhereStatement(bool useCrossJoin)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
using System.Collections.Generic;
using System.Linq.Expressions;
using NHibernate.Linq.Visitors;
using Remotion.Linq;
using Remotion.Linq.Clauses;

namespace NHibernate.Linq.GroupJoin
{
internal class GroupJoinAggregateDetectionQueryModelVisitor : NhQueryModelVisitorBase
{
private readonly GroupJoinAggregateDetectionVisitor _groupJoinAggregateDetectionVisitor;

private GroupJoinAggregateDetectionQueryModelVisitor(IEnumerable<GroupJoinClause> groupJoinClauses)
{
_groupJoinAggregateDetectionVisitor = new GroupJoinAggregateDetectionVisitor(groupJoinClauses);
}

public static IsAggregatingResults Visit(IEnumerable<GroupJoinClause> groupJoinClause, QueryModel queryModel)
{
var visitor = new GroupJoinAggregateDetectionQueryModelVisitor(groupJoinClause);

visitor.VisitQueryModel(queryModel);

return visitor._groupJoinAggregateDetectionVisitor.GetResults();
}

public override void VisitWhereClause(WhereClause whereClause, QueryModel queryModel, int index)
{
_groupJoinAggregateDetectionVisitor.Visit(whereClause.Predicate);
}

public override void VisitSelectClause(SelectClause selectClause, QueryModel queryModel)
{
_groupJoinAggregateDetectionVisitor.Visit(selectClause.Selector);
}

public override void VisitOrdering(Ordering ordering, QueryModel queryModel, OrderByClause orderByClause, int index)
{
_groupJoinAggregateDetectionVisitor.Visit(ordering.Expression);
}
}
}
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq.Expressions;
using NHibernate.Linq.Expressions;
using NHibernate.Linq.Visitors;
using Remotion.Linq;
using Remotion.Linq.Clauses;
using Remotion.Linq.Clauses.Expressions;

Expand All @@ -18,7 +20,7 @@ internal class GroupJoinAggregateDetectionVisitor : NhExpressionVisitor
private readonly List<GroupJoinClause> _nonAggregatingGroupJoins = new List<GroupJoinClause>();
private readonly List<GroupJoinClause> _aggregatingGroupJoins = new List<GroupJoinClause>();

private GroupJoinAggregateDetectionVisitor(IEnumerable<GroupJoinClause> groupJoinClause)
internal GroupJoinAggregateDetectionVisitor(IEnumerable<GroupJoinClause> groupJoinClause)
{
_groupJoinClauses = new HashSet<GroupJoinClause>(groupJoinClause);
}
Expand All @@ -29,11 +31,12 @@ public static IsAggregatingResults Visit(IEnumerable<GroupJoinClause> groupJoinC

visitor.Visit(selectExpression);

return new IsAggregatingResults { NonAggregatingClauses = visitor._nonAggregatingGroupJoins, AggregatingClauses = visitor._aggregatingGroupJoins, NonAggregatingExpressions = visitor._nonAggregatingExpressions };
return GetResults(visitor);
}

protected override Expression VisitSubQuery(SubQueryExpression expression)
{
//Visit the entire query model?
Visit(expression.QueryModel.SelectClause.Selector);
return expression;
}
Expand Down Expand Up @@ -89,6 +92,21 @@ protected override Expression VisitQuerySourceReference(QuerySourceReferenceExpr
return base.VisitQuerySourceReference(expression);
}

internal IsAggregatingResults GetResults()
{
return GetResults(this);
}

private static IsAggregatingResults GetResults(GroupJoinAggregateDetectionVisitor visitor)
{
return new IsAggregatingResults
{
NonAggregatingClauses = visitor._nonAggregatingGroupJoins,
AggregatingClauses = visitor._aggregatingGroupJoins,
NonAggregatingExpressions = visitor._nonAggregatingExpressions
};
}

internal class StackFlag
{
public bool FlagIsTrue { get; private set; }
Expand Down
20 changes: 19 additions & 1 deletion src/NHibernate/Linq/GroupJoin/NonAggregatingGroupJoinRewriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,24 @@ private void ReWrite()
throw new NotSupportedException();
}
}

// Remove not used group joins
foreach (var groupJoinClause in _groupJoinClauses)
{
if (aggregateDetectorResults.NonAggregatingClauses.Contains(groupJoinClause) || aggregateDetectorResults.AggregatingClauses.Contains(groupJoinClause))
{
continue;
}

var locator = new QuerySourceUsageLocator(groupJoinClause);
foreach (var bodyClause in _model.BodyClauses)
{
locator.Search(bodyClause);
}

_model.BodyClauses.Remove((IBodyClause) locator.Usages[0]);
_model.BodyClauses.Remove(groupJoinClause);
}
}

private void ProcessFlattenedJoin(GroupJoinClause nonAggregatingJoin, QuerySourceUsageLocator locator)
Expand Down Expand Up @@ -159,7 +177,7 @@ private bool IsHierarchicalJoin(GroupJoinClause nonAggregatingJoin, QuerySourceU
// TODO - rename this and share with the AggregatingGroupJoinRewriter
private IsAggregatingResults GetGroupJoinInformation(IEnumerable<GroupJoinClause> clause)
{
return GroupJoinAggregateDetectionVisitor.Visit(clause, _model.SelectClause.Selector);
return GroupJoinAggregateDetectionQueryModelVisitor.Visit(clause, _model);
}
}

Expand Down