How to execute DDL only when tables don't exist?

扶醉桌前 提交于 2019-11-29 03:56:32

Since I like to control the creation of my tables individually and keep it DRY, I just tend to add a utility method to my apps:

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

Then you can just create your tables with the implicit session:

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

For the benefit of others SLICK provides an MTable Object that you can use to count the number of tables present in your database.

You can then conditionally call the ddl if they are not present. In the case below I expect to have 11 tables + the play_evolutions table

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
}

I realise the question is about Slick 1, but for the sake of completeness in Slick 3 I do the following:

  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(())
          }
        }
      }
    )
  }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!