如何在Yesod应用程序中的GHCi中执行数据库查询

时间:2014-01-07 09:29:00

标签: haskell yesod persistent ghci

如何使用Yesod应用程序的模型将新用户插入数据库?或者有更好的方法吗?

我正在处理脚手架应用程序。现在我创建了App实例,并且不知道如何使用它来执行请求。

:i Extra
data Extra
  = Extra {extraCopyright :: Data.Text.Internal.Text,
           extraAnalytics :: Maybe Data.Text.Internal.Text}
        -- Defined in `Settings

let e = Extra "asdf" Nothing
let c = AppConfig {appEnv = Development, appPort = 3000, appRoot = "/", appHost = "localhost", appExtra = e}
f <- makeFoundation c
:t f
f :: App

:i App
data App
  = App {settings :: AppConfig DefaultEnv Extra,
         getStatic :: Yesod.Static.Static,
         connPool :: persistent-1.2.3.0:Database.Persist.Class.PersistConfig.PersistConfigPool
                       PersistConf,
         httpManager :: http-client-0.2.0.1:Network.HTTP.Client.Types.Manager,
         persistConfig :: PersistConf,
         appLogger :: Yesod.Core.Types.Logger}
        -- Defined in `Foundation'

下一步是什么?

3 个答案:

答案 0 :(得分:6)

如果您只想在ghci中执行持久性查询,则可以在不创建Yesod应用程序的情况下执行此操作。不幸的是,根据您要使用的特定后端,这样做有很大不同。

对于SQLite:

> import Database.Persist.Sqlite
> import Model
> pool <- createSqlitePool "yesod-test.sqlite3" 2
> runSqlite "yesod-test.sqlite3" (runMigration migrateAll)
> userId <- runSqlite "yesod-test.sqlite3" (insert (User "foo@bar.com" Nothing))

对于Postgresql:

-- In Shell: $ createdb yesod-test
> import Database.PostgreSQL.Simple
> con <- connectPostgreSQL  "dbname=yesod-test"
> import Database.Persist.Postgresql
> pcon <- openSimpleConn con
> import Model
> runSqlPersistM (runMigration migrateAll) pcon
> userId <- runSqlPersistM (insert (User "foo@bar.com" Nothing)) pcon
> Just user <- runSqlPersistM (get userId) pcon
> userIdent user

答案 1 :(得分:3)

脚手架提供(至少使用yesod-bin 1.4.5)db中的函数Application.hs,您可以使用:

$ cabal repl
...
*Application> db $ insert $ User "foo@bar.com" Nothing

答案 2 :(得分:0)

似乎已接受的答案很旧。这是使用postgresql后端在IO中运行持久查询的更新。

import Control.Monad.Reader (ReaderT)
import Control.Monad.Logger (LoggingT, runStdoutLoggingT)
import Database.Persist.Sql (SqlBackend, runSqlConn)
import Database.Persist.Postgresql (withPostgresqlConn)

runDBIO :: ReaderT SqlBackend (LoggingT IO) a -> IO a
runDBIO = runStdoutLoggingT . withPostgresqlConn "dbname=test-db" . runSqlConn