Slick 3截断表进行测试

时间:2016-09-20 13:19:39

标签: mysql scala jdbc slick-3.0

我需要将我的旧代码与Slick 3一起使用,但它不起作用,我不知道该怎么做。

我的旧代码:

database.withSession { implicit s: Session =>
  StaticQuery.updateNA("SET foreign_key_checks = 0").execute()
  val q = StaticQuery.query[String, String](
    "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = ?"
  ).apply(dbname)
  for (table <- q) {
    StaticQuery.updateNA("TRUNCATE " + dbname + "." + table).execute()
  }
  StaticQuery.updateNA("SET foreign_key_checks = 1").execute()
}

带有光滑3的新代码:

val a = for {
  _ <- sqlu"SET foreign_key_checks = 0"
  s <- sql"SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = ${ dbname }".as[String]
  _ <- DBIO.sequence(s.map(table => sqlu"TRUNCATE #${MySQLDriver.quoteIdentifier(dbname)}.#${MySQLDriver.quoteIdentifier(table)}").map(x => DBIO.successful(x)))
  _ <- DBIO.successful(sql"SET foreign_key_checks = 1")
} yield ()

Await.result(db.run(a), scala.concurrent.duration.Duration(1000, SECONDS))

错误:

com.googlecode.flyway.core.api.FlywayException: Unable to lock table `myLocalDB_test`.`schema_version
Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'myLocalDB_test.schema_version' doesn't exist

2 个答案:

答案 0 :(得分:1)

好像你想从MTable.getTables获取表格。

@ import slick.jdbc.meta.MTable 
import slick.jdbc.meta.MTable
@ MTable.getTables 
res91: profile.BasicStreamingAction[Vector[MTable], MTable, Effect.Read] = slick.jdbc.ResultSetAction$$anon$1@61dff30a
@ db.run(res91) 
res92: concurrent.Future[Vector[MTable]] = Success(Vector(MTable(MQName(TEST1.PUBLIC.COFFEES),TABLE,,None,None,None), MTable(MQName(TEST1.PUBLIC.SUPPLIERS),TABLE,,None,None,None)))

答案 1 :(得分:0)

我在Github上找到了一个示例,它现在似乎正常工作,您可以从here

查看

我改变了它:

val truncatesFuture = db.run(
      sql"""SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = ${ dbname }""".as[String]
    ).map {
      _.map { case (table) => SQLActionBuilder(List(s"TRUNCATE TABLE $table"), SetUnit).asUpdate }
    }

Await.result(truncatesFuture.flatMap(
  truncates =>
    db.run(
      DBIO.sequence(
        List(
          List( sqlu"""SET FOREIGN_KEY_CHECKS = 0;"""),
          truncates,
          List( sqlu"""SET FOREIGN_KEY_CHECKS = 1;""")
        ).flatten
      )
    )
), scala.concurrent.duration.Duration(5000, SECONDS))