spring-data-relational icon indicating copy to clipboard operation
spring-data-relational copied to clipboard

OrderBy only accepts columns, although it should really accept Expressions

Open schauder opened this issue 4 years ago • 2 comments

schauder avatar Dec 10 '21 17:12 schauder

Concrete example for this issue:

After updating from 2.2.5 to 2.3.0 invalid SQL queries are generated for PagingAndSortingRepository methods when a jsonb field is used in the order by statement combined with a type cast.

Example:

With 2.2.5 the following findById method:

@Repository
interface ExampleRepository : PagingAndSortingRepository<Entity, String> {

    fun findById(id: String, pageable: Pageable): List<Entity>
	
} 

generated a query like this:

SELECT "entity"."attribute1" AS "attributeName1",
"entity"."attribute2" AS "attributeName2"
...
"entity"."attributeN" AS "attributeNameN" FROM "entity"
WHERE "entity"."id" = ? 
ORDER BY (jsonbField ->> 'jsonbAtttribute')::int DESC LIMIT 20 OFFSET 0

After updating to 2.3.0. The query looks like this:

SELECT "entity"."attribute1" AS "attributeName1",
"entity"."attribute2" AS "attributeName2"
...
"entity"."attributeN" AS "attributeNameN" FROM "entity"
WHERE "entity"."id" = ? 
ORDER BY "entity".(jsonbField ->> 'jsonbAtttribute')::int DESC LIMIT 20 OFFSET 0

which is invalid SQL ("entity".(jsonbField ->> 'jsonbAtttribute'::int)) and a PSQLException is thrown with the message: ERROR: syntax error at or near "("

chriskn avatar Dec 20 '21 10:12 chriskn

This is also doesn't work when trying to use a custom sort like

Expressions.just(
  "GREATEST(${table.column("updated_at")}, " +
      "${brandings.column("updated_at")}, " +
      "${merchantContactDetails.column("updated_at")})"
)

The generated SQL for this looks like ORDER BY ASC, so the complete expression is omitted.

koenpunt avatar Oct 05 '22 11:10 koenpunt