2015-11-26 5 views

risposta

4

Questo è quello che faccio per più tabelle, con la chiazza di petrolio 3.1.1 e 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

perché non si controlla semplicemente l'esistenza prima di create?

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

Con Slick 3.0, Mtable.getTables è un DBAction così qualcosa come questo dovrebbe funzionare:

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

Continuo a ricevere un errore di contesto di esecuzione per questo, l'errore scompare se si importa 'scala.concurrent.ExecutionContext.Implicits.global', ma la tabella non viene creata. Come posso risolverlo? – JoshSGman

3

Come JoshSGoman comment punti conoscere il answer of Mike-s, non viene creata la tabella. Sono riuscito a farlo funzionare modificando leggermente il codice della prima risposta:

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 

Con le seguenti importazioni:

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

Perché dobbiamo dichiarare db.run due volte? Non dovrebbe coffees.schema.create funzionare ancora in questo contesto? – JoshSGman