bitemyapp / esqueleto

New home of Esqueleto, please file issues so we can get things caught up!
BSD 3-Clause "New" or "Revised" License
370 stars 107 forks source link

`distinctOnOrderBy` generates bad sql with nested exprs #277

Closed NikitaRazmakhnin closed 2 years ago

NikitaRazmakhnin commented 2 years ago

We noticed that when we use some nested expression with distinctOnOrderBy like coalesce generates bad sql in the beginning of a query:

let someVal = coalesce [ entity1?.Entity1Value, entity2^.Entity2Value ]
distinctOnOrderBy [ asc someVal ] $ do pure someVal

gives something like that

SELECT DISTINCT ON (COALESCE("entity1"."entity2_value",)
              COALESCE("entity1"."entity1_value", "entity2".entity2_value")
ORDER BY COALESCE("entity1"."entity1_value", "entity2".entity2_value")  ASC

So it omits second substitution-part of COALESCE expression for some reasons but the value expression itself works perfectly in ORDER BY part. So it behaves badly only in DISTINCT ON (..) clause.

Rewriting it into usual distinctOn [don ...] $ do orderBy [...] works perfectly.