假设我在下面有 2 个模式。它们都在同一个 MySQL 服务器中。
- 大师
- 基地
问题是我不能在单个数据库中使用超过 2 个模式操作 run
.
如果我通过 sql
执行这样的普通 sql 查询, 它工作没有任何问题。
def fooAction(name: String) = {
sql"""
SELECT AGE FROM MASTER.FOO_TABLE WHERE NAME = $name
""".as[String].head
}
def barAction(id: String) = {
sql"""
SELECT BAZ FROM BASE.BAR_TABLE WHERE ID = $id
""".as[String].head
}
def execute = {
//It doesn't matter which Db I use in here But Let's say this baseDb is pointing to BASE schema.
baseDb.run(for{
foo <- fooAction("sample")
bar <- barAction("sample")
} yield foo + bar)
}
但是代码blow的情况不会
class FooTableDAO @Inject() (@NamedDatabase("master") protected val dbConfigProvider: DatabaseConfigProvider) extends HasDatabaseConfigProvider[JdbcProfile] {
import dbConfig.driver.api._
val table = TableQuery[FooTable]
def fooAction(name: String) = table.filter{_.name == name}.map{_.age}.result.head
}
class BarTableDAO @Inject() (@NamedDatabase("base") protected val dbConfigProvider: DatabaseConfigProvider) extends HasDatabaseConfigProvider[JdbcProfile] {
import dbConfig.driver.api._
val table = TableQuery[BarTable]
def fooAction(id: String) = table.filter{_.id == id}.map{_.baz}.result.head
}
def execute = {
//com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'BASE.FOO_TABLE' doesn't exist
baseDb.run(for{
foo <- fooTableDAO.fooAction("sample")
bar <- barTableDAO.barAction("sample")
} yield foo + bar)
}
自 baseDb
指向 BASE 模式,它试图找到 FOO_TABLE
在主架构中。我想要 slick 做的就是为每个查询使用不同的模式,但我找不到方法。
目前我做DBIO.from(db.run(**))
如果在理解 DBIO 操作时需要另一个模式操作或通过 run
执行每个操作并用 EitherT
包裹它们这是名为 cats
的 Scala 库Either
的 monad 转换器继续使用 for-comprehension。
除了使用纯文本查询之外,是否有任何方法可以在单个 DBIO 操作中处理超过 2 个模式?
提前致谢。
最佳答案
我认为(尽管我不是 MySQL 专家)您指的是 schema
,而不是 database
。至少这是我从您的 SQL
示例中看到的。
您不能在 Slick
表映射中使用 schema 属性吗?在这里你有使用不同模式的完整答案:https://stackoverflow.com/a/41090987/2239369
相关代码如下:
class StudentTable(tag: Tag) extends Table[Student](tag, _schemaName = Option("database2"), "STUDENT") {
...
}
(注意 _schemaName
属性)。
考虑到这一点,回答这部分问题:
Is there any way to handle more than 2 schemas in a single DBIO Action except using plain text query?
是:是的,你可以。
关于mysql - 在 Slick 的单个 DBIO 中使用多个 DB/Schema,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41820387/