circuithub / rel8

Hey! Hey! Can u rel8?
https://rel8.readthedocs.io
Other
150 stars 38 forks source link

how to use `groupBy` #181

Closed marcosh closed 2 years ago

marcosh commented 2 years ago

I'm trying to write a query like

SELECT array_agg(foo) FROM bar GROUP BY baz

but I'm struggling to understand how to do it.

How should the groupBy combinator be used?

shane-circuithub commented 2 years ago
{-# 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 query

Does this work for you?

marcosh commented 2 years ago

thanks @shane-circuithub. I actually figured it out and I created a PR adding a little bit of documentation