0Pricing
Scala for Backend Engineering & Functional Programming · Lesson

Composing Transactions

Combine effects safely.

ConnectionIO Is a Monad

The real power of Doobie is that ConnectionIO is a monad. You combine many statements into one larger program using flatMap or a for-comprehension.

Everything you sequence this way runs on the same connection inside one transaction.

import doobie.implicits._

val program: ConnectionIO[Long] =
  for {
    id <- insertUser("Ada")
    _  <- insertProfile(id)
  } yield id

One Transaction per transact

No matter how many statements you compose, the whole ConnectionIO becomes a single transaction when you call .transact.

If any step fails, the Transactor's strategy rolls back everything; if all succeed, it commits once at the end.

val io: IO[Long] = program.transact(xa)

All lessons in this course

  1. Connecting with a Transactor
  2. Running Queries
  3. Inserts and Updates
  4. Composing Transactions
← Back to Scala for Backend Engineering & Functional Programming