【问题标题】:How to execute DDL only when tables don't exist?仅当表不存在时如何执行 DDL?
【发布时间】:2013-03-14 11:52:22
【问题描述】:

我将 Slick 1.0 与 Play Framework 2.1 和 MySQL 一起使用。

我想控制 ddl 表的创建,以便仅在表不存在时进行。也就是说,表应该只在我第一次开始游戏时创建。

如何在 Slick 中做到这一点?

【问题讨论】:

    标签: mysql scala playframework-2.1 slick


    【解决方案1】:

    由于我喜欢单独控制表的创建并保持干燥,我只是倾向于向我的应用程序添加一个实用方法:

    def createIfNotExists(tables: TableQuery[_ <: Table[_]]*)(implicit session: Session) {
      tables foreach {table => if(MTable.getTables(table.baseTableRow.tableName).list.isEmpty) table.ddl.create}
    }
    

    然后您可以使用隐式会话创建表:

    db withSession {
      implicit session =>
        createIfNotExists(table1, table2, ..., tablen)
    }
    

    【讨论】:

    • 这似乎是一个比公认的答案更强大的解决方案
    【解决方案2】:

    为了他人的利益,SLICK 提供了一个MTable 对象,您可以使用它来计算数据库中存在的表的数量。

    然后,如果它们不存在,您可以有条件地调用 ddl。在下面的情况下,我希望有 11 个表 + play_evolutions 表

    import scala.slick.jdbc.meta._
    
     if (MTable.getTables.list().size < 12) {
            (Contacts.ddl ++ ThirdParties.ddl ++ Directorates.ddl ++ ServiceAreas.ddl ++ ICTServers.ddl
              ++ ICTServerDependencies.ddl ++ ICTSystems.ddl ++ ICTSystemDependencies.ddl ++ ICTSystemServerDependencies.ddl
                  ++ CouncilServices.ddl ++ CouncilServiceDependencies.ddl).create
    }
    

    【讨论】:

    • 单表:if (MTable.getTables ("test") .list.isEmpty) Test.ddl.create
    • 你也可以通过在Slick 1.0中调用Test.tableName和在Slick 2.0中调用Test.baseTableRow.tableName来获取表名
    【解决方案3】:

    我知道问题是关于 Slick 1,但为了 Slick 3 的完整性,我做了以下操作:

      Await.result(createTableIfNotExists(tableQuery1, tableQuery2, tableQuery3), Duration.Inf)
    
      private def createTableIfNotExists(tables: TableQuery[_ <: Table[_]]*): Future[Seq[Unit]] = {
        Future.sequence(
          tables map { table =>
            db.run(MTable.getTables(table.baseTableRow.tableName)).flatMap { result =>
              if (result.isEmpty) {
                db.run(table.schema.create)
              } else {
                Future.successful(())
              }
            }
          }
        )
      }
    

    【讨论】:

      猜你喜欢
      • 2014-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-12
      • 2021-04-11
      • 2010-09-30
      • 2016-08-23
      • 1970-01-01
      相关资源
      最近更新 更多