用于测试的 Slick 3 截断表
Posted
技术标签:
【中文标题】用于测试的 Slick 3 截断表【英文标题】:Slick 3 truncate tables for testing 【发布时间】:2017-01-28 10:45:05 【问题描述】:我需要在 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()
带有 slick 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
【问题讨论】:
【参考方案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)))
【讨论】:
【参考方案2】:我在 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))
【讨论】:
以上是关于用于测试的 Slick 3 截断表的主要内容,如果未能解决你的问题,请参考以下文章