ScalaConsultants/zio-slick-interop

"Database" is reinitialized and closed on each call

Opened this issue · 2 comments

After encountering rather poor performances in my application, I found out that the bottleneck is Slick. Further investigation discovered that the default DatabaseProvider was problematic:

object DatabaseProvider {

  val live: ZLayer[Config with JdbcProfile, Throwable, DatabaseProvider] = {
    val dbProvider = for {
      cfg <- ZIO.service[Config]
      p   <- ZIO.service[JdbcProfile]
      db   = ZIO.attempt(p.backend.Database.forConfig("", cfg))
      a   <- ZIO.acquireRelease(db)(db => ZIO.succeed(db.close()))
    } yield new DatabaseProvider {
      override val db: UIO[JdbcBackend#Database] = ZIO.succeed(a)
      override val profile: UIO[JdbcProfile]     = ZIO.succeed(p)
    }

    ZLayer.scoped(dbProvider)
  }
}

The "Database" is reinitialized and closed after each call of ZIO.fromDBIO( ... ) leading to poor performances.
My temporary fix:

  private val database = Database.forConfig("", dbConfig)

  private val dbProvider = ZIO.service[JdbcProfile].map { prof =>
    new DatabaseProvider {
      override val db: UIO[JdbcBackend#Database] = ZIO.succeed(database)
      override val profile: UIO[JdbcProfile]     = ZIO.succeed(prof)
    }
  }

  val live: ZLayer[Config with JdbcProfile, Throwable, DatabaseProvider] = ZLayer.scoped(dbProvider)

In this case, the "Database" is initialized once and reused.

Is this still a problem?

@baovitt Yes. Avoid using the lib as is since a DB pool is recreated on every call. You can either use it as I described or write your own wrapper.