Haskell has no ORM monoculture. A Yesod app reaches for persistent, a data-heavy service picks beam, and a team that wants SQL to stay SQL writes hasql. All three are healthy in 2026, all three talk to Postgres, and none of them is interchangeable with the others.

The choice matters more than in Ruby or Elixir, because Haskell makes the abstraction boundary visible in the type system. With persistent, your schema becomes types via Template Haskell. With beam, your tables become a typed AST that you compose. With hasql, your SQL stays a string and only the encoder and decoder are typed. That single decision determines your compile times, your migration story, and how painful the first schema change after launch will be.

TL;DR: Quick Verdict

  • Pick persistent when you are building a Yesod/Yesod-adjacent app or want migrations generated from your Haskell types. Schema-first, one source of truth, lowest ceremony.
  • Pick beam when queries are the product: dashboards, filters, joins that vary at runtime, and you want the compiler to verify them without writing SQL strings.
  • Pick hasql when your team writes SQL deliberately and wants only two things from Haskell: safe parameter binding and typed decoding. Lowest runtime overhead, highest SQL fluency required.

If you are choosing a web framework at the same time, the Haskell web framework comparison of Yesod, Scotty and Servant covers which of these data layers each framework assumes by default.

persistent vs beam vs hasql at a Glance

Dimensionpersistentbeamhasql
GitHub stars486638554
Last commit2026-06-292026-11-192026-11-26
Schema defined asHaskell types + TH spliceHaskell table typesExternal SQL migrations
Query styleTyped DSL (selectList, filter_)Composable typed ASTSQL strings + typed codecs
MigrationsAuto-generated from typesbeam-migrate (separate package)Yours to write
Compile-time costHigh (TH per model)High (instance derivation)Low
Raw SQL escape hatchrawSqlLimited by designIt is raw SQL
Backend supportSQLite, Postgres, MySQL, MongoDBPostgres, SQLite, FirebirdPostgres, plus community drivers
Best fitCRUD apps, Yesod, fast iterationComplex dynamic queriesPerformance-sensitive services

Which One Fits Your Project?

Use caseRecommendationWhy
Internal admin tool with 20 tablespersistentSchema and migrations from one definition, no SQL to maintain
Analytics API with user-composed filtersbeamQuery fragments compose; the compiler checks the join graph
High-throughput ingest or read pathhasqlMinimal allocation, prepared statements, explicit control
Existing database you cannot ownhasql (or beam read-only)No TH-generated schema to keep in sync
Team new to HaskellpersistentBest documentation, largest body of examples
You need multi-backend portabilitypersistentSame models against SQLite in tests, Postgres in production

persistent: Schema as Types

persistent inverts the usual order. You declare entities in a quasi-quoted block, and Template Haskell generates record types, field lenses, and migration code from it.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
{-# LANGUAGE QuasiQuotes, TypeOperators, TemplateHaskell, GADTs,
             FlexibleContexts, MultiParamTypeClasses, DerivingStrategies #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedStrings #-}

share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase|
Customer
  name         Text
  email        Text
  UniqueEmail  email
  deriving     Show Generic

Invoice
  number       Text
  amountCents  Int
  status       InvoiceStatus
  customerId   CustomerId
  createdAt    UTCTime default=now()
  UniqueNumber number
  deriving     Show Generic
|]

The generated code gives you Customer, Invoice, InvoiceId, and lenses such as invoiceAmountCents — all ordinary Haskell values that compose with everything else in your application.

1
2
3
4
5
6
7
8
9
insertInvoice :: MonadIO m => CustomerId -> Text -> Int -> ReaderT SqlBackend m (Key Invoice)
insertInvoice cid number cents = do
  now <- liftIO getCurrentTime
  insert $ Invoice number cents StatusDraft cid now
  where
    status = StatusDraft

openInvoices :: MonadIO m => ReaderT SqlBackend m [Entity Invoice]
openInvoices = selectList [InvoiceStatus ==. StatusOpen] [Desc InvoiceCreatedAt, LimitTo 100]

Migrations come from the same definition:

1
2
3
4
main :: IO ()
main = do
  runStderrLoggingT $ withPostgresqlConn connStr $ \backend ->
    runReaderT (runMigration migrateAll) backend

