Phil Phil - 3 months ago 26
Scala Question

Scala Slick, how to create Schema ONLY if it does not exist

In Scala Slick, a database schema can be created with the following:

val schema = coffees.schema ++ suppliers.schema
db.run(DBIO.seq(
schema.create
))


From the bottom of this documentation page http://slick.typesafe.com/doc/3.0.0/schemas.html

However, if the database schema already exists then this throws an exception.

Is there a normal way or right way to create the schema IF AND ONLY IF it does not already exist?

Answer

As JoshSGoman comment points out about the answer of Mike-s, the table is not created. I managed to make it work by slightly modifying the first answer's code :

val coffees = TableQuery[Coffees]

try {
  def createTableIfNotInTables(tables: Vector[MTable]): Future[Unit] = {
    if (!tables.exists(_.name.name == events.baseTableRow.tableName)) {
      db.run(coffees.schema.create)
    } else {
      Future()
    }
  }

  val createTableIfNotExist: Future[Unit] = db.run(MTable.getTables).flatMap(createTableIfNotInTables)

  Await.result(createTableIfNotExist, Duration.Inf)
} finally db.close

With the following imports :

import slick.jdbc.meta.MTable
import slick.driver.SQLiteDriver.api._

import scala.concurrent.{Await, Future}
import scala.concurrent.duration.Duration
import scala.concurrent.ExecutionContext.Implicits.global