Search code examples
haskellyesodpersistent

How can I run Yesod's DB actions in the REPL?


It is easy to run DB actions in the normal Handler workflow, since the runDB function can be used to transform the SqlPersistM actions into Handler ones.

But there is no such way to convert SqlPersistM directly into IO using the default app settings. Looking at the Foundation.hs as its defined in the application scaffold, there is the following instance

instance YesodPersist App where
    type YesodPersistBackend App = SqlBackend
    runDB action = do
        master <- getYesod
        runSqlPool action $ appConnPool master
instance YesodPersistRunner App where
    getDBRunner = defaultGetDBRunner appConnPool

which basically uses runSqlPool with the app's config, but I don't see an easy way how to leverage this to access the config form within the REPL.

TL;DR: What I'm looking for is simply being able to do something like runDB $ selectList [...] [...] from within cabal repl in my Yesod app, without having to duplicate the setup that Yesod scaffolding does out of the box.


Solution

  • If you're using the Yesod scaffolding, the handler and db functions are provided to let you run handler actions and database queries, respectively, from the repl:

    $ cabal repl
    
    db $ selectList [UserName ==. "foo"] []
    

    Edit: I've also updated Yesod's wiki page on GHCi with this information. It includes more examples and covers some advanced usage, like using the debugger.