Skip to main content

Part 7: Store the Books in a Database

Our books service from part 4 keeps the books in a Ref, so they live only as long as the server process. Restart the server, and every book you added is gone. In this part, we store the books in a real database. We use H2, a database written in Java that runs inside our own program and saves its data to a file, so there is nothing else to install or start.

Back in part 4, we wrote the handlers against the BookRepo trait rather than against the Ref, so that we could swap the storage later. This is that moment. By the end of this part, the routes are exactly the same as in part 5; only the BookRepo implementation and the layers we provide are new.

This part uses three pieces that work together:

  • JDBC (Java Database Connectivity) is the standard Java API for talking to SQL databases. We send SQL text and read rows back.
  • A connection pool keeps a few database connections open and lends them out to requests, because opening a new connection for every request is slow.
  • ZIO Config reads the database settings (where the database is, which user to log in as) from the environment, so the same program can point at a different database without code changes.

1. Add the H2 Dependency​

H2 contains both the database itself and its JDBC driver. Add this line to build.sbt:

// H2: an embedded SQL database and its JDBC driver
libraryDependencies += "com.h2database" % "h2" % "2.5.252"

Notice the single % after "com.h2database": H2 is a Java library, so it has no Scala version in its name. JDBC itself is part of the JDK, so this is the only new dependency.

2. Read the Database Settings from Config​

A database needs a few settings: its JDBC URL, which says which database to open, a user name and a password. We describe these settings with ZIO's built-in Config type, the same way we describe a JSON body with a Schema. Add the imports at the top of BooksApp.scala, then a case class and its companion object below BookRepo:

import java.sql.{PreparedStatement, ResultSet, Statement}
import javax.sql.DataSource

import scala.util.Using

import zio._
import zio.http._
import zio.schema.{DeriveSchema, Schema}

import org.h2.jdbcx.JdbcConnectionPool

// Book, NewBook, ApiError, BookNotFound and BookRepo are unchanged from part 5.
final case class Book(id: Int, title: String, author: String, year: Int)
object Book { implicit val schema: Schema[Book] = DeriveSchema.gen[Book] }
final case class NewBook(title: String, author: String, year: Int)
object NewBook { implicit val schema: Schema[NewBook] = DeriveSchema.gen[NewBook] }
final case class ApiError(message: String)
object ApiError { implicit val schema: Schema[ApiError] = DeriveSchema.gen[ApiError] }
final case class BookNotFound(id: Int)

trait BookRepo {
def all: UIO[List[Book]]
def get(id: Int): IO[BookNotFound, Book]
def add(newBook: NewBook): UIO[Book]
}

final case class DbConfig(url: String, user: String, password: Config.Secret)

object DbConfig {

val config: Config[DbConfig] =
(Config.string("url").withDefault("jdbc:h2:./books") ++
Config.string("user").withDefault("sa") ++
Config.secret("password").withDefault(Config.Secret(""))).nested("db").map { case (url, user, password) =>
DbConfig(url, user, password)
}

val layer: Layer[Config.Error, DbConfig] =
ZLayer.fromZIO(ZIO.config(config))
}

Line by line:

  • Config.string("url") describes one setting, a string named url. Config#withDefault gives it a value to use when the setting is missing, so the app runs without any setup.
  • jdbc:h2:./books is a JDBC URL: jdbc:h2: picks the H2 driver, and ./books tells H2 to keep the database in a file named books.mv.db in the folder where the server starts.
  • Config.secret("password") reads a Config.Secret instead of a String. A secret prints as Secret(<redacted>), so the password never ends up in a log by accident.
  • ++ combines the three settings into one Config of a tuple, and Config#nested("db") places all of them under the name db.
  • Config#map turns the tuple into our DbConfig case class.
  • ZIO.config(config) loads the settings, and ZLayer.fromZIO turns that into a layer that produces a DbConfig. It fails with a Config.Error when the settings cannot be read.

By default, ZIO.config looks for each setting first in the environment variables, then in the JVM system properties. The setting url nested under db is read from the environment variable DB_URL or the system property db.url. We use this in section 7.

3. Open a Connection Pool with a Scoped Layer​

