【问题标题】:How can Slick use different Database driver based on Application environment (e.g. test, prod, etc.)Slick 如何根据应用程序环境(例如 test、prod 等)使用不同的数据库驱动程序
【发布时间】:2018-01-17 14:50:37
【问题描述】:

光滑 3.0.0 玩2.6.2

我正在尝试使用 Slick 并遇到一个有趣的问题。我希望解决方案只是微不足道的,我想太多了

我已经实现了以下简单的代码。

case class Content(content:String)

class ContentTable(tag: Tag) extends Table[Content](tag, "content"){
  def id = column[Long]("id", O.PrimaryKey, O.AutoInc)

  def content = column[String]("content")


  override def * : ProvenShape[Content] = (content).mapTo[Content]
}

object ContentDb {
  val db = Database.forConfig("databaseConfiguration")
  lazy val contents = TableQuery[ContentTable]

  def all: Seq[Content] = Await.result(db.run(contents.result), 2 seconds)
}

因此,要使此代码正常工作,当然需要以下导入。

import slick.jdbc.H2Profile.api._

或者

import slick.jdbc.PostgresProfile.api._

现在,我认为,如果我错了,请纠正我,数据库驱动程序应该是一个配置细节。也就是说,我会选择在开发时在内存数据库中运行 H2。在测试时针对测试 PostgreSQL 实例运行,然后在生产时针对另一个实例运行。我的意思是抽象驱动程序的整个想法是具有这种灵活性......我认为。

现在,我做了一些研究,发现我可以做这样的事情:

trait DbComponent {

  val driver: JdbcProfile

  import driver.api._

  val db: Database

}


trait H2DbComponent extends DbComponent {

  val driver: JdbcProfile = slick.jdbc.H2Profile

  import driver.api._

  val db = Database.forConfig("databaseConfiguration")

}

trait Contents {
  def all: Seq[Content]
}

object Contents {
  def apply: Contents = new ContentsDb with H2DbComponent
}

trait ContentsDb extends Contents {
  this: DbComponent =>

  import driver.api._

  class ContentTable(tag: Tag) extends Table[Content](tag, "content") {
    def id = column[Long]("id", O.PrimaryKey, O.AutoInc)

    def content = column[String]("content")


    override def * : ProvenShape[Content] = content.mapTo[Content]
  }

  lazy val contents = TableQuery[ContentTable]

  def all: Seq[Content] = Await.result(db.run(contents.result), 2 seconds)

}

然后我可以使用依赖注入为我拥有的每个实体注入正确的实例。不理想,但可能。因此,我开始研究如何根据 Play Framework 中运行的环境进行条件依赖注入。

我期待类似于以下内容:

@Component(env=("prod","test")
class ProductionContentsDb extends ContentsDb with PostgresDbComponent

@Component(env="dev")
class ProductionContentsDb extends ContentsDb with H2DbComponent

但是,没有运气......

编辑

就在我写完这篇文章并再次开始阅读之后,我很好奇我们是否可以拥有类似的东西:

class DbComponent @Inject (driver: JdbcProfile) {

  import driver.api._

  val db = Database.forConfig("databaseConfiguration")

} 

【问题讨论】:

    标签: scala jdbc playframework sbt slick


    【解决方案1】:

    您可以为每个环境创建单独的配置文件。喜欢

    application.conf --local
    
    application.prod.conf -- prod with contents below
    
    include "aplication.conf"
    ###update slick configurations
    

    然后在不同阶段运行应用程序时输入-Dconfig.resource=

    【讨论】:

    • 非常感谢@Sourav。您如何从应用程序中选择哪个环境?
    猜你喜欢
    • 2019-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-03
    • 2013-07-09
    相关资源
    最近更新 更多