how to use groupBy
#185
-
|
I'm trying to write a query like SELECT array_agg(foo) FROM bar GROUP BY bazbut I'm struggling to understand how to do it. How should the |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 1 reply
-
{-# language DeriveAnyClass #-}
{-# language DeriveGeneric #-}
{-# language NamedFieldPuns #-}
{-# language OverloadedStrings #-}
module Foo
( query
, test
) where
-- base
import GHC.Generics (Generic)
-- rel8
import Rel8
( Expr
, Column
, Name
, Query
, Rel8able
, TableSchema(..)
, aggregate
, each
, groupBy
, listAggExpr
, showQuery
)
-- text
import Data.Text (Text)
data Bar f = Bar
{ foo :: Column f Text
, baz :: Column f Text
} deriving (Generic, Rel8able)
barSchema :: TableSchema (Bar Name)
barSchema = TableSchema
{ name = "bar"
, schema = Nothing
, columns = Bar
{ foo = "foo"
, baz = "baz"
}
}
query :: Query (Expr Text, Expr [Text])
query = aggregate $ do
Bar {foo, baz} <- each barSchema
pure (groupBy foo, listAggExpr baz)
test :: IO ()
test = putStrLn $ showQuery queryDoes this work for you? |
Beta Was this translation helpful? Give feedback.
-
|
thanks @shane-circuithub. I actually figured it out and I created a PR adding a little bit of documentation |
Beta Was this translation helpful? Give feedback.
-
|
For what it's worth, depending on what you're trying to do, the example in the documentation might be more idiomatically written as: itemsByOrder :: Tabulation (Expr OrderId) (ListTable Expr (Item Expr))
itemsByOrder = Tabulation.many $ Tabulation.fromQuery $ do
item <- each itemSchema
pure (itemOrderId item, item) |
Beta Was this translation helpful? Give feedback.
{-# language DeriveAnyClass #-} {-# language DeriveGeneric #-} {-# language NamedFieldPuns #-} {-# language OverloadedStrings #-} module Foo ( query , test ) where -- base import GHC.Generics (Generic) -- rel8 import Rel8 ( Expr , Column , Name , Query , Rel8able , TableSchema(..) , aggregate , each , groupBy , listAggExpr , showQuery ) -- text import Data.Text (Text) data Bar f = Bar { foo :: Column f Text , baz :: Column f Text } deriving (Generic, Rel8able) barSchema :: TableSchema (Bar Name) barSchema = TableSchema { name = "bar" , schema = Nothing , columns = Bar { foo = "foo" , baz = "baz" } } query :: Query (Expr