Last active
April 13, 2018 17:12
-
-
Save matanox/512fb33d67e7ddd7eb46 to your computer and use it in GitHub Desktop.
SBT task for slick code generation from a live database
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// SBT task for slick code generation for a live database | |
// ====================================================== | |
// | |
// This sbt task will generate slick scala classes to match your (MySQL) database schema, | |
// which will allow you to use the database through slick, in your scala application. | |
// | |
// Usage: Review all ? symbols and comments below, to adapt to your system. Embed in build.sbt. | |
// Make sure the database is up. Run: sbt slickGenerate | |
// In your scala application, import the resulting scala file | |
// | |
// Tested on Ubuntu, sbt 0.13.6, 3.0.0-RC2. Ugly code style like all build.sbt. | |
// | |
libraryDependencies += "com.typesafe.slick" %% "slick-codegen" % "3.0.0-RC3" | |
lazy val slickGenerate = taskKey[Seq[File]]("slick code generation from an existing database") | |
slickGenerate := { | |
import java.io.File | |
val dbName = ??? | |
val userName = ??? | |
val password = ??? | |
val url = s"jdbc:mysql://localhost:3306/$dbName" // adapt as necessary to your system | |
val jdbcDriver = "com.mysql.jdbc.Driver" // replace if not MySQL | |
val slickDriver = "slick.driver.MySQLDriver" // replace if not MySQL | |
val resultRelativeDir = ??? // directory to create output scala slick definitions at | |
val targetPackageName = ??? // package name to give it | |
val resultFilePath = s"$resultRelativeDir/$targetPackageName/Tables.scala" // override the name if you like | |
val backupFilePath = s"$resultRelativeDir/$targetPackageName/Tables.scala.auto-backup" // override the name if you like | |
val format = scala.Console.BLUE + scala.Console.BOLD | |
println(format + s"Backing up existing slick mappings source to: file://${baseDirectory.value}/$backupFilePath") | |
println(format + s"About to auto-generate slick mappings source from database schema at $url...") | |
sbt.IO.copyFile(new File(resultFilePath), new File(backupFilePath)) | |
(runner in Compile).value.run("slick.codegen.SourceCodeGenerator", (dependencyClasspath in Compile).value.files, Array(slickDriver, jdbcDriver, url, resultRelativeDir, targetPackageName, userName, password), streams.value.log) | |
println(format + s"Result: file://${baseDirectory.value}/$resultFilePath" + scala.Console.RESET) | |
val diff = (s"diff -u $resultFilePath $backupFilePath" #| "colordiff").!! | |
println(scala.Console.BLUE + s"Changes compared to previous output file, follow, if any.\n\n $diff") | |
Seq(file(resultFilePath)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks :)