In this lecture Alexandr Kurilin shows how to work with the database in Haskell. He shows how the Persistent and Esqueleto libraries create typesafe queries that are checked by the compiler for compatibility with the rest of your code. This builds on top of the example from Lecture 1.

Download Video: (HD / SD).

Summary

Quick recap of last lecture

(Sorry, slight video glitch for the first two minutes)

Today is all about databases, we’ll save the data that we parsed last time into PostgreSQL

How to review db libraries and decide which to use

Ultimately this lecture uses Persistent with Esqueleto on top It has been well maintained for a long time It has solid documentation Copy and paste examples! Supports many dbs Adds type safety to the SQL boundary of our app Does basic schema migrations automatically

Discussion of Persistent and its origins in the Yesod ecosystem

How to define data entities with the Persistent template Haskell DSL Explanation of how template Haskell works, and an examination of the actual code Persistent generates Persistent requires some GHC extensions

Migrations Persistent scans the db schema to find how it must change it It automatically does transformations as long as they are safe, meaning can’t irreversibly change data

Column type declarations, along with some auto-created ones for artificial keys

GHC build options to reveal template splices “This splice goes on pretty much forever…”

Writing tests for Persistent code is tricky but Yesod offers some hspec helpers

Analysis and demo of a program to parse a file and save the results through Persistent How to inspect a Persistent “Entity” How to create objects, turn them into Entities and insert them in a forM_ “loop” Also possible to bulk insert directly

How to use selectList to retrieve values. Notice it infers which table to query based on the surrounding types.

to retrieve values. Notice it infers which table to query based on the surrounding types. Updates and deletes

Persistent can only query one table at a time. Quite a limitation…but there’s a way around it You could use raw SQL but you lose the type safety 95% of all SQL errors at Front Row Education came from being lazy and writing raw SQL You can improve things a little by asking Persistent for the SQL names of things, but even that is not so good Enter Esqueleto, the type safe DSL to build SQL (An alternative is Groundhog)

An example of building an inner join with Esqueleto

It’s also composable – you can build queries out of others. Careful not to get too crazy with it or it will distance you from the queries that actually get generated.

Recommended reads Template Haskell Persistent



Related Posts