Skip to content

Instantly share code, notes, and snippets.

@k4200
Created May 9, 2014 07:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save k4200/e1364175f8feead34a3d to your computer and use it in GitHub Desktop.
Save k4200/e1364175f8feead34a3d to your computer and use it in GitHub Desktop.
import java.io.File
import play.api._
import play.api.Application
import play.api.db.slick.Database
import scala.slick.model.codegen.SourceCodeGenerator
import scala.slick.jdbc.meta.createModel
/**
*/
object PlaySlickCodeGenerator {
def main(args: Array[String]) = {
try {
run(outputDir = args(0), pkg = args(1))
} catch {
case ex: Throwable => Logger.error("Could not generate code: " + ex.getMessage)
} finally {
Play.stop()
}
}
private def run(outputDir: String, pkg: String) = {
val cl = Thread.currentThread().getContextClassLoader
// start fake application using in-memory database
implicit val mainApp = FakeApplication(
path = new File(".").getCanonicalFile,
classloader = cl)
Play.start(mainApp)
// read database configuration
val databaseNames = mainApp.configuration.getConfig("db").toSeq.flatMap(_.subKeys)
val databaseName = databaseNames.headOption.getOrElse(throw new RuntimeException("Could not read db.* config."))
if (databaseName.length == 0)
throw new IllegalArgumentException("No database name found in configuration")
val db = Database(databaseName)
// get list of tables for which code will be generated
// also, we exclude the play evolutions table
val excludedTables = Seq("play_evolutions", "schema_version")
val model = db.withSession{
implicit session =>
val tables = db.driver.getTables.list.filterNot(t => excludedTables contains t.name.name)
Logger.info("tables => " + tables)
createModel( tables, db.driver )
}
// generate slick db code
val codegen = new SourceCodeGenerator(model)
codegen.writeToFile(
profile = "scala.slick.driver." + db.driver.profile.toString,
folder = outputDir,
pkg = pkg,
container = "Tables",
fileName = "Tables.scala")
Play.stop()
}
}
/** Fake application needed for running evolutions outside normal Play app */
case class FakeApplication(
override val path: java.io.File = new java.io.File("."),
override val classloader : ClassLoader = classOf[FakeApplication].getClassLoader,
val additionalConfiguration: Map[String, _ <: Any] = Map.empty) extends {
override val sources = None
override val mode = play.api.Mode.Test
} with Application with WithDefaultConfiguration with WithDefaultGlobal with WithDefaultPlugins {
override def configuration =
super.configuration ++ play.api.Configuration.from(additionalConfiguration)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment