2017-08-09 59 views
0

油滑3.0.0 发挥2.6.2如何油滑使用不同的数据库驱动程序根据应用环境(如测试,督促等)

我用油滑试验和运行成一个有趣的问题。我希望解决方案只是微不足道的,我对这个想法太多了

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

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") 

} 

回答

0

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

application.conf --local 

application.prod.conf -- prod with contents below 

include "aplication.conf" 
###update slick configurations 

然后同时在不同阶段运行的应用饲料与-Dconfig.resource=

+0

非常感谢你,@Sourav。你如何从应用程序中选择哪个环境? –

相关问题