haskelldb
haskelldb copied to clipboard
Double aggregation leads to malformed SQL
If I aggregate twice in a row I seem to get malformed SQL. For example with this code
import Database.HaskellDB.PrimQuery
import Database.HaskellDB.Query
import Database.HaskellDB.DBLayout
data Apples = Apples
instance FieldTag Apples where
fieldName _ = "apples"
data Name' = Name'
instance FieldTag Name' where
fieldName _ = "name"
apples :: Attr Apples Int
apples = mkAttr Apples
name :: Attr Name' String
name = mkAttr Name'
appleTable :: Table (RecCons Apples Int (RecCons Name' String RecNil))
appleTable = Table "apple_table" [ ("apples", AttrExpr "applecol")
, ("name", AttrExpr "namecol") ]
summed :: Query (Rel (RecCons Apples (Expr Int) (RecCons Name' (Expr String) RecNil)))
summed = do
b <- table appleTable
project (apples << _sum(b!apples) #
name << b!name)
summed' :: Query (Rel (RecCons Apples (Expr Int) (RecCons Name' (Expr String) RecNil)))
summed' = do
b <- summed
project (apples << _sum(b!apples) #
name << b!name)
showStrange = putStrLn $ showSql summed'
I get the result
*Main> showStrange
SELECT SUM(SUM(applecol)) as apples,
namecol as name
FROM apple_table as T1
GROUP BY namecol
I suspect the culprit is this
https://github.com/m4dc4p/haskelldb/blob/master/src/Database/HaskellDB/Optimize.hs#L142
It should be checked that assoc1
contains no aggregations before merging the projections.