From 18951b280b34142ff4faad0c0bafc2aa84427e60 Mon Sep 17 00:00:00 2001 From: Nikita Razmakhnin <58581226+NikitaRazmakhnin@users.noreply.github.com> Date: Thu, 2 Sep 2021 21:39:29 +0300 Subject: [PATCH] Fix distinctOnOrderBy with nested expression (#278) * Fix stripped part of nested expression during assembling of `distinctOnOrderBy` subexpression * Bump version number and update changelog --- changelog.md | 6 ++++++ esqueleto.cabal | 2 +- src/Database/Esqueleto/Internal/Internal.hs | 6 +++++- test/PostgreSQL/Test.hs | 6 ++++++ 4 files changed, 18 insertions(+), 2 deletions(-) diff --git a/changelog.md b/changelog.md index 7dc4b97..50d7f74 100644 --- a/changelog.md +++ b/changelog.md @@ -1,3 +1,9 @@ +3.5.2.2 +======= +- @NikitaRazmakhnin + - [#278](https://github.com/bitemyapp/esqueleto/pull/278) + - Fix generating of bad sql using nexted expressions with `distinctOnOrderBy`. + 3.5.2.1 ======= - @cdparks diff --git a/esqueleto.cabal b/esqueleto.cabal index f87997a..b767528 100644 --- a/esqueleto.cabal +++ b/esqueleto.cabal @@ -1,7 +1,7 @@ cabal-version: 1.12 name: esqueleto -version: 3.5.2.1 +version: 3.5.2.2 synopsis: Type-safe EDSL for SQL queries on persistent backends. description: @esqueleto@ is a bare bones, type-safe EDSL for SQL queries that works with unmodified @persistent@ SQL backends. Its language closely resembles SQL, so you don't have to learn new concepts, just new syntax, and it's fairly easy to predict the generated SQL and optimize it for your backend. Most kinds of errors committed when writing SQL are caught as compile-time errors---although it is possible to write type-checked @esqueleto@ queries that fail at runtime. . diff --git a/src/Database/Esqueleto/Internal/Internal.hs b/src/Database/Esqueleto/Internal/Internal.hs index 99b8113..1eb7b7c 100644 --- a/src/Database/Esqueleto/Internal/Internal.hs +++ b/src/Database/Esqueleto/Internal/Internal.hs @@ -374,7 +374,11 @@ distinctOnOrderBy exprs act = toDistinctOn :: SqlExpr OrderBy -> SqlExpr DistinctOn toDistinctOn (ERaw m f) = ERaw m $ \p info -> let (b, vals) = f p info - in (TLB.fromLazyText $ head $ TL.splitOn " " $ TLB.toLazyText b, vals) + in ( TLB.fromLazyText + $ TL.replace " DESC" "" + $ TL.replace " ASC" "" + $ TLB.toLazyText b + , vals ) -- | @ORDER BY random()@ clause. -- diff --git a/test/PostgreSQL/Test.hs b/test/PostgreSQL/Test.hs index d5e9848..13cae96 100644 --- a/test/PostgreSQL/Test.hs +++ b/test/PostgreSQL/Test.hs @@ -220,6 +220,12 @@ testSelectDistinctOn = do slightlyLessSimpleTest $ \bp -> distinctOnOrderBy [asc (bp ^. BlogPostAuthorId), asc (bp ^. BlogPostTitle)] + itDb "generates correct sql with nested expression (distinctOnOrderBy)" $ do + let query = do + let orderVal = coalesce [nothing, just $ val (10 :: Int)] + distinctOnOrderBy [ asc orderVal, desc orderVal ] $ pure orderVal + select query + asserting noExceptions