A connection pool is a resource: we open it when the app starts, and we must close it when the app stops, so that H2 can finish writing its file. ZIO models this with ZIO.acquireRelease, which pairs an effect that opens a resource with an effect that closes it. ZLayer.scoped turns such a resource into a layer that stays open while the app uses it. Add this object below DbConfig:

object ConnectionPool {

val layer: RLayer[DbConfig, DataSource] =
ZLayer.scoped {
for {
config <- ZIO.service[DbConfig]
pool <- ZIO.acquireRelease(
ZIO.attemptBlocking(JdbcConnectionPool.create(config.url, config.user, config.password.stringValue)),
)(pool => ZIO.succeed(pool.dispose()))
} yield pool
}
}

Line by line:

  • RLayer[DbConfig, DataSource] is the type of a layer that needs a DbConfig, may fail with a Throwable, and produces a DataSource. DataSource is JDBC's standard interface for "something that hands out connections"; the rest of our code depends only on it, not on H2.
  • ZIO.service[DbConfig] takes the DbConfig that DbConfig.layer built.
  • JdbcConnectionPool.create(...) is H2's own small connection pool. Config.Secret#stringValue reads the password out of its secret wrapper.
  • ZIO.attemptBlocking runs code that may block a thread, such as file or network access, on ZIO's separate pool of threads for blocking work, and turns any exception it throws into a failure.
  • pool => ZIO.succeed(pool.dispose()) is the release step: it closes every connection in the pool.

Because the layer is scoped, ZIO runs the release step when the program shuts down, even when it stops because of an error or a Ctrl+C. We never have to remember to close the pool ourselves.

4. Implement BookRepo with JDBC​

Now we write a second implementation of BookRepo, next to InMemoryBookRepo, that runs SQL against the DataSource. Every method follows the same steps: borrow a connection, prepare an SQL statement, run it, read the result, and give the connection back. We put those shared steps in one helper, withStatement, at the bottom of the class:

final case class JdbcBookRepo(dataSource: DataSource) extends BookRepo {

def all: UIO[List[Book]] =
withStatement("SELECT id, title, author, published_year FROM books ORDER BY id") { statement =>
readBooks(statement.executeQuery())
}

def get(id: Int): IO[BookNotFound, Book] =
withStatement("SELECT id, title, author, published_year FROM books WHERE id = ?") { statement =>
statement.setInt(1, id)
readBooks(statement.executeQuery()).headOption
}.someOrFail(BookNotFound(id))

def add(newBook: NewBook): UIO[Book] =
withStatement("INSERT INTO books (title, author, published_year) VALUES (?, ?, ?)") { statement =>
statement.setString(1, newBook.title)
statement.setString(2, newBook.author)
statement.setInt(3, newBook.year)
statement.executeUpdate()
val keys = statement.getGeneratedKeys()
keys.next()
Book(keys.getInt(1), newBook.title, newBook.author, newBook.year)
}

def createTable: UIO[Unit] =
withStatement(
"CREATE TABLE IF NOT EXISTS books (" +
"id INT AUTO_INCREMENT PRIMARY KEY, title VARCHAR(255) NOT NULL, " +
"author VARCHAR(255) NOT NULL, published_year INT NOT NULL)",
)(_.execute()).unit

private def withStatement[A](sql: String)(use: PreparedStatement => A): UIO[A] =
ZIO.attemptBlocking {
Using.resource(dataSource.getConnection()) { connection =>
Using.resource(connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS))(use)
}
}.orDie

private def readBooks(rows: ResultSet): List[Book] = {
val books = List.newBuilder[Book]
while (rows.next())
books += Book(rows.getInt("id"), rows.getString("title"), rows.getString("author"), rows.getInt("published_year"))
books.result()
}
}

Let's start with the helper, because every other method uses it:

  • dataSource.getConnection() borrows a connection from the pool, and connection.prepareStatement(sql, ...) prepares one SQL statement on it.
  • Using.resource(...), from the Scala standard library, closes what it opened when the code inside finishes, even when that code throws. Closing a pooled connection hands it back to the pool.
  • Statement.RETURN_GENERATED_KEYS asks JDBC to keep the ids the database creates for new rows, which JdbcBookRepo#add reads.
  • ZIO.attemptBlocking runs the whole JDBC call on the blocking thread pool, as in section 3, because JDBC blocks the thread while it waits for the database.
  • ZIO#orDie turns a database failure into a defect, ZIO's name for an unexpected error. Our trait's methods have no room for database errors, and a client cannot fix them by changing its request, so ZIO HTTP answers a defect with 500 Internal Server Error and logs the exception.

