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")
}
非常感謝你,@Sourav。你如何從應用程序中選擇哪個環境? –