Phil Phil - 6 months ago 67
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

From the bottom of this documentation page

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?


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( == events.baseTableRow.tableName)) {
    } else {

  val createTableIfNotExist: Future[Unit] =

  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