domaframework / doma

DAO oriented database mapping framework for Java
https://doma.readthedocs.io/
Apache License 2.0
447 stars 70 forks source link

MSSQL: TOP keyword is appended in wrong place when select with DISTINCT #1076

Closed longgt closed 8 months ago

longgt commented 8 months ago

Describe the bug In MSSQL, execute a query with both DISTINCT and limit causes invalid syntax exception.

The root cause might come from the below code while Doma is trying to inject TOP keyword into SELECT clause https://github.com/domaframework/doma/blob/bcc3e124910e6cf4caebf0277f17d21d486fa730/doma-core/src/main/java/org/seasar/doma/internal/jdbc/dialect/Mssql2008PagingTransformer.java#L39

Expected behavior

As described in the link below, the TOP keyword should be appended after DISTINCT (if exists), not right after SELECT https://learn.microsoft.com/en-us/sql/t-sql/queries/select-transact-sql?view=sql-server-ver16

Actual behavior The TOP keyword is append right after SELECT which causes invalid syntax error while executing.

To Reproduce Execute with offset = 0, limit = 50 for the below query

SELECT   DISTINCT FirstName,
                  LastName
FROM     Person.Person
ORDER BY LastName

The current generated SQL of Doma (at debug step of org.seasar.doma.internal.jdbc.dialect.MssqlPagingTransformer)

SELECT TOP(50) DISTINCT FirstName,
                  LastName
FROM     Person.Person
ORDER BY LastName

An exception with message Incorrect syntax near the keyword 'DISTINCT' was thrown.

It should be generated as

SELECT  DISTINCT TOP(50)  FirstName,
                  LastName
FROM     Person.Person
ORDER BY LastName

The workaround is creating a Dialect with forces to use the OFFSET FETCH Clause for a pagination.

@Configuration
public class DomaConfiguration {
    @Bean
    public Dialect dialect(Environment environment) {
        return new MssqlDialect(new MssqlJdbcMappingVisitor(), new MssqlSqlLogFormattingVisitor(), new MssqlExpressionFunctions(), true);
    }
}

Environment (please complete the following information):

nakamura-to commented 8 months ago

Thanks for your feedback.