diff --git a/QueryBuilder.Tests/WhereTests.cs b/QueryBuilder.Tests/WhereTests.cs new file mode 100644 index 00000000..0c1254b2 --- /dev/null +++ b/QueryBuilder.Tests/WhereTests.cs @@ -0,0 +1,33 @@ +using SqlKata.Compilers; +using SqlKata.Tests.Infrastructure; +using Xunit; + +namespace SqlKata.Tests +{ + public class WhereTests : TestSupport + { + [Fact] + public void GroupedWhereFilters() + { + var q = new Query("Table1") + .Where(q => q.Or().Where("Column1", 10).Or().Where("Column2", 20)) + .Where("Column3", 30); + + var c = Compile(q); + + Assert.Equal(@"SELECT * FROM ""Table1"" WHERE (""Column1"" = 10 OR ""Column2"" = 20) AND ""Column3"" = 30", c[EngineCodes.PostgreSql]); + } + + [Fact] + public void GroupedHavingFilters() + { + var q = new Query("Table1") + .Having(q => q.Or().HavingRaw("SUM([Column1]) = ?", 10).Or().HavingRaw("SUM([Column2]) = ?", 20)) + .HavingRaw("SUM([Column3]) = ?", 30); + + var c = Compile(q); + + Assert.Equal(@"SELECT * FROM ""Table1"" HAVING (SUM(""Column1"") = 10 OR SUM(""Column2"") = 20) AND SUM(""Column3"") = 30", c[EngineCodes.PostgreSql]); + } + } +} diff --git a/QueryBuilder/Compilers/Compiler.Conditions.cs b/QueryBuilder/Compilers/Compiler.Conditions.cs index 1f24dd78..190a85ea 100644 --- a/QueryBuilder/Compilers/Compiler.Conditions.cs +++ b/QueryBuilder/Compilers/Compiler.Conditions.cs @@ -170,12 +170,14 @@ protected virtual string CompileBasicDateCondition(SqlResult ctx, BasicDateCondi protected virtual string CompileNestedCondition(SqlResult ctx, NestedCondition x) where Q : BaseQuery { - if (!x.Query.HasComponent("where", EngineCode)) + if (!(x.Query.HasComponent("where", EngineCode) || x.Query.HasComponent("having", EngineCode))) { return null; } - var clauses = x.Query.GetComponents("where", EngineCode); + var clause = x.Query.HasComponent("where", EngineCode) ? "where" : "having"; + + var clauses = x.Query.GetComponents(clause, EngineCode); var sql = CompileConditions(ctx, clauses);