Skip to content

Port Hibernate's support subqueries in HQL as CASE statement alternatives #2106

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
Jun 19, 2019
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
70 changes: 70 additions & 0 deletions src/NHibernate.Test/Async/Hql/SubQueryTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by AsyncGenerator.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------


using NHibernate.Cfg.MappingSchema;
using NHibernate.Mapping.ByCode;
using NUnit.Framework;

namespace NHibernate.Test.Hql
{
using System.Threading.Tasks;
[TestFixture]
public class SubQueryTestAsync : TestCaseMappingByCode
{
protected override HbmMapping GetMappings()
{
var mapper = new ModelMapper();
mapper.Class<Root>(
rc =>
{
rc.Id(x => x.Id, m => m.Generator(Generators.Native));
rc.Property(x => x.RootName);
rc.ManyToOne(x => x.Branch);
});

mapper.Class<Branch>(
rc =>
{
rc.Id(x => x.Id, m => m.Generator(Generators.Native));
rc.Property(x => x.BranchName);
rc.Bag(x => x.Leafs, cm => cm.Cascade(Mapping.ByCode.Cascade.All), x => x.OneToMany());
});
mapper.Class<Leaf>(
rc =>
{
rc.Id(x => x.Id, m => m.Generator(Generators.Native));
rc.Property(x => x.LeafName);
});

return mapper.CompileMappingForAllExplicitlyAddedEntities();
}

protected override bool AppliesTo(Dialect.Dialect dialect)
{
return dialect.SupportsScalarSubSelects;
}

[TestCase("SELECT CASE WHEN l.id IS NOT NULL THEN (SELECT COUNT(r.id) FROM Root r) ELSE 0 END FROM Leaf l")]
[TestCase("SELECT CASE WHEN (SELECT COUNT(r.id) FROM Root r) > 1 THEN 1 ELSE 0 END FROM Leaf l")]
[TestCase("SELECT CASE WHEN l.id > 1 THEN 1 ELSE (SELECT COUNT(r.id) FROM Root r) END FROM Leaf l")]
[TestCase("SELECT CASE (SELECT COUNT(r.id) FROM Root r) WHEN 1 THEN 1 ELSE 0 END FROM Leaf l")]
[TestCase("SELECT CASE l.id WHEN (SELECT COUNT(r.id) FROM Root r) THEN 1 ELSE 0 END FROM Leaf l")]
public async Task TestSubQueryAsync(string query)
{
using (var session = OpenSession())
using (var transaction = session.BeginTransaction())
{
// Simple syntax check
await (session.CreateQuery(query).ListAsync());
await (transaction.CommitAsync());
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
using System.Collections.Generic;
using System.Linq;
using NHibernate.Cfg.MappingSchema;
using NHibernate.Exceptions;
using NHibernate.Mapping.ByCode;
using NHibernate.Type;
using NUnit.Framework;
Expand Down Expand Up @@ -124,8 +125,7 @@ protected async Task AreEqualAsync<TResult>(
{
expectedResult = await (expectedQuery(session.Query<T>()).ToListAsync(cancellationToken));
}
catch (OperationCanceledException) { throw; }
catch (Exception e)
catch (GenericADOException e)
{
Assert.Ignore($"Not currently supported query: {e}");
}
Expand Down
10 changes: 10 additions & 0 deletions src/NHibernate.Test/Hql/Ast/SqlTranslationFixture.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,16 @@ public void CaseClauseWithMath()
Assert.DoesNotThrow(() => GetSql(queryWithoutParen));
}

[Test]
public void SimpleCaseClauseWithMath()
{
const string query = "from SimpleClass s where (case (cast(s.IntValue as long) * :pAValue) when (cast(s.IntValue as long) * :pAValue) then (cast(s.IntValue as long) * :pAValue) else 1 end) > 0";
Assert.DoesNotThrow(() => GetSql(query));

const string queryWithoutParen = "from SimpleClass s where (case cast(s.IntValue as long) * :pAValue when cast(s.IntValue as long) * :pAValue then cast(s.IntValue as long) * :pAValue else 1 end) > 0";
Assert.DoesNotThrow(() => GetSql(queryWithoutParen));
}

[Test]
public void Union()
{
Expand Down
59 changes: 59 additions & 0 deletions src/NHibernate.Test/Hql/SubQueryTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
using NHibernate.Cfg.MappingSchema;
using NHibernate.Mapping.ByCode;
using NUnit.Framework;

namespace NHibernate.Test.Hql
{
[TestFixture]
public class SubQueryTest : TestCaseMappingByCode
{
protected override HbmMapping GetMappings()
{
var mapper = new ModelMapper();
mapper.Class<Root>(
rc =>
{
rc.Id(x => x.Id, m => m.Generator(Generators.Native));
rc.Property(x => x.RootName);
rc.ManyToOne(x => x.Branch);
});

mapper.Class<Branch>(
rc =>
{
rc.Id(x => x.Id, m => m.Generator(Generators.Native));
rc.Property(x => x.BranchName);
rc.Bag(x => x.Leafs, cm => cm.Cascade(Mapping.ByCode.Cascade.All), x => x.OneToMany());
});
mapper.Class<Leaf>(
rc =>
{
rc.Id(x => x.Id, m => m.Generator(Generators.Native));
rc.Property(x => x.LeafName);
});

return mapper.CompileMappingForAllExplicitlyAddedEntities();
}

protected override bool AppliesTo(Dialect.Dialect dialect)
{
return dialect.SupportsScalarSubSelects;
}

[TestCase("SELECT CASE WHEN l.id IS NOT NULL THEN (SELECT COUNT(r.id) FROM Root r) ELSE 0 END FROM Leaf l")]
[TestCase("SELECT CASE WHEN (SELECT COUNT(r.id) FROM Root r) > 1 THEN 1 ELSE 0 END FROM Leaf l")]
[TestCase("SELECT CASE WHEN l.id > 1 THEN 1 ELSE (SELECT COUNT(r.id) FROM Root r) END FROM Leaf l")]
[TestCase("SELECT CASE (SELECT COUNT(r.id) FROM Root r) WHEN 1 THEN 1 ELSE 0 END FROM Leaf l")]
[TestCase("SELECT CASE l.id WHEN (SELECT COUNT(r.id) FROM Root r) THEN 1 ELSE 0 END FROM Leaf l")]
public void TestSubQuery(string query)
{
using (var session = OpenSession())
using (var transaction = session.BeginTransaction())
{
// Simple syntax check
session.CreateQuery(query).List();
transaction.Commit();
}
}
}
}
29 changes: 29 additions & 0 deletions src/NHibernate.Test/Hql/SubQueryTestEntities.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
using System.Collections.Generic;

namespace NHibernate.Test.Hql
{
public class Root
{
public virtual int Id { get; set; }

public virtual string RootName { get; set; }

public virtual Branch Branch { get; set; }
}

public class Branch
{
public virtual int Id { get; set; }

public virtual string BranchName { get; set; }

public virtual IList<Leaf> Leafs { get; set; }
}

public class Leaf
{
public virtual int Id { get; set; }

public virtual string LeafName { get; set; }
}
}
3 changes: 2 additions & 1 deletion src/NHibernate.Test/NHSpecificTest/GH1879/FixtureByCode.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.Linq;
using NHibernate.Cfg.MappingSchema;
using NHibernate.Exceptions;
using NHibernate.Mapping.ByCode;
using NHibernate.Type;
using NUnit.Framework;
Expand Down Expand Up @@ -111,7 +112,7 @@ protected void AreEqual<TResult>(
{
expectedResult = expectedQuery(session.Query<T>()).ToList();
}
catch (Exception e)
catch (GenericADOException e)
{
Assert.Ignore($"Not currently supported query: {e}");
}
Expand Down
28 changes: 18 additions & 10 deletions src/NHibernate/Hql/Ast/ANTLR/Hql.g
Original file line number Diff line number Diff line change
Expand Up @@ -527,23 +527,31 @@ unaryExpression
;

caseExpression
: CASE (whenClause)+ (elseClause)? END
-> ^(CASE whenClause+ elseClause?)
| CASE unaryExpression (altWhenClause)+ (elseClause)? END
-> ^(CASE2 unaryExpression altWhenClause+ elseClause?)
: simpleCaseStatement
| searchedCaseStatement
;

whenClause
: (WHEN^ logicalExpression THEN! expression)

simpleCaseStatement
: CASE expression (simpleCaseWhenClause)+ (elseClause)? END
-> ^(CASE2 expression simpleCaseWhenClause+ elseClause?)
;
altWhenClause
: (WHEN^ unaryExpression THEN! expression)

simpleCaseWhenClause
: (WHEN^ expression THEN! expression)
;

elseClause
: (ELSE^ expression)
;

searchedCaseStatement
: CASE (searchedCaseWhenClause)+ (elseClause)? END
-> ^(CASE searchedCaseWhenClause+ elseClause?)
;

searchedCaseWhenClause
: (WHEN^ logicalExpression THEN! expression)
;

quantifiedExpression
: ( SOME^ | EXISTS^ | ALL^ | ANY^ )
Expand Down
24 changes: 22 additions & 2 deletions src/NHibernate/Hql/Ast/ANTLR/HqlSqlWalker.g
Original file line number Diff line number Diff line change
Expand Up @@ -432,8 +432,28 @@ arithmeticExpr
;

caseExpr
: ^(CASE { _inCase = true; } (^(WHEN logicalExpr expr))+ (^(ELSE expr))?) { _inCase = false; }
| ^(CASE2 { _inCase = true; } expr (^(WHEN expr expr))+ (^(ELSE expr))?) { _inCase = false; }
: simpleCaseExpression
| searchedCaseExpression
;

simpleCaseExpression
: ^(CASE2 {_inCase=true;} exprOrSubquery (simpleCaseWhenClause)+ (elseClause)?) {_inCase=false;}
;

simpleCaseWhenClause
: ^(WHEN exprOrSubquery exprOrSubquery)
;

elseClause
: ^(ELSE exprOrSubquery)
;

searchedCaseExpression
: ^(CASE {_inCase = true;} (searchedCaseWhenClause)+ (elseClause)?) {_inCase = false;}
;

searchedCaseWhenClause
: ^(WHEN logicalExpr exprOrSubquery)
;

//TODO: I don't think we need this anymore .. how is it different to
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,14 @@ public override void VisitSelectClause(SelectClause selectClause, QueryModel que
_expander.Transform(selectClause);
}

public override void VisitMainFromClause(MainFromClause fromClause, QueryModel queryModel)
{
if (fromClause.FromExpression is SubQueryExpression subqueryExpression)
{
VisitQueryModel(subqueryExpression.QueryModel);
}
}

public override void VisitOrdering(Ordering ordering, QueryModel queryModel, OrderByClause orderByClause, int index)
{
_expander.Transform(ordering);
Expand Down
8 changes: 8 additions & 0 deletions src/NHibernate/Linq/ReWriters/SubQueryConditionalExpander.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,14 @@ public override void VisitSelectClause(SelectClause selectClause, QueryModel que
_expander.Transform(selectClause);
}

public override void VisitMainFromClause(MainFromClause fromClause, QueryModel queryModel)
{
if (fromClause.FromExpression is SubQueryExpression subqueryExpression)
{
VisitQueryModel(subqueryExpression.QueryModel);
}
}

public override void VisitOrdering(Ordering ordering, QueryModel queryModel, OrderByClause orderByClause, int index)
{
_expander.Transform(ordering);
Expand Down