Skip to content

Using Pagination with CTE query generates wrong countQuery #3752

@saadalmogren

Description

@saadalmogren

Hello,
I am using the latest spring-data-jpa:3.4.2 with postgresql and faced the below issue:

using two CTE Queries with native query enabled as below:

@Query(value = """
            WITH credit_transactions AS (
                SELECT
                    *
                FROM transaction trx
                WHERE trx."CreditDebit" = 'CR' AND trx."Message Reference Id" > :transactionIdOffset
            ),
            debit_transactions AS (
                SELECT
                    *
                FROM transaction trx
                WHERE trx."CreditDebit" = 'DR' AND trx."Message Reference Id" > :transactionIdOffset
            )
            SELECT
                COALESCE(c."Message Reference Id", d."Message Reference Id") AS "Message Reference Id",
            FROM credit_transactions c
            FULL OUTER JOIN debit_transactions d
                ON c."Message Reference Id" = d."Message Reference Id" ORDER BY "Message Reference Id" ASC 
            """,
            nativeQuery = true)
    Page<Transaction> getTransactionsByOffset(@Param("transactionIdOffset") Long transactionIdOffset, Pageable pageable);

but hibernate executes the following query

WITH credit_transactions AS (select count(trx) FROM transaction trx
    WHERE trx."CreditDebit" = 'CR' AND trx."Message Reference Id" > ?
),
debit_transactions AS (
    SELECT
        *
    FROM transaction trx
    WHERE trx."CreditDebit" = 'DR' AND trx."Message Reference Id" > ?
)
SELECT
COALESCE(c."Message Reference Id", d."Message Reference Id") AS "Message Reference Id",
FROM credit_transactions c
FULL OUTER JOIN debit_transactions d
    ON c."Message Reference Id" = d."Message Reference Id"

and throws the following error:

Caused by: org.postgresql.util.PSQLException: ERROR: column c.Message Reference Id does not exist
  Hint: Perhaps you meant to reference the column "d.Message Reference Id".

CAUSE:
It changed the first CTE with:

WITH credit_transactions AS (select count(trx) FROM transaction trx
    WHERE trx."CreditDebit" = 'CR' AND trx."Message Reference Id" > ?
)

Workaround:
I was able to workaround the issue by specifying an explicit countQuery. Thanks to: #3726 (comment)

Metadata

Metadata

Assignees

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