Scala Slick,如果它不存在,如何创建Schema

Phi*_*hil 15 scala slick

在Scala Slick中,可以使用以下命令创建数据库模式:

val schema = coffees.schema ++ suppliers.schema
db.run(DBIO.seq(
  schema.create
))
Run Code Online (Sandbox Code Playgroud)

从本文档页面底部http://slick.typesafe.com/doc/3.0.0/schemas.html

但是,如果数据库模式已存在,则会引发异常.

有没有正常的方法或正确的方法来创建架构IF并且仅在它尚不存在的情况下?

Dmi*_*rov 17

在油滑3.3.0createIfNotExists和dropIfExists添加模式的方法。所以:

db.run(coffees.schema.createIfNotExists)
Run Code Online (Sandbox Code Playgroud)

谷歌搜索了这个问题,并从答案中尝试了几种解决方案,直到弄清楚为止。


Mik*_*e S 5

用油滑3.0,Mtable.getTables是一DBAction所以像这样的工作:

val coffees = TableQuery[Coffees]
try {
  Await.result(db.run(DBIO.seq(
    MTable.getTables map (tables => {
      if (!tables.exists(_.name.name == coffees.baseTableRow.tableName))
        coffees.schema.create
    })
  )), Duration.Inf)
} finally db.close
Run Code Online (Sandbox Code Playgroud)


Vin*_*oba 5

正如JoshSGoman 评论指出Mike-s的答案,该表未创建。我设法通过稍微修改第一个答案的代码使其工作:

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
Run Code Online (Sandbox Code Playgroud)

使用以下进口:

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
Run Code Online (Sandbox Code Playgroud)


use*_*759 5

这就是我对多个表所做的事情,使用光滑的3.1.1和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)
Run Code Online (Sandbox Code Playgroud)