m4dc4p / haskelldb

A library for building re-usable and composable SQL queries.
BSD 3-Clause "New" or "Revised" License
102 stars 17 forks source link

Double aggregation leads to malformed SQL #15

Open tomjaguarpaw opened 11 years ago

tomjaguarpaw commented 11 years ago

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
tomjaguarpaw commented 10 years ago

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.