diff --git a/src/Database/Esqueleto/PostgreSQL.hs b/src/Database/Esqueleto/PostgreSQL.hs index 8982c3f..b45be5b 100644 --- a/src/Database/Esqueleto/PostgreSQL.hs +++ b/src/Database/Esqueleto/PostgreSQL.hs @@ -7,6 +7,7 @@ module Database.Esqueleto.PostgreSQL ( arrayAggDistinct , arrayAgg , arrayRemove + , arrayRemoveNull , stringAgg , chr , now_ @@ -48,6 +49,11 @@ arrayAgg = unsafeSqlFunction "array_agg" arrayRemove :: SqlExpr (Value [a]) -> SqlExpr (Value a) -> SqlExpr (Value [a]) arrayRemove arr elem' = unsafeSqlFunction "array_remove" (arr, elem') +-- | Remove @NULL@ values from an array +arrayRemoveNull :: SqlExpr (Value [Maybe a]) -> SqlExpr (Value [a]) +arrayRemoveNull x = unsafeSqlFunction "array_remove" (x, unsafeSqlValue "NULL") + + -- | (@string_agg@) Concatenate input values separated by a -- delimiter. -- diff --git a/test/PostgreSQL/Test.hs b/test/PostgreSQL/Test.hs index 00ce7e0..e9a3c72 100644 --- a/test/PostgreSQL/Test.hs +++ b/test/PostgreSQL/Test.hs @@ -237,6 +237,25 @@ testSelectDistinctOn = do +testArrayRemoveNull :: SpecWith (Arg (IO ())) +testArrayRemoveNull = do + describe "array_remove (NULL)" $ do + it "removes NULL from arrays from nullable fields" $ run $ do + mapM_ insert [ Person "1" Nothing Nothing 1 + , Person "2" (Just 7) Nothing 1 + , Person "3" (Nothing) Nothing 1 + , Person "4" (Just 8) Nothing 2 + , Person "5" (Just 9) Nothing 2 + ] + ret <- select . from $ \(person :: SqlExpr (Entity Person)) -> do + groupBy (person ^. PersonFavNum) + return . EP.arrayRemoveNull $ EP.arrayAgg (person ^. PersonAge) + liftIO $ (L.sort $ map (L.sort . unValue) ret) `shouldBe` [[7], [8,9]] + + + + + testPostgresModule :: Spec testPostgresModule = do describe "PostgreSQL module" $ do @@ -317,7 +336,7 @@ run = verbose :: Bool -verbose = False +verbose = True migrateIt :: RunDbMonad m => SqlPersistT (R.ResourceT m) () migrateIt = do