我今天写了一个小小的光滑程序。有用。这是代码
package com.abhi
import slick.driver.MySQLDriver.api._
import slick.jdbc.meta.MTable
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
import scala.util.{Success, Failure}
object MySlickApp extends App {
val db = Database.forConfig("essential-slick ")
val messages = TableQuery[MessageTable]
val tableExists = MTable.getTables map { tables =>
tables.exists(_.name.name == messages.baseTableRow.tableName)
}
val dropAction = messages.schema.drop
val createAction = messages.schema.create
val freshMessages = Seq(
Message("Dave", "Hello HAL. Do you read me? HAL?"),
Message("HAL", "Affirmtive, Dave. I read you."),
Message("Dave", "Open the pod doors, HAL."),
Message("HAL", "I'm Sorry. Dave. I'm afraid, I cannot do that.")
)
val insertAction = messages ++= freshMessages
val f5 = for {
f1 <- db.run(tableExists)
f2 <- db.run(dropAction) if f1 == true
f3 <- db.run(createAction)
f4 <- db.run(insertAction)
} yield (f1, f2, f3, f4)
f5.onComplete{
case Success(s) => println("table initialized successfully "); db.close
case Failure(f) => println(f.getMessage); db.close
}
scala.io.StdIn.readLine()
}
final case class Message (sender: String, content: String, id: Long = 0L)
final case class MessageTable(tag: Tag) extends Table[Message](tag, "Message") {
def id = column[Long]("id", O.PrimaryKey, O.AutoInc)
def sender = column[String]("sender")
def content = column[String]("content")
def * = (sender, content, id) <> (Message.tupled, Message.unapply)
}
我对这个程序有两件事情
我必须在for comprehension的每一行指定db.run。我试图将所有操作都放在Seq中,然后将DBIO.seq提供给db.run,但它运行所有异步而不是按顺序。
我必须在&#34;成功&#34;两者中调用db.close。和&#34;失败&#34;场景。我想知道是否有一种方法可以在一个地方关闭资源而不会重复。
答案 0 :(得分:1)
使用最新的光滑3.2 1.你可以通过将DBIOActions链接在一起而不是期货来以单向数据库的方式运行它。这样做可以增加将其作为事务运行的好处:
val f = for {
r1 <- tableExists
r2 <- {
if(r1){
dropAction
}else{
DBIO.successful()
}
}
r3 <- createAction
r4 <- insertAction
} yield (f)
db.run(f).transactionally