/play-slick-forklift-example

An example of doing database migration using play, play-slick, and scala-forklift.

Primary LanguageScalaCreative Commons Zero v1.0 UniversalCC0-1.0

Use Play, Slick, and Forklift to do Database Migration

Project Structure

In app directory you can find the code for the web application written in Play Scala. This application simply fetches the names stored in a h2 database and list them on the webpage, as you can see in app/controllers/Application.scala:

class Application @Inject()(dbConfigProvider: DatabaseConfigProvider)
    extends Controller {
  val dbConfig = dbConfigProvider.get[JdbcProfile]

  def index = Action.async { implicit request =>
    val resultingUsers: Future[Seq[UsersRow]] = dbConfig.db.run(Users.result)
    resultingUsers.map(users => Ok(views.html.index(users)))
  }
}

The migrations directory stores all the migration files. You can find three already written migration files in migrations/src_migrations/main/scala/(namely 1.scala, 2.scala, 3.scala). 1.scala is written in plain SQL queries, 2.scala is written with type-safe Slick queries, and 3.scala is written with slick-migration-api.

The generated_code directory stores all the code generated by Slick code generator. This directory will store the generated code for every version of the database.

In the migration_manager directory you can find the code to manage the migration files. This is where you want to look for help when things go wrong with the generated code which makes you unable to compile the application or migrations.

How to Play with this Demo?

Make sure you have sbt installed. Enter sbt in the project root to enter sbt interactive shell. You can use app/compile or app/run to compile or run the application but since the UsersRow and Users are not yet generated you will certainly get a type error.

Let's apply the migrations. First, enter mg init to initialize the database. After the database has been initialized you can use ~mg migrate to apply your migrations one by one. Once there are no migrations to be applied (no response from the console) you can enter enter to interrupt the command. The ~mg migrate command will apply all the migration files, and generate the corresponding schema code after each migration. The whole process is automatic so you can try app/run immediately after the command finished.

For more details about Scala Forklift, please refer to https://github.com/lastland/scala-forklift/blob/develop/example/README.markdown

References

Play Framework: https://github.com/playframework/playframework

Play Slick: https://github.com/playframework/play-slick

Scala Forklift: https://github.com/lastland/scala-forklift

Scala Forklift Example: https://github.com/lastland/scala-forklift/tree/develop/example