And the methods:

  • JdbcBookRepo#all runs a SELECT and turns the rows into books with readBooks, which walks the ResultSet row by row with rows.next().
  • JdbcBookRepo#get puts the id into the ? placeholder with statement.setInt(1, id). A placeholder sends the value separately from the SQL text, so a value can never change the meaning of the query. ZIO#someOrFail turns "no row" (None) into our BookNotFound failure from part 5.
  • JdbcBookRepo#add fills the three placeholders, runs the INSERT, and reads the new id with statement.getGeneratedKeys(). The database picks the id (AUTO_INCREMENT), so two requests that add a book at the same moment get different ids, just as Ref#modify guaranteed in part 4.
  • JdbcBookRepo#createTable creates the books table if it does not exist yet. The column for the year is called published_year, because YEAR is a keyword in H2's SQL and cannot name a column.

5. Create the Table and the First Books​

Before the first request arrives, the database needs its table, and a new database should start with our three books. A layer is the right place for this setup work, because ZIO builds it once, before the server starts. Add a companion object for JdbcBookRepo:

object JdbcBookRepo {

val initialBooks: List[NewBook] =
List(
NewBook("Dune", "Frank Herbert", 1965),
NewBook("Neuromancer", "William Gibson", 1984),
NewBook("Count Zero", "William Gibson", 1986),
)

val layer: URLayer[DataSource, BookRepo] =
ZLayer.fromZIO {
for {
dataSource <- ZIO.service[DataSource]
repo = JdbcBookRepo(dataSource)
_ <- repo.createTable
books <- repo.all
_ <- ZIO.foreachDiscard(initialBooks)(repo.add).when(books.isEmpty)
} yield repo
}
}

The layer takes the DataSource from the pool layer, creates the table, and adds the three books only when the table is empty, which is the case the first time the app runs. Because JdbcBookRepo#add lets the database pick the ids, the three books get the ids 1, 2 and 3, as before. The type URLayer[DataSource, BookRepo] says the layer needs a DataSource, cannot fail, and produces a BookRepo.

InMemoryBookRepo is no longer used, so you can delete it.

6. Provide the New Layers​

Here is the payoff of the BookRepo trait: the routes do not change at all. They still have the type Routes[BookRepo, Response], and they do not know that a database now sits behind BookRepo. The only line that changes is run, where we replace InMemoryBookRepo.layer with our three new layers:

def run =
Server.serve(routes).provide(Server.default, JdbcBookRepo.layer, ConnectionPool.layer, DbConfig.layer)

The layers form a chain: DbConfig.layer needs nothing and produces a DbConfig; ConnectionPool.layer turns that DbConfig into a DataSource; JdbcBookRepo.layer turns the DataSource into the BookRepo our routes need. We list the layers in any order, and ZIO#provide works out the order to build them in from their types:

DbConfig.layer ──► ConnectionPool.layer ──► JdbcBookRepo.layer ──► routes
(DbConfig) (DataSource) (BookRepo)

When the program stops, ZIO#provide closes the layers in the reverse order, which runs the release step of ConnectionPool.layer and closes the pool.

7. Run It​

Start the server with sbt run, then add a book:

curl -i -X POST localhost:8080/books -d '{"title":"Snow Crash","author":"Neal Stephenson","year":1992}'

The answer is the same as in part 4:

HTTP/1.1 201 Created
content-type: application/json
content-length: 68

{"id":4,"title":"Snow Crash","author":"Neal Stephenson","year":1992}

Notice the new file books.mv.db in the project folder: that is the database. Now stop the server with Ctrl+C, start it again with sbt run, and ask for the new book:

curl localhost:8080/books/4

This time, the book survived the restart:

{"id":4,"title":"Snow Crash","author":"Neal Stephenson","year":1992}

Finally, let's point the app at a different database without touching the code. Stop the server, and start it again with the DB_URL environment variable set:

DB_URL=jdbc:h2:./other-books sbt run