That convenience has a sharp edge. runMigration is fine in development and dangerous in production: it will happily drop columns it no longer recognises. The production pattern is to run runMigrationSilent in a dry-run mode, capture the SQL, review it, and apply it through your normal migration pipeline — never let the app mutate schema at boot.

The other cost is compile time. Every entity added to the share block re-runs Template Haskell for the whole module; past roughly 40 entities on a mid-range laptop, full builds climb into minutes. The standard mitigation is to split entity definitions across modules and re-export from one umbrella module.

beam: Queries as a Typed AST

beam treats SQL as an algebra. Tables are types, columns are fields, and queries are expressions the compiler type-checks — including join conditions and nullability.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
{-# LANGUAGE DeriveAnyClass, DeriveGeneric, StandaloneDeriving, TypeFamilies #-}

data CustomerT f = Customer
  { customerId    :: C f Int32
  , customerName  :: C f Text
  , customerEmail :: C f Text
  } deriving (Generic, Beamable)

data InvoiceT f = Invoice
  { invoiceId          :: C f Int32
  , invoiceNumber      :: C f Text
  , invoiceAmountCents :: C f Int32
  , invoiceCustomerId  :: PrimaryKey CustomerT f
  } deriving (Generic, Beamable)

deriving instance Show (CustomerT Identity)
deriving instance Show (InvoiceT Identity)

instance Table CustomerT where
  data PrimaryKey CustomerT f = CustomerId (Columnar f Int32) deriving (Generic, Beamable)
  primaryKey = CustomerId . customerId

instance Table InvoiceT where
  data PrimaryKey InvoiceT f = InvoiceId (Columnar f Int32) deriving (Generic, Beamable)
  primaryKey = InvoiceId . invoiceId

Queries then compose like any other value, which is the whole point:

1
2
3
4
5
6
invoiceTotals :: Q Postgres BeamSql QExpr (Text, Int64)
invoiceTotals =
  aggregate_ (\(c, i) -> (customerName c, sum_ (invoiceAmountCents i))) $
    join_ invoices $ \i ->
      join_ customers $ \c ->
        where_ (invoiceCustomerId i == primaryKey c)

Because the query is a data structure, you can build it from runtime filters without string concatenation:

1
2
3
4
5
6
7
8
9
filteredInvoices :: Maybe Text -> Maybe Int32 -> Q Postgres BeamSql QExpr (Text, Int32)
filteredInvoices mStatus mMinCents =
  select $
    limit_ 200 $
      orderBy_ (desc_ . invoiceId) $
        filter_ (\i ->
          maybe (sqlExpr True) (\s -> invoiceNumber i `like_` (s <> "%")) mStatus
          && maybe (sqlExpr True) (\m -> invoiceAmountCents i >=. m) mMinCents)
          (all_ invoices)

Two things to budget for. First, beam’s type errors are notoriously verbose: a single mismatched column can produce a 60-line error mentioning three type families. Second, migrations live in beam-migrate, which builds a schema descriptor from your tables and diffs it — powerful, but a separate mental model from persistent’s single splice.

hasql: SQL Stays SQL

hasql makes no attempt to model your schema. A Statement pairs a SQL string with an encoder for parameters and a decoder for results; everything else — pool, transactions, retries — is composed around it.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
{-# LANGUAGE OverloadedStrings #-}

import Hasql.Statement (Statement(..))
import qualified Hasql.Encoders as E
import qualified Hasql.Decoders as D

openInvoices :: Statement (Int64) [(Int64, Text, Int32)]
openInvoices = Statement sql encoder decoder True
  where
    sql = "SELECT id, number, amount_cents FROM invoices WHERE status = $1 ORDER BY created_at DESC LIMIT 100"
    encoder = E.param $ E.nonNullable E.int8
    decoder = D.rowList $
      (,,) <$> D.column (D.nonNullable D.int8)
           <*> D.column (D.nonNullable D.text)
           <*> D.column (D.nonNullable D.int4)

Running it inside a session is explicit about transactions:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
import qualified Hasql.Session as Session
import qualified Hasql.Pool as Pool

markPaid :: Pool.Pool -> Int64 -> IO (Either Pool.UsageError ())
markPaid pool invoiceId =
  Pool.use pool $ Session.sql $ Session.statement invoiceId markPaidStmt

markPaidStmt :: Statement (Int64) ()
markPaidStmt = Statement
  "UPDATE invoices SET status = 'paid' WHERE id = $1"
  (E.param $ E.nonNullable E.int8)
  D.noResult
  True

Multi-statement transactions use Session.transaction:

1
2
3
4
5
transferCredit :: Pool.Pool -> Int64 -> Int64 -> Int32 -> IO (Either Pool.UsageError ())
transferCredit pool fromId toId cents =
  Pool.use pool $ Session.transaction
    Session.ReadWrite
    (Session.statement (fromId, cents) debitStmt >> Session.statement (toId, cents) creditStmt)

What you trade away: schema drift is invisible to the compiler. If someone renames status to state, hasql compiles cleanly and fails at runtime. Tests must cover every statement — the type system protects your encoding, not your SQL. That is a real cost, and it is why teams that pick hasql usually pair it with a thin integration-test layer that runs every statement against a real Postgres.

What you gain: no Template Haskell, fast builds, predictable memory behaviour, and complete control over the generated SQL. On read-heavy services the reduction in allocation and interpretation overhead is measurable, and prepared statement caching is explicit rather than inferred.

Postgres for development

All three expect a real Postgres, and testing against anything else hides concurrency and JSONB behaviour:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
services:
  db:
    image: postgres:17-alpine
    environment:
      POSTGRES_USER: haskell
      POSTGRES_PASSWORD: haskell
      POSTGRES_DB: haskell_dev
    ports:
      - "5432:5432"
    volumes:
      - pgdata:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U haskell"]
      interval: 5s
      retries: 10
volumes:
  pgdata:

Connection pooling is a separate decision from the library choice. persistent typically runs over resource-pool; hasql has hasql-pool. Both are fork-safe only if you create the pool after forking, or rely on the pool’s internal resource management — the classic Haskell service outage is a pool created in main before forkIO, sharing sockets across capabilities.

Common Traps

Trap 1 — runMigration in production. It applies destructive changes silently. Generate, review, apply.

Trap 2 — Duplicate field names across entity modules. persistent’s generated lenses collide unless you enable DuplicateRecordFields or split into separate modules with explicit exports. This produces confusing “ambiguous occurrence” errors that look like a TH bug.

Trap 3 — Assuming the compiler validates SQL in hasql. It does not. Every statement needs an integration test.

Trap 4 — Composing beam queries with where_ after aggregate_. Order matters; the type error will not tell you that in plain language. Build small query fragments as top-level definitions so the errors point at a short expression.

Trap 5 — Ignoring transaction isolation levels. All three default to Postgres’ READ COMMITTED. If you implement invariants in application code (balances, inventory counts), you need SERIALIZABLE or explicit row locking — the library will not do it for you.

If you are wiring effects or serialization around the data layer, our Haskell effect systems comparison and Haskell serialization guide covering aeson, cassava, cborg and serialise cover the two layers that most often collide with database code in real services.

FAQ

Is persistent still maintained in 2026? Yes. It tracks GHC releases and remains the default data layer for Yesod. Its commit cadence is slower than beam’s, which reflects stability rather than abandonment.

Can I use beam without beam-migrate? Yes. beam-postgres works with hand-written migrations; beam-migrate only adds schema diffing and verification. Many teams start without it and adopt it once the schema stabilises.

Which is fastest at runtime? hasql generally wins on read-heavy workloads because it skips Template Haskell-generated indirection and gives explicit control over prepared statements. For typical CRUD the difference is smaller than the cost of a badly chosen index.

Does hasql support transactions and pooling? Yes — Session.transaction for transactions, hasql-pool for pooling. Neither is automatic; you compose them.

How do these handle JSON columns? persistent supports Value fields with PersistJSON; beam models JSONB as a PgJSONB column you can query with Postgres operators; hasql decodes it with Hasql.Decoders.jsonb or as raw ByteString you parse yourself.

What about SQLite for tests? persistent and beam both support SQLite, which is fine for fast unit tests — but keep at least one Postgres-backed suite, or you will ship ON CONFLICT and concurrency bugs your tests cannot see.


💰 想测试你的市场判断力?我用 Polymarket 做预测市场交易——这是全球最大的预测市场平台,从大选结果到技术监管时间线,什么都可以押注。和赌博不同,这是真正的信息市场:你懂的信息越多,胜率越高。我靠预测技术相关事件的走向已经赚了不少。用我的邀请链接注册:Polymarket.com