Connecting with a Transactor
Set up database access.
Connecting with a Transactor is a free Scala for Backend Engineering & Functional Programming lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Scala for Backend Engineering & Functional Programming learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What Is a Transactor?
Doobie is a pure functional JDBC layer for Scala. A Transactor[F] is the bridge between Doobie's pure programs and a real database connection.
A Transactor knows how to acquire a JDBC Connection, run your program inside a transaction, and release resources safely.
It is parameterized by an effect type F[_] such as cats.effect.IO.
import doobie._
import cats.effect.IO
val xa: Transactor[IO] = ???The ConnectionIO Program
Doobie queries are values of type ConnectionIO[A]. They describe a computation that needs a JDBC connection but do not run yet.
You build these programs purely, then hand them to a Transactor to execute them. Nothing touches the database until you run it.
import doobie.implicits._
val program: ConnectionIO[Int] =
sql"select 42".query[Int].uniqueDriverManagerTransactor
The simplest Transactor is Transactor.fromDriverManager. It opens a brand new connection for every transaction using JDBC's DriverManager.
It needs the driver class name, JDBC URL, username, and password. It is fine for tests and scripts but has no connection pooling.
val xa = Transactor.fromDriverManager[IO](
driver = "org.postgresql.Driver",
url = "jdbc:postgresql://localhost:5432/app",
user = "postgres",
password = "secret",
logHandler = None
)Running a Program
To execute a ConnectionIO you call .transact(xa). This yields an F[A], here an IO[A].
The Transactor wraps the program in a transaction: it commits on success and rolls back on failure, releasing the connection either way.
import doobie.implicits._
val result: IO[Int] =
sql"select 42".query[Int].unique.transact(xa)Pooling with HikariCP
For production you want a connection pool. Doobie ships HikariTransactor, backed by HikariCP.
It is created as a Resource so the pool is shut down cleanly. You also pass an execution context for blocking JDBC operations.
import doobie.hikari.HikariTransactor
import cats.effect.IO
val xaRes: Resource[IO, HikariTransactor[IO]] =
HikariTransactor.newHikariTransactor[IO](
"org.postgresql.Driver",
"jdbc:postgresql://localhost/app",
"postgres", "secret",
connectEC
)Why a Resource?
A pooled Transactor owns long-lived state: open connections and background threads. Resource[F, A] guarantees acquisition and release are paired even on errors or cancellation.
You typically build the Transactor once at startup and reuse it for the whole application's lifetime.
xaRes.use { xa =>
program.transact(xa)
}The connectEC Pool
HikariCP needs an ExecutionContext to await connections from the pool. Doobie provides ExecutionContexts.fixedThreadPool for this, itself a Resource.
Keeping this separate from your compute pool prevents blocking connection acquisition from starving CPU-bound work.
import doobie.util.ExecutionContexts
val poolRes =
for {
ec <- ExecutionContexts.fixedThreadPool[IO](8)
xa <- HikariTransactor.newHikariTransactor[IO](
"org.postgresql.Driver", url, user, pass, ec)
} yield xaConfiguring an Existing DataSource
If you already have a configured javax.sql.DataSource (e.g. a tuned Hikari instance), wrap it directly with Transactor.fromDataSource.
This is common when a framework manages the pool and you only want Doobie to use it.
val xa = Transactor.fromDataSource[IO](
dataSource = myDataSource,
connectEC = connectEC
)Smoke-Testing the Connection
A simple health check is to run select 1 through the Transactor. If it returns, your driver, URL, and credentials are all working.
This is a good first step before wiring up real queries.
val check: IO[Int] =
sql"select 1".query[Int].unique.transact(xa)
// check.unsafeRunSync() == 1Transactor Internals: Strategy
A Transactor is built from interpreters and a Strategy. The Strategy controls what happens around each transaction: before, after, oops (on error), and always.
The default strategy sets auto-commit off, commits after success, rolls back on error, and always closes the connection.
import doobie.util.transactor.Strategy
val noCommit = xa.copy(
strategy0 = Strategy.default.copy(after = doobie.free.connection.unit)
)Logging and Observability
Doobie can log every statement, its arguments, and timing. Modern versions attach a LogHandler[F] per query rather than per Transactor.
This is invaluable for spotting slow queries and verifying parameter binding in production.
import doobie.util.log._
val handler: LogHandler[IO] = (ev: LogEvent) =>
IO.println(ev.sql)Quick Check
Test your understanding of Transactors.
Recap
A Transactor[F] connects pure ConnectionIO programs to a real database. fromDriverManager suits tests; HikariTransactor and fromDataSource suit production via pooling.
Build pooled Transactors as a Resource, run programs with .transact(xa), and let the default Strategy handle commit, rollback, and cleanup.
Frequently asked questions
Is the “Connecting with a Transactor” lesson free?
Yes — the full text of “Connecting with a Transactor” is free to read here on the web, and the Scala for Backend Engineering & Functional Programming course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Scala for Backend Engineering & Functional Programming course, upgrade to CoddyKit PRO.
What will I learn in “Connecting with a Transactor”?
Set up database access. You practise Scala for Backend Engineering & Functional Programming with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Scala for Backend Engineering & Functional Programming?
No prior experience is required. Scala for Backend Engineering & Functional Programming on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Connecting with a Transactor” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Scala for Backend Engineering & Functional Programming lesson?
Yes. Every Scala for Backend Engineering & Functional Programming lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Connecting with a Transactor
- Running Queries
- Inserts and Updates
- Composing Transactions