GET /books now lists only the three initial books, because the app opened a new, empty database file, other-books.mv.db, and added them to it:

[{"id":1,"title":"Dune","author":"Frank Herbert","year":1965},{"id":2,"title":"Neuromancer","author":"William Gibson","year":1984},{"id":3,"title":"Count Zero","author":"William Gibson","year":1986}]

8. Test Against an In-Memory Database​

Our tests from part 6 still provide InMemoryBookRepo.layer. Let's run them against the real JDBC code instead. The only thing a test needs to change is the database it opens: H2 also has in-memory databases, whose URL starts with jdbc:h2:mem:. An in-memory database disappears when the pool closes, so every test starts from an empty database and our layer adds the three books again.

Add a test layer for DbConfig to BooksAppSpec, and swap the layers in Spec#provide:

import java.util.UUID
import zio.test.{ZIOSpecDefault, assertTrue, suite, test}

object BooksAppSpec extends ZIOSpecDefault {

val testDbConfig: ULayer[DbConfig] =
ZLayer.fromZIO(
ZIO.succeed(DbConfig(s"jdbc:h2:mem:books-${UUID.randomUUID()}", "sa", Config.Secret(""))),
)

def spec =
suite("BooksApp with H2")(
test("GET /books/1 returns Dune") {
for {
response <- BooksApp.routes.runZIO(Request.get("/books/1"))
book <- response.body.asJson[Book]
} yield assertTrue(
response.status == Status.Ok,
book.title == "Dune",
)
},
// ...and the other three tests from part 6, unchanged
).provide(JdbcBookRepo.layer, ConnectionPool.layer, testDbConfig, Scope.default)
}

Line by line:

  • testDbConfig builds a DbConfig directly, instead of reading it from the environment, so the tests never touch the books.mv.db file.
  • UUID.randomUUID() gives every test its own database name. ZIO Test runs tests in parallel, and Spec#provide builds the layers once per test, so without unique names two tests could share one database.
  • Spec#provide lists the same database layers as run, with testDbConfig in place of DbConfig.layer.

Run the tests with sbt test. The same four tests now pass against H2 (the order of the lines may vary, because tests run in parallel):

+ BooksApp with H2
+ GET /books?limit=abc returns 400 Bad Request
+ POST /books saves a new book
+ GET /books/1 returns Dune
+ GET /books/42 returns 404 Not Found
4 tests passed. 0 tests failed. 0 tests ignored.
The complete BooksApp.scala at the end of part 7, with the database layers
zio-http-example-rest-api-tutorial/src/main/scala/example/restapi/part7/BooksApp.scala
//> using scala 2.13.18
//> using dep dev.zio::zio-http:3.12.0
//> using dep com.h2database:h2:2.5.252
// Run from this folder: scala-cli run BooksApp.scala
// Or from zio-http-example-rest-api-tutorial: sbt "runMain example.restapi.part7.BooksApp"

package example.restapi.part7

import java.sql.{PreparedStatement, ResultSet, Statement}
import javax.sql.DataSource

import scala.util.Using

import zio._
import zio.http._
import zio.schema.{DeriveSchema, Schema}

import org.h2.jdbcx.JdbcConnectionPool

/**
* Build Your First REST API — Part 7: Store the Books in a Database
*
* The finished app from part 5, with the books stored in an embedded H2
* database instead of a Ref. The routes are unchanged; only the BookRepo
* implementation and the layers given to `provide` are new.
*/
final case class Book(id: Int, title: String, author: String, year: Int)

object Book {
implicit val schema: Schema[Book] = DeriveSchema.gen[Book]
}

final case class NewBook(title: String, author: String, year: Int)

object NewBook {
implicit val schema: Schema[NewBook] = DeriveSchema.gen[NewBook]
}

final case class ApiError(message: String)

object ApiError {
implicit val schema: Schema[ApiError] = DeriveSchema.gen[ApiError]
}

final case class BookNotFound(id: Int)

trait BookRepo {
def all: UIO[List[Book]]
def get(id: Int): IO[BookNotFound, Book]
def add(newBook: NewBook): UIO[Book]
}

final case class DbConfig(url: String, user: String, password: Config.Secret)

