Skip to content

Instantly share code, notes, and snippets.

@khibino
Created December 19, 2014 16:31
Show Gist options
  • Save khibino/1e7f608c15e48acfc57b to your computer and use it in GitHub Desktop.
Save khibino/1e7f608c15e48acfc57b to your computer and use it in GitHub Desktop.
> {-# LANGUAGE TemplateHaskell, MultiParamTypeClasses, FlexibleInstances #-}
>
> import Data.Int
>
> import Database.Relational.Query
> import Database.Relational.Query.TH
>
>
> $(defineTableDefault defaultConfig
> "PUBLIC" "my_table"
> [ ("person", [t| String |])
> , ("family", [t| String |])
> , ("age" , [t| Int32 |])
> ]
> [] [0] (Just 0))
>
>
> agesOfFamiliesQ :: QueryAggregate (Projection Aggregated (String, Maybe Int32))
> agesOfFamiliesQ = do
> my <- query myTable
> gFam <- groupBy $ my ! family'
> return $ gFam >< sum' (my ! age')
>
> justAgeOfFamilies0 :: Relation () (Maybe Int32)
> justAgeOfFamilies0 = aggregateRelation $ do
> pair <- agesOfFamiliesQ
> return $ pair ! snd'
>
> -- *Main> justAgeOfFamilies0
> -- SELECT ALL SUM (T0.age) AS f0 FROM PUBLIC.my_table T0 GROUP BY T0.family
>
> agesOfFamilies :: Relation () (String, Maybe Int32)
> agesOfFamilies = aggregateRelation agesOfFamiliesQ
>
> justAgeOfFamilies1 :: Relation () (Maybe Int32)
> justAgeOfFamilies1 = relation $ do
> pair <- query agesOfFamilies
> return $ pair ! snd'
>
> -- *Main> justAgeOfFamilies1
> -- SELECT ALL T1.f1 AS f0
> -- FROM (SELECT ALL T0.family AS f0, SUM (T0.age) AS f1
> -- FROM PUBLIC.my_table T0 GROUP BY T0.family) T1
>
> main :: IO ()
> main = do
> putStrLn "0"
> print justAgeOfFamilies0
> putStrLn "1"
> print justAgeOfFamilies1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment