How to query a database inside makeApplication function

I am trying to unlock a non-web service in my Yesod application and it needs to do some interaction with the database. From this publication, I decided to put the service in makeApplication. I would like my service to return some value when certain things happen and store it in a database. So I am wondering what is the best way to do this?

How to run runDB $ insert $ Stuff (T.pack "stuff") inside the makeApplication function?

EDIT: As Michael suggested, I made the following helper function inside Application.hs

 runDBIO conf foundation f = do dbconf <- withYamlEnvironment "config/postgresql.yml" (appEnv conf) Database.Persist.loadConfig >>= Database.Persist.applyEnv p <- Database.Persist.createPoolConfig (dbconf :: Settings.PersistConf) logger <- mkLogger True stdout runLoggingT (Database.Persist.runPool dbconf fp) (messageLoggerSource foundation logger) 

And in makeApplication, I used it like this:

 runDBIO conf foundation $ do dbid <- insert $ Stuff (T.pack "some random stuff") string <- get dbid liftIO $ print string 

However, I get this compilation error:

 No instance for (resourcet-0.4.5:Control.Monad.Trans.Resource.MonadResource IO) arising from a use of 'insert' 

Did I enter the wrong type for runPool? Or do I need to make an instance for insert ? I do not understand why runMigration migrateAll works, but insert does not work.

+4
source share
1 answer

You can see a demonstration of how to start the database action in the IO monad in the forest level itself . Essentially, you need to provide two pieces of information: how to register requests and the database connection pool. You can convert this code to a helper function (for example, runDBIO ) and then run runDBIO $ insert $ Stuff $ T.pack "stuff" .

+2
source

Source: https://habr.com/ru/post/1480433/


All Articles