2015-11-26 46 views

回答

4

這是我對多個表做的,用油滑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) 
4

爲什麼不簡單檢查create之前的存在?

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

用油滑3.0,Mtable.getTablesDBAction所以像這樣的工作:

val coffees = TableQuery[Coffees] 
try { 
    Await.result(db.run(DBIO.seq(
    MTable.getTables map (tables => { 
     if (!tables.exists(_.name.name == coffees.baseTableRow.tableName)) 
     coffees.schema.create 
    }) 
)), Duration.Inf) 
} finally db.close 
+1

我不斷收到一個執行上下文錯誤,如果我導入'scala.concurrent.ExecutionContext.Implicits.global'但是沒有創建表,錯誤消失。我該如何解決這個問題? – JoshSGman

3

由於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 
+0

爲什麼我們需要聲明db.run兩次? coffees.schema.create是否仍然適用於這種情況? – JoshSGman