Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 773
Phil Avatar asked Nov 26 '15 02:11

Phil


2 Answers

In Slick 3.3.0 createIfNotExists and dropIfExists schema methods were added. So:

db.run(coffees.schema.createIfNotExists) 

Googled this question and tried several solutions from answers until figured it out.

like image 162
Dmitrii Nikiforov Avatar answered Oct 26 '22 08:10

Dmitrii Nikiforov


This is what I do for multiple tables, with slick 3.1.1 and Postgres

import slick.driver.PostgresDriver.api._ import slick.jdbc.meta.MTable import scala.concurrent.Await import scala.concurrent.duration.Duration import scala.concurrent.ExecutionContext.Implicits.global  val t1 = TableQuery[Table1] val t2 = TableQuery[Table2] val t3 = TableQuery[Table3] val tables = List(t1, t2, t3)  val existing = db.run(MTable.getTables) val f = existing.flatMap( v => {     val names = v.map(mt => mt.name.name)     val createIfNotExist = tables.filter( table =>         (!names.contains(table.baseTableRow.tableName))).map(_.schema.create)     db.run(DBIO.sequence(createIfNotExist)) }) Await.result(f, Duration.Inf) 
like image 23
user2829759 Avatar answered Oct 26 '22 08:10

user2829759