object DbConfig {

val config: Config[DbConfig] =
(Config.string("url").withDefault("jdbc:h2:./books") ++
Config.string("user").withDefault("sa") ++
Config.secret("password").withDefault(Config.Secret(""))).nested("db").map { case (url, user, password) =>
DbConfig(url, user, password)
}

val layer: Layer[Config.Error, DbConfig] =
ZLayer.fromZIO(ZIO.config(config))
}

object ConnectionPool {

val layer: RLayer[DbConfig, DataSource] =
ZLayer.scoped {
for {
config <- ZIO.service[DbConfig]
pool <- ZIO.acquireRelease(
ZIO.attemptBlocking(JdbcConnectionPool.create(config.url, config.user, config.password.stringValue)),
)(pool => ZIO.succeed(pool.dispose()))
} yield pool
}
}

final case class JdbcBookRepo(dataSource: DataSource) extends BookRepo {

def all: UIO[List[Book]] =
withStatement("SELECT id, title, author, published_year FROM books ORDER BY id") { statement =>
readBooks(statement.executeQuery())
}

def get(id: Int): IO[BookNotFound, Book] =
withStatement("SELECT id, title, author, published_year FROM books WHERE id = ?") { statement =>
statement.setInt(1, id)
readBooks(statement.executeQuery()).headOption
}.someOrFail(BookNotFound(id))

def add(newBook: NewBook): UIO[Book] =
withStatement("INSERT INTO books (title, author, published_year) VALUES (?, ?, ?)") { statement =>
statement.setString(1, newBook.title)
statement.setString(2, newBook.author)
statement.setInt(3, newBook.year)
statement.executeUpdate()
val keys = statement.getGeneratedKeys()
keys.next()
Book(keys.getInt(1), newBook.title, newBook.author, newBook.year)
}

def createTable: UIO[Unit] =
withStatement(
"CREATE TABLE IF NOT EXISTS books (" +
"id INT AUTO_INCREMENT PRIMARY KEY, title VARCHAR(255) NOT NULL, " +
"author VARCHAR(255) NOT NULL, published_year INT NOT NULL)",
)(_.execute()).unit

private def withStatement[A](sql: String)(use: PreparedStatement => A): UIO[A] =
ZIO.attemptBlocking {
Using.resource(dataSource.getConnection()) { connection =>
Using.resource(connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS))(use)
}
}.orDie

private def readBooks(rows: ResultSet): List[Book] = {
val books = List.newBuilder[Book]
while (rows.next())
books += Book(rows.getInt("id"), rows.getString("title"), rows.getString("author"), rows.getInt("published_year"))
books.result()
}
}

object JdbcBookRepo {

val initialBooks: List[NewBook] =
List(
NewBook("Dune", "Frank Herbert", 1965),
NewBook("Neuromancer", "William Gibson", 1984),
NewBook("Count Zero", "William Gibson", 1986),
)

val layer: URLayer[DataSource, BookRepo] =
ZLayer.fromZIO {
for {
dataSource <- ZIO.service[DataSource]
repo = JdbcBookRepo(dataSource)
_ <- repo.createTable
books <- repo.all
_ <- ZIO.foreachDiscard(initialBooks)(repo.add).when(books.isEmpty)
} yield repo
}
}

