How to write database-agnostic Play application and perform first-time database initialization?

后端 未结 4 1476
生来不讨喜
生来不讨喜 2020-12-22 17:45

I\'m using Slick with a Play Framework 2.1 and I have some troubles.

Given the following entity...

package models

import scala.slick.driver.Postgres         


        
4条回答
  •  隐瞒了意图╮
    2020-12-22 18:32

    I was also trying to address this problem: the ability to switch databases between test and production. The idea of wrapping each table object in a trait was unappealing.

    I am not trying to discuss the pros and cons of the cake pattern here, but I found another solution, for those who are interested.

    Basically, make an object like this:

    package mypackage
    import scala.slick.driver.H2Driver
    import scala.slick.driver.ExtendedProfile
    import scala.slick.driver.PostgresDriver
    
    object MovableDriver {
      val simple = profile.simple
      lazy val profile: ExtendedProfile = {
        sys.env.get("database") match {
          case Some("postgres") => PostgresDriver
          case _ => H2Driver
        }
      }
    }
    

    Obviously, you can do any decision logic you like here. It does not have to be based on system properties.

    Now, instead of:

    import scala.slick.driver.H2Driver.simple._
    

    You can say

    import mypackage.MovableDriver.simple._
    

    UPDATE: A Slick 3.0 Version, courtesy of trent-ahrens:

    package mypackage
    
    import com.typesafe.config.ConfigFactory
    
    import scala.slick.driver.{H2Driver, JdbcDriver, MySQLDriver}
    
    object AgnosticDriver {
      val simple = profile.simple
      lazy val profile: JdbcDriver = {
        sys.env.get("DB_ENVIRONMENT") match {
          case Some(e) => ConfigFactory.load().getString(s"$e.slickDriver") match {
            case "scala.slick.driver.H2Driver" => H2Driver
            case "scala.slick.driver.MySQLDriver" => MySQLDriver
          }
          case _ => H2Driver
        }
      }
    }
    

提交回复
热议问题