Frage

How to, for example, insert a new User into a database using Yesod application's models? Or is there a better way?

I am dealing with scaffolded application. Now I created App instance and dont know how to perform requests using it.

: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'

What next?

War es hilfreich?

Lösung

If you just want to do Persistent queries in ghci you can do this without creating a Yesod application. Unfortunately doing this is differs quite a bit depending on the specific back end you want to use.

For 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))

For 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

Andere Tipps

The scaffolding provides (at least with yesod-bin 1.4.5) a function db in Application.hs which you can use:

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

It looks like the accepted answer is pretty old. Here is an update for running persistent queries in IO with the postgresql backend.

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
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top