2013-03-14 6 views

答えて

11

SLICKには、データベースに存在するテーブルの数を数えるために使用できるMTableオブジェクトがあります。

ddlが存在しない場合、条件付きでddlを呼び出すことができます。私は個別に私のテーブルの作成を制御し、DRY、それを維持したいので、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

+1

あなたはまた、スリックでTest.tableNameを呼び出すことにより、テーブル名を得ることができる場合1.0とTest.baseTableRow.tableName Slick 2.0 – cvogt

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

これは受け入れられた答えよりも頑強な解決策のようです –

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(()) 
      } 
     } 
     } 
    ) 
    } 
関連する問題