2

我正在尝试使用来自 Esqueleto 的示例查询之一,但我无法编译它。唯一的变化是我在没有连接的情况下使用它。

我有一个看起来像这样的表:

sqlite> select * from my_table;
id|category|amount
1|A|1.0
2|A|2.0
3|B|2.0
4|B|8.0

我想这样做:

select category,sum(amount) from my_table group by category;
category|sum(amount)
A|3.0
B|10.0

这是我的查询:

import qualified Database.Esqueleto as E

r <- runDB $
    E.select $ E.from $ \t  -> do
        E.groupBy $ t E.^. MyTableCategory
        let sum' = E.sum_ (t E.^. MyTableAmount)
        E.orderBy [E.desc sum']
        return (t E.^. MyTableCategory, sum' )

我收到此错误:

No instance for (PersistField b0) arising from a use of `E.select'
The type variable `b0' is ambiguous
Possible fix: add a type signature that fixes these type variable(s)
Note: there are several potential instances:
  instance PersistField Account -- Defined in `Model'
  instance PersistField AccountCategory -- Defined in `Model'
  instance PersistField MyTable -- Defined in `Model'
  ...plus 37 others
In the expression: E.select
In the second argument of `($)', namely
  `E.select
   $ E.from
     $ \ t
         -> do { E.groupBy $ t E.^. MyTableCategory;
                 let ...;
                 .... }'
In a stmt of a 'do' block:
  r <- runDB
       $ E.select
         $ E.from
           $ \ t
               -> do { E.groupBy $ t E.^. MyTableCategory;
                       let ...;
                       .... }

我在哪里提供类型信息E.select?编译器应该能够从中推断t E.^.MyTableCategory吗?我也尝试使用countRows / groupBy此处的示例(https://hackage.haskell.org/package/esqueleto-1.4.1/docs/Database-Esqueleto.html)但类似的问题(唯一的区别是我没有加入)

感谢你的帮助。

谢谢!

4

1 回答 1

5

from table 参数类型有时是从必须明确的结果类型推导出来的。

通常会出现关于 monad 类型的其他歧义。

将查询包含在特定函数中以解决一些歧义很有用。

我现在无法证明您的esqueleto查询符合性,但是

尝试这个:

{-# LANGUAGE PackageImports, ConstraintKinds #-}

import Import
import "esqueleto" Database.Esqueleto as E
import "monad-logger" Control.Monad.Logger (MonadLogger)
import "resourcet" Control.Monad.Trans.Resource (MonadResourceBase)

type TCategory = Text  -- change it if its different
type TAmount = Double

myQuery :: (PersistQuery (SqlPersist m), MonadLogger m , MonadResourceBase m) =>

                        SqlPersist m [(E.Value TCategory, E.Value (Maybe TAmount))] -- corrected
myQuery = do

  -- your query

  E.select $ E.from $ \t  -> do
        E.groupBy $ t E.^. MyTableCategory
        let sum' = E.sum_ (t E.^. MyTableAmount)  
        E.orderBy [E.desc sum']
        return (t E.^. MyTableCategory, sum' )  

-- within your handler:

    pairListResult <- runDB myQuery

    forM_ pairListResult $ \(E.Value categ, E.Value maybeAmount) -> do -- whatever

更新:它编译

于 2014-05-11T14:30:11.630 回答