15 Working with relational databases

 

This chapter covers

  • Relating Haskell data to database data
  • Writing and executing SQL queries
  • Structuring programs that need access to databases

Accessing a database is an important part of any backend program. In this chapter, we’ll look at several approaches to access relational databases in Haskell. As usual, we’ll focus on Haskell features that make programming with databases safe. This includes type checking for values we send or receive from a database. Although NoSQL databases are also popular within the Haskell community, I’ve decided not to mention them in this book. The main reason behind this decision is that the corresponding libraries suggest a rather straightforward approach to communicate with databases and don’t rely on any of the sophisticated Haskell features.

Just as in other programming languages, Haskell database interfaces are extremely diverse. With some of them, we merely construct queries and run them against a database. With more sophisticated interfaces, we can avoid writing queries and do regular programming instead.

Although many database access packages are able to work with different databases, in this chapter, we’ll use one particular database, namely PostgreSQL, which is widely used with Haskell software in industry.

The following is a list of questions we have to answer when we want to access any database with any package:

15.1 Setting up an example

15.1.1 Sample database

15.1.2 Sample queries

15.1.3 Data representation in Haskell

15.2 Haskell database connectivity

15.2.1 Connecting to a database

15.2.2 Relating Haskell data types to database types

15.2.3 Constructing and executing SELECT queries

15.2.4 Manipulating data in a database

15.2.5 Solving tasks by issuing many queries

15.3 The postgresql-simple library

15.3.1 Connecting to a database

15.3.2 Relating Haskell data types to database types

15.3.3 Executing queries