在 ghci 中加载脚手架站点后获得 runDB 返回的正确实例是什么?例如,在运行这句话时:
runDB $ selectList [UserName ==. "Renny"] []
错误是:
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"] []
提前致谢
编辑:
我忘了 Yesod Scaffold 的
runDB
返回一个处理程序,这使我采用了这种解决方法(尽管我确信这是一个更好的解决方案):xs <- runSqlite "MyProject.sqlite3" (selectList [UserName ==. "Renny"] [])
哪里
"MyProject.sqlite3"
是 Sqlite 数据库的名称。这不是一个通用的解决方案。根据文档和这样 post 说,其他后端略有不同。
最佳答案
问题在于,与依赖环境状态的命令式语言不同,Haskell 依赖于显式(和隐式)状态传递。
运行时 runDB $ ...
从 ghci,您试图直接在 IO 中运行此代码段,因此您没有引用应用程序状态(包括您的数据库连接)。类型错误通知您它是 The type variable 'site0' is ambiguous
因为它无法推断出您试图针对什么应用程序状态运行此语句。
在 ghci 中,前缀 runSqlite "MyProject.sqlite3"
之所以有效,是因为您专门设置了针对正确数据库运行的环境,而 runSqlite 在 IO 中工作,这正是 ghci 想要的。
关于haskell - Yesod:在 ghci 中运行 `runDB` 函数时键入实例错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23437621/