5

我遇到了以下编译错误:

• Couldn't match type ‘BaseBackend backend0’ with ‘SqlBackend’
    arising from a use of ‘runSqlite’
  The type variable ‘backend0’ is ambiguous
• In the expression: runSqlite ":memory:"
  In the expression:
    runSqlite ":memory:"
    $ do { records <- selectList [UserUsername ==. "abc"] [LimitTo 10];
           liftIO $ print (records :: [Entity User]) }
  In an equation for ‘selectAll’:
      selectAll
        = runSqlite ":memory:"
          $ do { records <- selectList [UserUsername ==. "abc"] [LimitTo 10];
                 liftIO $ print (records :: [Entity User]) }

代码:

selectAll :: IO ()
selectAll = runSqlite ":memory:" $ do
  records <- selectList [UserUsername ==. "abc"] [LimitTo 10]
  liftIO $ print (records :: [Entity User])

看看 runSqlite 的类型签名:

runSqlite    
:: (MonadBaseControl IO m, MonadIO m, IsSqlBackend backend)  
=> Text 
-> ReaderT backend (NoLoggingT (ResourceT m)) a 
-> m a

我假设我需要为 runSqlite 指定一个显式类型,尽管我不太确定我在 in 中设置了backend什么ReaderT backend (NoLoggingT (ResourceT m)) a

4

1 回答 1

5

你可以专攻它SqlBackend

asSqlBackendReader :: ReaderT SqlBackend m a -> ReaderT SqlBackend m a
asSqlBackendReader = id

selectAll :: IO ()
selectAll = runSqlite ":memory:" . asSqlBackendReader $ do
  records <- selectList [UserUsername ==. "abc"] [LimitTo 10]
  liftIO $ print (records :: [Entity User])

查看 的类型,需要满足runSqlite一个约束条件。IsSqlBackend backend

的定义IsSqlBackend是:

type IsSqlBackend backend =
  (IsPersistBackend backend, BaseBackend backend ~ SqlBackend)

然后抬头看IsPersistBackend

就在类的定义下方,我们看到它具有三个实例:

instance IsPersistBackend SqlWriteBackend
instance IsPersistBackend SqlReadBackend
instance IsPersistBackend SqlBackend

这三种类型指定了具有各种功能的后端,其中SqlBackend最通用的一种(未知功能)。如果这就是您所需要的,请随意使用更受限制的。

于 2017-05-29T22:41:52.407 回答