0Pricing
Scala for Backend Engineering & Functional Programming · Ders

Transactor ile Bağlanma

Veritabanı erişimini kurun.

Transactor ile Bağlanma, CoddyKit'te ücretsiz bir Scala for Backend Engineering & Functional Programming dersidir. Bu, 4 dersinin 1. dersidir. Aşağıdan dersin tamamını ücretsiz okuyabilir, sonra tarayıcıda yerleşik kod editörü ve 7/24 yapay zeka koçu ile uygulamalı olarak pratik yapabilirsin. Bu, Scala for Backend Engineering & Functional Programming öğrenme yolunun bir parçasıdır ve ilerlemeniz web ve CoddyKit uygulaması arasında senkronize olur. Scala for Backend Engineering & Functional Programming kursu toplamda 4 dersten oluşur.

Bu dersin bazı bölümleri henüz çevrilmemiş olup İngilizce olarak gösterilmektedir.

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].unique

DriverManagerTransactor

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 xa

Configuring 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() == 1

Transactor 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.

Sıkça Sorulan Sorular

“Transactor ile Bağlanma” dersi ücretsiz mi?

Evet — “Transactor ile Bağlanma” dersin tüm metni burada web'de ücretsiz olarak okunabilir. Etkileşimli olarak pratik yapmak (yerleşik kod editörü ve 7/24 yapay zeka koçu) ve Scala for Backend Engineering & Functional Programming kursunun geri kalanını açmak için CoddyKit PRO'ya yükselt. Scala for Backend Engineering & Functional Programming kursu toplamda 4 dersten oluşur.

“Transactor ile Bağlanma” dersinde ne öğreneceğim?

Veritabanı erişimini kurun. Scala for Backend Engineering & Functional Programming ile uygulamalı kodu tarayıcıda doğrudan çalıştırarak pratik yaparsın ve 7/24 yapay zeka koçu dersi çalışırken sorularını yanıtlar.

Scala for Backend Engineering & Functional Programming öğrenmeye başlamak için deneyim gerekli mi?

Önceden deneyim gerekmez. CoddyKit'te Scala for Backend Engineering & Functional Programming, başlangıçtan ileri seviyeye kadar yapılandırıldığı için buradan başlayabilir veya başından başlayıp kendi hızında ilerleme yapabilirsin. Bu, 4 dersinin 1. dersidir.

“Transactor ile Bağlanma” dersi ne kadar sürer?

Çoğu CoddyKit dersi yaklaşık 5–10 dakika sürer. Her biri kısa ve etkileşimli olduğu için sabit ilerleme yaparsın ve web ile uygulama arasında tam olarak bıraktığın yerden devam edebilirsin.

Bu Scala for Backend Engineering & Functional Programming dersinde kod yazıp çalıştırabilir miyim?

Evet. Her Scala for Backend Engineering & Functional Programming dersi yerleşik bir kod editörü içerir, bu sayede tarayıcıda gerçek kod yazıp çalıştırabilir ve anlık yapay zeka geri bildirimi alırsın — yerel kurulum gerekli değildir.

Bu kursun tüm dersleri

  1. Transactor ile Bağlanma
  2. Sorguları Çalıştırma
  3. Ekleme ve Güncelleme
  4. İşlemleri Birleştirme
← Scala for Backend Engineering & Functional Programming Sayfasına Dön