Mag*_*ith 11 mysql scala slick playframework-2.1
我正在使用Slick 1.0与Play Framework 2.1和MySQL.
我想控制ddl表的创建,以便只有在表不存在时才会发生.也就是说,表格应该只在我第一次开始游戏时创建.
如何在Slick中做到这一点?
Mic*_*ess 15
由于我喜欢单独控制我的表的创建并保持干燥,我只是倾向于为我的应用添加一个实用工具方法:
def createIfNotExists(tables: TableQuery[_ <: Table[_]]*)(implicit session: Session) {
tables foreach {table => if(MTable.getTables(table.baseTableRow.tableName).list.isEmpty) table.ddl.create}
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用隐式会话创建表:
db withSession {
implicit session =>
createIfNotExists(table1, table2, ..., tablen)
}
Run Code Online (Sandbox Code Playgroud)
Mag*_*ith 11
为了其他人的利益,SLICK提供了一个MTable对象,您可以使用它来计算数据库中存在的表的数量.
然后,如果它们不存在,您可以有条件地调用ddl.在下面的情况下,我希望有11个表+ play_evolutions表
import scala.slick.jdbc.meta._
if (MTable.getTables.list().size < 12) {
(Contacts.ddl ++ ThirdParties.ddl ++ Directorates.ddl ++ ServiceAreas.ddl ++ ICTServers.ddl
++ ICTServerDependencies.ddl ++ ICTSystems.ddl ++ ICTSystemDependencies.ddl ++ ICTSystemServerDependencies.ddl
++ CouncilServices.ddl ++ CouncilServiceDependencies.ddl).create
}
Run Code Online (Sandbox Code Playgroud)
我意识到问题是关于Slick 1,但为了Slick 3中的完整性我做了以下事情:
Await.result(createTableIfNotExists(tableQuery1, tableQuery2, tableQuery3), Duration.Inf)
private def createTableIfNotExists(tables: TableQuery[_ <: Table[_]]*): Future[Seq[Unit]] = {
Future.sequence(
tables map { table =>
db.run(MTable.getTables(table.baseTableRow.tableName)).flatMap { result =>
if (result.isEmpty) {
db.run(table.schema.create)
} else {
Future.successful(())
}
}
}
)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3579 次 |
| 最近记录: |