Skip to content

Group HAVING filters #476

Description

@yankyhgoflow

Hi,

When using WHERE filters we might want to group some filters together, using the following filter as an example

-- Postgres
SELECT * FROM ""Table1""
WHERE (""Column1"" = 10 OR ""Column2"" = 20) AND ""Column3"" = 30

If we wouldn't group the OR filters the AND will take precedence, SqlKata has the mechanism to generate the above query perfectly well

new Query("Table1")
    .Where(q => q.Or().Where("Column1", 10).Or().Where("Column2", 20))
    .Where("Column3", 30);

My question is regarding the same functionality but with a HAVING clause, I understood that the API will be the same, but when trying the following code

new Query("Table1")
    .Having(q => q.Or().HavingRaw("SUM([Column1]) = ?", 10).Or().HavingRaw("SUM([Column2]) = ?", 20))
    .HavingRaw("SUM([Column3]) = ?", 30);

This is the generated SQL

SELECT * FROM "Table1"
HAVING AND SUM("Column3")

The filters within the filter group .Having(q => q...) is missing and the HAVING clause just starts with an AND

Sample test methods

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]);
        }
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions