Depending on what your goal is, there are different approaches to querying the database. Some commands query based on a numeric ID, while others will filter. Queries also differ in the number of results they return: some lookups should return no more than one result (if the lookup key is unique) while others can return many results.
Persistent therefore provides a few different query functions. As usual, we try to encode
as many invariants in the types as possible. For example, a query that can return only 0
or 1 results will use a
Maybe wrapper, whereas a query returning many
results will return a list.
The simplest query you can perform in Persistent is getting based on an ID. Since this
value may or may not exist, its return type is wrapped in a
Example 10-2. Using get
"Just kidding, not really there"
This can be very useful for sites that provide URLs like /person/5. However, in such a case, we don’t usually care about the
Maybe wrapper, and just want the value, returning a 404 message
if it is not found. Fortunately, the
helps us out here. We’ll go into more details when we see integration with Yesod.
getBy is almost identical to
get, except it takes a
uniqueness constraint instead of an ID it takes a Unique value.
Example 10-3. Using getBy