Scala
PlayFramework

非対話的に evolutions を適用する

More than 1 year has passed since last update.

複数 DB に対する evolutions をまとめて適用するやつ。CI とかコンテナ構築のお供に。

# デフォルト DB に対して適用
$ sbt "runMain ApplyEvolutions default"
object ApplyEvolutions {
  import play.api._
  import play.api.db._
  import play.api.db.evolutions._


  def main(args: Array[String]) {
    java.lang.System.setProperty("play.evolutions.enabled", "false")

    // Start the application (instead of using `new play.core.StaticApplication(...)`)
    val env = Environment(new java.io.File("."), this.getClass.getClassLoader, Mode.Dev)
    val context = ApplicationLoader.createContext(env)
    val loader = ApplicationLoader(context)
    implicit val app: Application = loader.load(context)
    val dbApi = app.injector.instanceOf[DBApi]

    val dbNames = if(args.length == 0) dbApi.databases.map(_.name) else args.toList

    try
        // Apply evolutions
        dbNames foreach (dbName => {
          try {
            Logger.info(s"Applying evolutions for database $dbName")
            OfflineEvolutions.applyScript(
              appPath = new java.io.File("."),
              classloader = this.getClass.getClassLoader,
              dbApi = dbApi,
              dbName = dbName,
              autocommit = true
            )
          } catch {
            case e: java.sql.SQLException =>
              Logger.error(s"Unable to apply evolutions for database $dbName -- skipping: " + e.getMessage)
          }
        })
    finally app.stop()
  }
}