Yesod:在ghci中运行`runDB`函数时输入实例错误

ren*_*nny 5 haskell persistent ghci yesod

在ghci中加载scaffolded站点后获取runDB的正确实例是什么?例如,在运行这句话时:

runDB $ selectList [UserName ==. "Renny"] []
Run Code Online (Sandbox Code Playgroud)

错误是:

Couldn't match type `PersistMonadBackend
(YesodPersistBackend site0 (HandlerT site0 IO))'
with `persistent-1.3.0.6:Database.Persist.Sql.Types.SqlBackend'
The type variable `site0' is ambiguous
Possible fix: add a type signature that fixes these type variable(s)
Expected type: PersistMonadBackend
                 (YesodPersistBackend site0 (HandlerT site0 IO))
  Actual type: PersistEntityBackend User
In the second argument of `($)', namely
  `selectList [UserName ==. "Renny"] []'
In the expression: runDB $ selectList [UserName ==. "Renny"] []
In an equation for `it':
    it = runDB $ selectList [UserName ==. "Renny"] []
Run Code Online (Sandbox Code Playgroud)

提前致谢

编辑:我忘记了Yesod Scaffold的runDB返回Handler,这导致我解决这个问题(虽然我确信这是一个更好的解决方案):

xs <- runSqlite "MyProject.sqlite3" (selectList [UserName ==. "Renny"] []) 
Run Code Online (Sandbox Code Playgroud)

哪里"MyProject.sqlite3"是Sqlite数据库的名称.

这不是一般化的解决方案.根据文档和正如这篇 文章所说,其他后端略有不同.

Tho*_*mas 3

问题在于,与依赖环境状态的命令式语言不同,Haskell 依赖显式(和隐式)状态传递。

从 ghci运行时runDB $ ...,您尝试直接在 IO 中运行此代码片段,因此您无法引用应用程序状态(包括数据库连接)。类型错误通知您,The type variable 'site0' is ambiguous因为它无法推断您尝试运行此语句的应用程序状态。

在 ghci 中,前缀runSqlite "MyProject.sqlite3"是有效的,因为您专门设置了针对正确数据库运行的环境,并且 runSqlite 在 IO 中工作,这正是 ghci 想要的。