object BooksApp extends ZIOAppDefault {

def jsonResponse[A](status: Status, value: A)(implicit schema: Schema[A]): Response =
Response(status, body = Body.json(value)).contentType(MediaType.application.json)

def errorResponse(status: Status, message: String): Response =
jsonResponse(status, ApiError(message))

val routes: Routes[BookRepo, Response] =
Routes(
Method.GET / "health" -> handler(Response.text("OK")),
Method.GET / "books" -> handler { (req: Request) =>
val author = req.queryParam("author")
for {
limit <- ZIO
.fromEither(req.query[Option[Int]]("limit"))
.orElseFail(errorResponse(Status.BadRequest, "limit must be a whole number"))
books <- ZIO.serviceWithZIO[BookRepo](_.all)
matching = books.filter(book => author.forall(_ == book.author)).take(limit.getOrElse(10))
} yield jsonResponse(Status.Ok, matching)
},
Method.GET / "books" / int("id") -> handler { (id: Int, _: Request) =>
ZIO
.serviceWithZIO[BookRepo](_.get(id))
.mapBoth(
notFound => errorResponse(Status.NotFound, s"No book with id ${notFound.id}"),
book => jsonResponse(Status.Ok, book),
)
},
Method.POST / "books" -> handler { (req: Request) =>
for {
newBook <- req.body
.asJson[NewBook]
.orElseFail(errorResponse(Status.BadRequest, "body must be a JSON book with title, author and year"))
book <- ZIO.serviceWithZIO[BookRepo](_.add(newBook))
} yield jsonResponse(Status.Created, book)
},
)

def run =
Server.serve(routes).provide(Server.default, JdbcBookRepo.layer, ConnectionPool.layer, DbConfig.layer)
}
The complete BooksAppSpec.scala at the end of part 7, running the part 6 tests against H2
zio-http-example-rest-api-tutorial/src/test/scala/example/restapi/part7/BooksAppSpec.scala
//> using scala 2.13.18
//> using dep dev.zio::zio-http:3.12.0
//> using dep com.h2database:h2:2.5.252
//> using dep dev.zio::zio-test:2.1.26
//> using dep dev.zio::zio-test-sbt:2.1.26
//> using file ../../../../../main/scala/example/restapi/part7/BooksApp.scala
// Run from this folder: scala-cli test BooksAppSpec.scala
// Or from zio-http-example-rest-api-tutorial: sbt "testOnly example.restapi.part7.BooksAppSpec"

package example.restapi.part7

import java.util.UUID

import zio._
import zio.http._
import zio.test._

/**
* Build Your First REST API — Part 7: Store the Books in a Database
*
* The tests from part 6, run against the JDBC repository. Each test gets its
* own in-memory H2 database, so every test starts with the same three books.
*/
object BooksAppSpec extends ZIOSpecDefault {

val testDbConfig: ULayer[DbConfig] =
ZLayer.fromZIO(
ZIO.succeed(DbConfig(s"jdbc:h2:mem:books-${UUID.randomUUID()}", "sa", Config.Secret(""))),
)

def spec =
suite("BooksApp with H2")(
test("GET /books/1 returns Dune") {
for {
response <- BooksApp.routes.runZIO(Request.get("/books/1"))
book <- response.body.asJson[Book]
} yield assertTrue(
response.status == Status.Ok,
book.title == "Dune",
)
},
test("GET /books/42 returns 404 Not Found") {
for {
response <- BooksApp.routes.runZIO(Request.get("/books/42"))
error <- response.body.asJson[ApiError]
} yield assertTrue(
response.status == Status.NotFound,
error.message == "No book with id 42",
)
},
test("POST /books saves a new book") {
val newBook = NewBook("Snow Crash", "Neal Stephenson", 1992)
for {
created <- BooksApp.routes.runZIO(Request.post("/books", Body.json(newBook)))
book <- created.body.asJson[Book]
fetched <- BooksApp.routes.runZIO(Request.get(s"/books/${book.id}"))
} yield assertTrue(
created.status == Status.Created,
book.id == 4,
fetched.status == Status.Ok,
)
},
test("GET /books?limit=abc returns 400 Bad Request") {
val request = Request.get((URL.root / "books").addQueryParam("limit", "abc"))
for {
response <- BooksApp.routes.runZIO(request)
} yield assertTrue(response.status == Status.BadRequest)
},
).provide(JdbcBookRepo.layer, ConnectionPool.layer, testDbConfig, Scope.default)
}

Running the Examples​

The code of this part is in the example.restapi.part7 package of zio-http-example-rest-api-tutorial. From that folder, start the server with sbt "runMain example.restapi.part7.BooksApp" and run its tests with sbt "testOnly example.restapi.part7.BooksAppSpec".

Recap​

In this part, we stored the books in an embedded H2 database. DbConfig describes the database settings with ZIO's Config, so they can come from environment variables. ConnectionPool.layer opens a connection pool with ZIO.acquireRelease inside ZLayer.scoped, so ZIO closes it when the program stops. JdbcBookRepo runs SQL on the blocking thread pool with ZIO.attemptBlocking and turns database errors into defects with ZIO#orDie. Because the handlers depend only on the BookRepo trait, switching from memory to a database meant changing the layers in ZIO#provide and Spec#provide, in the app and in the tests, and nothing else.

Where to Go Next​