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

时间:2015-11-26 02:35:43

标签: scala slick

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

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

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

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

是否有正常的方法或正确的方式来创建架构IF和仅在它尚不存在的情况下?

5 个答案:

答案 0 :(得分: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)

答案 1 :(得分:4)

为什么不在create之前检查存在?

val schema = coffees.schema ++ suppliers.schema
db.run(DBIO.seq(
  if (!MTable.getTables.list.exists(_.name.name == MyTable.tableName)){
    schema.create
  }
))

答案 2 :(得分:4)

由于JoshSGoman comment指出了answer of 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

使用以下导入:

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

答案 3 :(得分:2)

在Slick 3.3.0中,添加了createIfNotExistsdropIfExists模式方法。所以:

db.run(coffees.schema.createIfNotExists)

用Google搜索这个问题,并从答案中尝试了几种解决方案,直到找到答案。

答案 4 :(得分:1)

不能在由3个表组成的架构上使用createIfNotExists,并且其中一个表具有复合主键。在此,第三表具有由第一和第二表中的每一个的主键组成的主键。当第二次遇到.createIfNotExists时,在此架构上出现错误。我在scala 2.12.8上使用了光滑的3.3.1。

    class UserTable(tag: Tag) extends Table[User](tag, "user") {
      def id    = column[Long]("id", O.AutoInc, O.PrimaryKey)
      def name  = column[String]("name")
      def email = column[Option[String]]("email")

      def * = (id.?, name, email).mapTo[User]
    }
    val users = TableQuery[UserTable]
    lazy val insertUser = users returning users.map(_.id)

    case class Room(title: String, id: Long = 0L)
    class RoomTable(tag: Tag) extends Table[Room](tag, "room") {
     def id    = column[Long]("id", O.PrimaryKey, O.AutoInc)
     def title = column[String]("title")
     def * = (title, id).mapTo[Room]
    }
    val rooms = TableQuery[RoomTable]
    lazy val insertRoom = rooms returning rooms.map(_.id)

    case class Occupant(roomId: Long, userId: Long)
    class OccupantTable(tag: Tag) extends Table[Occupant](tag, "occupant") {
      def roomId = column[Long]("room")
      def userId = column[Long]("user")

      def pk = primaryKey("room_user_pk", (roomId, userId) )

      def * = (roomId, userId).mapTo[Occupant]
    }
    val occupants = TableQuery[OccupantTable]

我可以成功创建架构并首先添加用户,房间和占用者。在.createIfNotExists的第二种用法中,如下所示,在重复的主键上出现错误:

  println("\n2nd run on .createIfNotExists using different values for users, rooms and occupants")
  val initdup = for {
    _         <- users.schema.createIfNotExists
    _         <- rooms.schema.createIfNotExists
    _         <- occupants.schema.createIfNotExists
      curlyId   <- insertUser += User(None, "Curly", Some("curly@example.org"))
      larryId   <- insertUser += User(None, "Larry")
      moeId     <- insertUser += User(None, "Moe", Some("moe@example.org"))
      shedId   <- insertRoom += Room("Shed")
      _         <- occupants += Occupant(shedId, curlyId)
      _         <- occupants += Occupant(shedId, moeId)
    } yield ()

例外如下:

2nd run on .createIfNotExists using different values for users, rooms and occupants
[error] (run-main-2) org.h2.jdbc.JdbcSQLException: Constraint "room_user_pk" already exists; SQL statement:
[error] alter table "occupant" add constraint "room_user_pk" primary key("room","user") [90045-197]
[error] org.h2.jdbc.JdbcSQLException: Constraint "room_user_pk" already exists; SQL statement:
[error] alter table "occupant" add constraint "room_user_pk" primary key("room","user") [90045-197]
[error]         at org.h2.message.DbException.getJdbcSQLException(DbException.java:357)
[error]         at org.h2.message.DbException.get(DbException.java:179)
[error]         at org.h2.message.DbException.get(DbException.java:155)
[error]         at org.h2.command.ddl.AlterTableAddConstraint.tryUpdate(AlterTableAddConstraint.java:110)
[error]         at org.h2.command.ddl.AlterTableAddConstraint.update(AlterTableAddConstraint.java:78)
[error]         at org.h2.command.CommandContainer.update(CommandContainer.java:102)
[error]         at org.h2.command.Command.executeUpdate(Command.java:261)
[error]         at org.h2.jdbc.JdbcPreparedStatement.execute(JdbcPreparedStatement.java:249)
[error]         at slick.jdbc.JdbcActionComponent$SchemaActionExtensionMethodsImpl$$anon$6.$anonfun$run$7(JdbcActionComponent.scala:292)
[error]         at slick.jdbc.JdbcActionComponent$SchemaActionExtensionMethodsImpl$$anon$6.$anonfun$run$7$adapted(JdbcActionComponent.scala:292)
[error]         at slick.jdbc.JdbcBackend$SessionDef.withPreparedStatement(JdbcBackend.scala:425)
[error]         at slick.jdbc.JdbcBackend$SessionDef.withPreparedStatement$(JdbcBackend.scala:420)
[error]         at slick.jdbc.JdbcBackend$BaseSession.withPreparedStatement(JdbcBackend.scala:489)
[error]         at slick.jdbc.JdbcActionComponent$SchemaActionExtensionMethodsImpl$$anon$6.$anonfun$run$6(JdbcActionComponent.scala:292)
[error]         at slick.jdbc.JdbcActionComponent$SchemaActionExtensionMethodsImpl$$anon$6.$anonfun$run$6$adapted(JdbcActionComponent.scala:292)
[error]         at scala.collection.Iterator.foreach(Iterator.scala:941)
[error]         at scala.collection.Iterator.foreach$(Iterator.scala:941)
[error]         at scala.collection.AbstractIterator.foreach(Iterator.scala:1429)
[error]         at scala.collection.IterableLike.foreach(IterableLike.scala:74)
[error]         at scala.collection.IterableLike.foreach$(IterableLike.scala:73)
[error]         at scala.collection.AbstractIterable.foreach(Iterable.scala:56)
[error]         at slick.jdbc.JdbcActionComponent$SchemaActionExtensionMethodsImpl$$anon$6.run(JdbcActionComponent.scala:292)
[error]         at slick.jdbc.JdbcActionComponent$SchemaActionExtensionMethodsImpl$$anon$6.run(JdbcActionComponent.scala:290)
[error]         at slick.jdbc.JdbcActionComponent$SimpleJdbcProfileAction.run(JdbcActionComponent.scala:28)
[error]         at slick.jdbc.JdbcActionComponent$SimpleJdbcProfileAction.run(JdbcActionComponent.scala:25)
[error]         at slick.basic.BasicBackend$DatabaseDef$$anon$3.liftedTree1$1(BasicBackend.scala:276)
[error]         at slick.basic.BasicBackend$DatabaseDef$$anon$3.run(BasicBackend.scala:276)
[error]         at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
[error]         at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
[error]         at java.lang.Thread.run(Thread.java:748)
[error] Nonzero exit code: 1
[error] (Compile / run) Nonzero exit code: 1

此外,我可以在使用O.PrimaryKey约定创建所有表的架构上多次使用.createIfNotExists。

我可以做些按摩代码吗?是否有解决方法,以便.createIfNotExists在复合主键大小写情况下仍可用?