Haskell: HDBC, connection status, and possibly pool

Say I have a simple application that uses HDBC to interact with a database. It can be a quick application or a command line application. I would like that a general view of this is not a binding or anything concrete. A good example is chapter 22 of Real World Haskell.

So I would hide all my SQL related functions like connect, saveArticle, getArticle etc. in a separate DB.hs. All database functions take a connection descriptor as an argument.

Now, how would I initiate a connection once and put it in a state so that all these database functions use it without initiating the connection separately? Is it possible? Maybe I'm thinking wrong or with OO concepts, but ... I would like to β€œinitialize” my connection (for example, you would initialize the object in OO). I do not want each database function to create and close a new connection.

Do I need to create a pool and pass the pool to functions as an argument instead of a connection descriptor? What is the simplest example of this?

Is this a pool or connection descriptor, how can I put it in a state so that my functions just grab it if necessary and do not repeat β€œopen” and β€œclose” all the time? If so, how is this done correctly?

Do I need to create a pool and put it in a state, so the functions simply request a pool for connections from the global state? Again, the example will be really appreciated.

Thanks.

+6
source share
2 answers

You can take a look at the bos resource-pool library.

+1
source

There is no state or module state, so you need to find a different strategy. I highly recommend the reader monad, with environments that support a db connection. This will require several returns in some functions, but will be very durable.

The following is a simple pseudo-haskell example.

type AppState = AppState { dbcon :: DatabaseConnection } type App = ReaderT AppState IO main = do db <- makeNewDbConnection runReaderT getDbTableCount $ AppState db getDbTableCount :: App Integer getDbTableCount = do (count:_) <- runDb "select count(*) from table;" return $ read count runDb :: String -> App [String] runDb req = do con <- asks dbcon return $ dbQuery con req 
+2
source

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


All Articles