2013-03-14 18 views
11

我在Play Framework 2.1和MySQL上使用了Slick 1.0。如何僅在表不存在時執行DDL?

我想控制ddl表的創建,以便它只發生在表不存在的情況下。也就是說,表格只能在我第一次開始玩遊戲時創建。

如何在Slick中做到這一點?

回答

11

爲了其他人的利益SLICK提供了一個對象,您可以使用該對象來統計數據庫中存在的表的數量。

然後,您可以有條件地調用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 
} 
+4

單個表:'如果(MTable.getTables(「測試」).list.isEmpty)Test.ddl.create' – ArtemGr 2013-04-10 03:46:59

+1

您還可以通過在油滑調用Test.tableName拿到表名1.0和Test.baseTableRow.tableName in Slick 2.0 – cvogt 2014-03-30 13:29:43

15

因爲我喜歡單獨控制我的表的創建和保持乾燥,我只是傾向於實用方法添加到我的應用程序:

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) 
} 
+0

這似乎是一個比接受的答案更強大的解決方案 – 2015-03-18 16:16:22

8

我意識到問題是關於油滑1,但對完整的油滑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(()) 
      } 
     } 
     } 
    ) 
    } 
相關問題