What is the best way to interact with a database using Haskell? I'm accustomed to using some sort of ORM (Django's ORM, hibernate, etc.) and something similar would be nice when creating apps with HAppS.
Edit: I'd like to be free to choose from Postgresql MySql and SQLite as far as the actual databases go.
The library I have in mind is not an ORM, but it may still do what you want.
If you want something that makes your database accesses safe while integrating things into your program nicely then try out HaskellDB. It basically looks at your schema, generates some data structures, and then gives you type safe ways to query. It's been around for quite a while and the community opinion is that it's good and stable.
To use it, you'll need some underlying Haskell DB library like HSQL.
Good luck!
The reason that ORM libraries exist is that there is relative big difference between Objects in C# or Java and what you store in a database. This is not so much an issue in Haskell because:
Persistent is rather nice to use, and lets you rely on type inference to determine the table your query relates to. For example, if I have the following in my "models" file:
User
name Text
age Int
Login
user UserId
login Text
passwd Text
Then I could do this:
Just (Entity uid _) <- selectFirst [ UserName ==. "exampleUser" ] []
Just (Entity lid Login {..}) <- selectFirst [ LoginUser ==. uid ] []
And it would know which tables I meant. Of course, you probably don't want to be writing partial code like this, but I wanted to emphasize just the queries.
I personally used only Database.HDBC which is recommended by "Real World Haskell": http://book.realworldhaskell.org/read/using-databases.html
But I agree that it definitely makes sense to use a higher-level DB access layer, and I'll probably try to move to such a model for future projects. On this topic, I found this post from 2012 which provides a history and comparison of such solutions for Haskell: http://www.yesodweb.com/blog/2012/03/history-of-persistence
From it, I gather that Persistent (documentation) and Groundhog (some documentation, examples) are the most promising libraries in this area. Both libraries support the databases you mention; for Groundhog it's not written in this post but in this announcement you can see that it supports exactly the DBs you are interested in.
Also note this thread on Haskell-beginners in which Esqueletto is mentioned as a better choice for update operations.
Note that Persistent ships with Yesod and as such may have a greater following.
I actually very much like the approach of HAppS (HAppS-State) which allows you to forget about going through the marshalling/unmarshalling cludge of ORM and let's you simply use Haskell's data types.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With