diff --git a/play-scala-isolated-slick-example/.gitignore b/play-scala-isolated-slick-example/.gitignore new file mode 100644 index 000000000..4c15fc12d --- /dev/null +++ b/play-scala-isolated-slick-example/.gitignore @@ -0,0 +1,38 @@ +/.idea + +modules/play/logs/ + +# sbt specific +.cache +.history +.lib/ +dist/* +target/ +lib_managed/ +src_managed/ +project/boot/ +project/plugins/project/ + +# Scala-IDE specific +.scala_dependencies +.worksheet + +### PlayFramework template +# Ignore Play! working directory # +bin/ +/db +.eclipse +/lib/ +/logs/ +/project/project +/project/target +/target +tmp/ +test-result +server.pid +*.iml +*.eml +/dist/ + + +test.mv.db diff --git a/play-scala-isolated-slick-example/.mergify.yml b/play-scala-isolated-slick-example/.mergify.yml new file mode 100644 index 000000000..32f8689ae --- /dev/null +++ b/play-scala-isolated-slick-example/.mergify.yml @@ -0,0 +1,27 @@ +pull_request_rules: + - name: automatic merge on CI success require review + conditions: + - status-success=Travis CI - Pull Request + - "#approved-reviews-by>=1" + - "#changes-requested-reviews-by=0" + - label!=block-merge + actions: + merge: + method: squash + strict: smart + + - name: automatic merge on CI success for TemplateControl + conditions: + - status-success=Travis CI - Pull Request + - label=merge-when-green + - label!=block-merge + actions: + merge: + method: squash + strict: smart + + - name: delete branch after merge + conditions: + - merged + actions: + delete_head_branch: {} diff --git a/play-scala-isolated-slick-example/.travis.yml b/play-scala-isolated-slick-example/.travis.yml new file mode 100644 index 000000000..1e8c0e7c4 --- /dev/null +++ b/play-scala-isolated-slick-example/.travis.yml @@ -0,0 +1,50 @@ +language: scala +scala: + - 2.12.8 + +before_install: + - curl -sL https://github.com/shyiko/jabba/raw/master/install.sh | bash && . ~/.jabba/jabba.sh + +env: + global: + - JABBA_HOME=$HOME/.jabba + matrix: + # There is no concise way to specify multi-dimensional build matrix: + # https://github.com/travis-ci/travis-ci/issues/1519 + - SCRIPT=scripts/test-sbt TRAVIS_JDK=adopt@1.8.192-12 + - SCRIPT=scripts/test-sbt TRAVIS_JDK=adopt@1.11.0-1 + - SCRIPT=scripts/test-gradle TRAVIS_JDK=adopt@1.8.192-12 + - SCRIPT=scripts/test-gradle TRAVIS_JDK=adopt@1.11.0-1 + +# Exclude some combinations from build matrix. See: +# https://docs.travis-ci.com/user/customizing-the-build/#Build-Matrix +matrix: + fast_finish: true + allow_failures: + # Current release of Gradle still does not supports Play 2.7.x releases + # As soon as there is a release of Gradle that fixes that, we can then + # remove this allowed failure. + - env: SCRIPT=scripts/test-gradle TRAVIS_JDK=adopt@1.8.192-12 + - env: SCRIPT=scripts/test-gradle TRAVIS_JDK=adopt@1.11.0-1 + # Java 11 is still not fully supported. It is good that we are already + # testing our sample applications to better discover possible problems + # but we can allow failures here too. + - env: SCRIPT=scripts/test-sbt TRAVIS_JDK=adopt@1.11.0-1 + +install: + - $JABBA_HOME/bin/jabba install $TRAVIS_JDK + - unset _JAVA_OPTIONS + - export JAVA_HOME="$JABBA_HOME/jdk/$TRAVIS_JDK" && export PATH="$JAVA_HOME/bin:$PATH" && java -Xmx32m -version + +script: + - $SCRIPT + +before_cache: + - find $HOME/.ivy2 -name "ivydata-*.properties" -delete + - find $HOME/.sbt -name "*.lock" -delete + +cache: + directories: + - "$HOME/.ivy2/cache" + - "$HOME/.gradle/caches" + - "$HOME/.jabba/jdk" diff --git a/play-scala-isolated-slick-example/LICENSE b/play-scala-isolated-slick-example/LICENSE new file mode 100644 index 000000000..670154e35 --- /dev/null +++ b/play-scala-isolated-slick-example/LICENSE @@ -0,0 +1,116 @@ +CC0 1.0 Universal + +Statement of Purpose + +The laws of most jurisdictions throughout the world automatically confer +exclusive Copyright and Related Rights (defined below) upon the creator and +subsequent owner(s) (each and all, an "owner") of an original work of +authorship and/or a database (each, a "Work"). + +Certain owners wish to permanently relinquish those rights to a Work for the +purpose of contributing to a commons of creative, cultural and scientific +works ("Commons") that the public can reliably and without fear of later +claims of infringement build upon, modify, incorporate in other works, reuse +and redistribute as freely as possible in any form whatsoever and for any +purposes, including without limitation commercial purposes. These owners may +contribute to the Commons to promote the ideal of a free culture and the +further production of creative, cultural and scientific works, or to gain +reputation or greater distribution for their Work in part through the use and +efforts of others. + +For these and/or other purposes and motivations, and without any expectation +of additional consideration or compensation, the person associating CC0 with a +Work (the "Affirmer"), to the extent that he or she is an owner of Copyright +and Related Rights in the Work, voluntarily elects to apply CC0 to the Work +and publicly distribute the Work under its terms, with knowledge of his or her +Copyright and Related Rights in the Work and the meaning and intended legal +effect of CC0 on those rights. + +1. Copyright and Related Rights. A Work made available under CC0 may be +protected by copyright and related or neighboring rights ("Copyright and +Related Rights"). Copyright and Related Rights include, but are not limited +to, the following: + + i. the right to reproduce, adapt, distribute, perform, display, communicate, + and translate a Work; + + ii. moral rights retained by the original author(s) and/or performer(s); + + iii. publicity and privacy rights pertaining to a person's image or likeness + depicted in a Work; + + iv. rights protecting against unfair competition in regards to a Work, + subject to the limitations in paragraph 4(a), below; + + v. rights protecting the extraction, dissemination, use and reuse of data in + a Work; + + vi. database rights (such as those arising under Directive 96/9/EC of the + European Parliament and of the Council of 11 March 1996 on the legal + protection of databases, and under any national implementation thereof, + including any amended or successor version of such directive); and + + vii. other similar, equivalent or corresponding rights throughout the world + based on applicable law or treaty, and any national implementations thereof. + +2. Waiver. To the greatest extent permitted by, but not in contravention of, +applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and +unconditionally waives, abandons, and surrenders all of Affirmer's Copyright +and Related Rights and associated claims and causes of action, whether now +known or unknown (including existing as well as future claims and causes of +action), in the Work (i) in all territories worldwide, (ii) for the maximum +duration provided by applicable law or treaty (including future time +extensions), (iii) in any current or future medium and for any number of +copies, and (iv) for any purpose whatsoever, including without limitation +commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes +the Waiver for the benefit of each member of the public at large and to the +detriment of Affirmer's heirs and successors, fully intending that such Waiver +shall not be subject to revocation, rescission, cancellation, termination, or +any other legal or equitable action to disrupt the quiet enjoyment of the Work +by the public as contemplated by Affirmer's express Statement of Purpose. + +3. Public License Fallback. Should any part of the Waiver for any reason be +judged legally invalid or ineffective under applicable law, then the Waiver +shall be preserved to the maximum extent permitted taking into account +Affirmer's express Statement of Purpose. In addition, to the extent the Waiver +is so judged Affirmer hereby grants to each affected person a royalty-free, +non transferable, non sublicensable, non exclusive, irrevocable and +unconditional license to exercise Affirmer's Copyright and Related Rights in +the Work (i) in all territories worldwide, (ii) for the maximum duration +provided by applicable law or treaty (including future time extensions), (iii) +in any current or future medium and for any number of copies, and (iv) for any +purpose whatsoever, including without limitation commercial, advertising or +promotional purposes (the "License"). The License shall be deemed effective as +of the date CC0 was applied by Affirmer to the Work. Should any part of the +License for any reason be judged legally invalid or ineffective under +applicable law, such partial invalidity or ineffectiveness shall not +invalidate the remainder of the License, and in such case Affirmer hereby +affirms that he or she will not (i) exercise any of his or her remaining +Copyright and Related Rights in the Work or (ii) assert any associated claims +and causes of action with respect to the Work, in either case contrary to +Affirmer's express Statement of Purpose. + +4. Limitations and Disclaimers. + + a. No trademark or patent rights held by Affirmer are waived, abandoned, + surrendered, licensed or otherwise affected by this document. + + b. Affirmer offers the Work as-is and makes no representations or warranties + of any kind concerning the Work, express, implied, statutory or otherwise, + including without limitation warranties of title, merchantability, fitness + for a particular purpose, non infringement, or the absence of latent or + other defects, accuracy, or the present or absence of errors, whether or not + discoverable, all to the greatest extent permissible under applicable law. + + c. Affirmer disclaims responsibility for clearing rights of other persons + that may apply to the Work or any use thereof, including without limitation + any person's Copyright and Related Rights in the Work. Further, Affirmer + disclaims responsibility for obtaining any necessary consents, permissions + or other rights required for any use of the Work. + + d. Affirmer understands and acknowledges that Creative Commons is not a + party to this document and has no duty or obligation with respect to this + CC0 or use of the Work. + +For more information, please see + diff --git a/play-scala-isolated-slick-example/NOTICE b/play-scala-isolated-slick-example/NOTICE new file mode 100644 index 000000000..6d6c034d3 --- /dev/null +++ b/play-scala-isolated-slick-example/NOTICE @@ -0,0 +1,8 @@ +Written by Lightbend + +To the extent possible under law, the author(s) have dedicated all copyright and +related and neighboring rights to this software to the public domain worldwide. +This software is distributed without any warranty. + +You should have received a copy of the CC0 Public Domain Dedication along with +this software. If not, see . diff --git a/play-scala-isolated-slick-example/README.md b/play-scala-isolated-slick-example/README.md new file mode 100644 index 000000000..b61f8dadd --- /dev/null +++ b/play-scala-isolated-slick-example/README.md @@ -0,0 +1,45 @@ +# Play with Slick 3.1 + +[![Build Status](https://travis-ci.org/playframework/play-scala-isolated-slick-example.svg?branch=2.6.x)](https://travis-ci.org/playframework/play-scala-isolated-slick-example) + +This project shows Play working with Slick. + +This project is configured to keep all the modules self-contained. + +* Slick is isolated from Play, not using play-slick. +* Database migration is done using [Flyway](https://flywaydb.org/), not Play Evolutions. +* Slick's classes are auto-generated following database migration. + +## Database Migration + +```bash +sbt flyway/flywayMigrate +``` + +## Slick Code Generation + +You will need to run the flywayMigrate task first, and then you will be able to generate tables using sbt-codegen. + +```bash +sbt slickCodegen +``` + +## Testing + +You can run functional tests against an in memory database and Slick easily with Play from a clean slate: + +```bash +sbt clean flyway/flywayMigrate slickCodegen compile test +``` + +## Running + +To run the project, start up Play: + +```bash +sbt run +``` + +And that's it! + +Now go to , and you will see the list of users in the database. diff --git a/play-scala-isolated-slick-example/app/Module.scala b/play-scala-isolated-slick-example/app/Module.scala new file mode 100644 index 000000000..b4d328b02 --- /dev/null +++ b/play-scala-isolated-slick-example/app/Module.scala @@ -0,0 +1,37 @@ +import javax.inject.{Inject, Provider, Singleton} + +import com.example.user.UserDAO +import com.example.user.slick.SlickUserDAO +import com.google.inject.AbstractModule +import com.typesafe.config.Config +import play.api.inject.ApplicationLifecycle +import play.api.{Configuration, Environment} +import slick.jdbc.JdbcBackend.Database + +import scala.concurrent.Future + +/** + * This module handles the bindings for the API to the Slick implementation. + * + * https://www.playframework.com/documentation/latest/ScalaDependencyInjection#Programmatic-bindings + */ +class Module(environment: Environment, + configuration: Configuration) extends AbstractModule { + override def configure(): Unit = { + bind(classOf[Database]).toProvider(classOf[DatabaseProvider]) + bind(classOf[UserDAO]).to(classOf[SlickUserDAO]) + bind(classOf[UserDAOCloseHook]).asEagerSingleton() + } +} + +@Singleton +class DatabaseProvider @Inject() (config: Config) extends Provider[Database] { + lazy val get = Database.forConfig("myapp.database", config) +} + +/** Closes database connections safely. Important on dev restart. */ +class UserDAOCloseHook @Inject()(dao: UserDAO, lifecycle: ApplicationLifecycle) { + lifecycle.addStopHook { () => + Future.successful(dao.close()) + } +} diff --git a/play-scala-isolated-slick-example/app/controllers/HomeController.scala b/play-scala-isolated-slick-example/app/controllers/HomeController.scala new file mode 100644 index 000000000..9f82b47e3 --- /dev/null +++ b/play-scala-isolated-slick-example/app/controllers/HomeController.scala @@ -0,0 +1,21 @@ +package controllers + +import javax.inject.{Inject, Singleton} + +import com.example.user.UserDAO +import play.api.mvc._ + +import scala.concurrent.ExecutionContext + +@Singleton +class HomeController @Inject() (userDAO: UserDAO, cc: ControllerComponents) + (implicit ec: ExecutionContext) + extends AbstractController(cc) { + + def index = Action.async { implicit request => + userDAO.all.map { users => + Ok(views.html.index(users)) + } + } + +} diff --git a/play-scala-isolated-slick-example/app/views/index.scala.html b/play-scala-isolated-slick-example/app/views/index.scala.html new file mode 100644 index 000000000..6a5dbe123 --- /dev/null +++ b/play-scala-isolated-slick-example/app/views/index.scala.html @@ -0,0 +1,22 @@ +@(users: Seq[User]) + +@main("Title Page") { +

Users

+ + + + + + + + + @for(user <- users){ + + + + + + + } +
IdEmailCreated AtUpdated At
@user.id@user.email@user.createdAt@user.updatedAt
+} diff --git a/play-scala-isolated-slick-example/app/views/main.scala.html b/play-scala-isolated-slick-example/app/views/main.scala.html new file mode 100644 index 000000000..aff0eff1d --- /dev/null +++ b/play-scala-isolated-slick-example/app/views/main.scala.html @@ -0,0 +1,15 @@ +@(title: String)(content: Html) + + + + + + @title + + + + + + @content + + diff --git a/play-scala-isolated-slick-example/build.sbt b/play-scala-isolated-slick-example/build.sbt new file mode 100644 index 000000000..1b61cfcd1 --- /dev/null +++ b/play-scala-isolated-slick-example/build.sbt @@ -0,0 +1,35 @@ +name := """play-isolated-slick""" + +version := "1.1-SNAPSHOT" + +scalaVersion := "2.12.8" + +crossScalaVersions := Seq("2.11.12", "2.12.6") + +lazy val flyway = (project in file("modules/flyway")) + .enablePlugins(FlywayPlugin) + +lazy val api = (project in file("modules/api")) + .settings(Common.projectSettings) + +lazy val slick = (project in file("modules/slick")) + .settings(Common.projectSettings) + .aggregate(api) + .dependsOn(api) + +lazy val root = (project in file(".")) + .enablePlugins(PlayScala) + .aggregate(slick) + .dependsOn(slick) + +TwirlKeys.templateImports += "com.example.user.User" + +libraryDependencies += guice +libraryDependencies += "com.h2database" % "h2" % "1.4.197" + +// Automatic database migration available in testing +fork in Test := true +libraryDependencies += "org.flywaydb" % "flyway-core" % "5.1.1" +libraryDependencies += "com.typesafe.play" %% "play-ahc-ws" % "2.6.15" % Test +libraryDependencies += "org.scalatestplus.play" %% "scalatestplus-play" % "3.1.2" % Test + diff --git a/play-scala-isolated-slick-example/conf/logback.xml b/play-scala-isolated-slick-example/conf/logback.xml new file mode 100644 index 000000000..de7e962a3 --- /dev/null +++ b/play-scala-isolated-slick-example/conf/logback.xml @@ -0,0 +1,39 @@ + + + + + + ${application.home:-.}/logs/application.log + + %date [%level] from %logger in %thread - %message%n%xException + + + + + + %coloredLevel %logger{15} - %message%n%xException{10} + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/play-scala-isolated-slick-example/conf/routes b/play-scala-isolated-slick-example/conf/routes new file mode 100644 index 000000000..f59f0a3b1 --- /dev/null +++ b/play-scala-isolated-slick-example/conf/routes @@ -0,0 +1,9 @@ +# Routes +# This file defines all application routes (Higher priority routes first) +# ~~~~ + +# Home page +GET / controllers.HomeController.index + +# Map static resources from the /public folder to the /assets URL path +GET /assets/*file controllers.Assets.versioned(path="/public", file: Asset) diff --git a/play-scala-isolated-slick-example/modules/api/src/main/scala/com/example/user/UserDAO.scala b/play-scala-isolated-slick-example/modules/api/src/main/scala/com/example/user/UserDAO.scala new file mode 100644 index 000000000..6bc67e021 --- /dev/null +++ b/play-scala-isolated-slick-example/modules/api/src/main/scala/com/example/user/UserDAO.scala @@ -0,0 +1,28 @@ +package com.example.user + +import org.joda.time.DateTime + +import scala.concurrent.Future + +/** + * An implementation dependent DAO. This could be implemented by Slick, Cassandra, or a REST API. + */ +trait UserDAO { + + def lookup(id: String): Future[Option[User]] + + def all: Future[Seq[User]] + + def update(user: User): Future[Int] + + def delete(id: String): Future[Int] + + def create(user: User): Future[Int] + + def close(): Future[Unit] +} + +/** + * Implementation independent aggregate root. + */ +case class User(id: String, email: String, createdAt: DateTime, updatedAt: Option[DateTime]) diff --git a/play-scala-isolated-slick-example/modules/flyway/build.sbt b/play-scala-isolated-slick-example/modules/flyway/build.sbt new file mode 100644 index 000000000..0bcbf9b45 --- /dev/null +++ b/play-scala-isolated-slick-example/modules/flyway/build.sbt @@ -0,0 +1,19 @@ +// Database Migrations: +// run with "sbt flywayMigrate" +// http://flywaydb.org/getstarted/firststeps/sbt.html + +//$ export DB_DEFAULT_URL="jdbc:h2:/tmp/example.db" +//$ export DB_DEFAULT_USER="sa" +//$ export DB_DEFAULT_PASSWORD="" + +libraryDependencies += "org.flywaydb" % "flyway-core" % "5.0.3" + +lazy val databaseUrl = sys.env.getOrElse("DB_DEFAULT_URL", "jdbc:h2:./test") +lazy val databaseUser = sys.env.getOrElse("DB_DEFAULT_USER", "sa") +lazy val databasePassword = sys.env.getOrElse("DB_DEFAULT_PASSWORD", "") + +flywayLocations := Seq("classpath:db/migration") + +flywayUrl := databaseUrl +flywayUser := databaseUser +flywayPassword := databasePassword diff --git a/play-scala-isolated-slick-example/modules/flyway/src/main/resources/db/migration/V20150409112518__create_users_table.sql b/play-scala-isolated-slick-example/modules/flyway/src/main/resources/db/migration/V20150409112518__create_users_table.sql new file mode 100644 index 000000000..8ac824164 --- /dev/null +++ b/play-scala-isolated-slick-example/modules/flyway/src/main/resources/db/migration/V20150409112518__create_users_table.sql @@ -0,0 +1,6 @@ +create table "users" ( + "id" VARCHAR(255) PRIMARY KEY NOT NULL, + "email" VARCHAR(1024) NOT NULL, + created_at TIMESTAMP NOT NULL, + updated_at TIMESTAMP NULL +); diff --git a/play-scala-isolated-slick-example/modules/flyway/src/main/resources/db/migration/V20150409131208__add_user.sql b/play-scala-isolated-slick-example/modules/flyway/src/main/resources/db/migration/V20150409131208__add_user.sql new file mode 100644 index 000000000..7113f28ab --- /dev/null +++ b/play-scala-isolated-slick-example/modules/flyway/src/main/resources/db/migration/V20150409131208__add_user.sql @@ -0,0 +1,6 @@ +INSERT INTO "users" VALUES ( + 'd074bce8-a8ca-49ec-9225-a50ffe83dc2f', + 'myuser@example.com', + (TIMESTAMP '2013-03-26T17:50:06Z'), + (TIMESTAMP '2013-03-26T17:50:06Z') +); diff --git a/play-scala-isolated-slick-example/modules/slick/build.sbt b/play-scala-isolated-slick-example/modules/slick/build.sbt new file mode 100644 index 000000000..bac898945 --- /dev/null +++ b/play-scala-isolated-slick-example/modules/slick/build.sbt @@ -0,0 +1,40 @@ +import slick.codegen.SourceCodeGenerator +import slick.{ model => m } + +libraryDependencies ++= Seq( + "com.zaxxer" % "HikariCP" % "2.7.9", + "com.typesafe.slick" %% "slick" % "3.2.3", + "com.typesafe.slick" %% "slick-hikaricp" % "3.2.3", + "com.github.tototoshi" %% "slick-joda-mapper" % "2.3.0" +) + +lazy val databaseUrl = sys.env.getOrElse("DB_DEFAULT_URL", "jdbc:h2:./test") +lazy val databaseUser = sys.env.getOrElse("DB_DEFAULT_USER", "sa") +lazy val databasePassword = sys.env.getOrElse("DB_DEFAULT_PASSWORD", "") + +slickCodegenSettings +slickCodegenDatabaseUrl := databaseUrl +slickCodegenDatabaseUser := databaseUser +slickCodegenDatabasePassword := databasePassword +slickCodegenDriver := slick.driver.H2Driver +slickCodegenJdbcDriver := "org.h2.Driver" +slickCodegenOutputPackage := "com.example.user.slick" +slickCodegenExcludedTables := Seq("schema_version") + +slickCodegenCodeGenerator := { (model: m.Model) => + new SourceCodeGenerator(model) { + override def code = + "import com.github.tototoshi.slick.H2JodaSupport._\n" + "import org.joda.time.DateTime\n" + super.code + override def Table = new Table(_) { + override def Column = new Column(_) { + override def rawType = model.tpe match { + case "java.sql.Timestamp" => "DateTime" // kill j.s.Timestamp + case _ => + super.rawType + } + } + } + } +} + +sourceGenerators in Compile += slickCodegen.taskValue diff --git a/play-scala-isolated-slick-example/modules/slick/src/main/resources/application.conf b/play-scala-isolated-slick-example/modules/slick/src/main/resources/application.conf new file mode 100644 index 000000000..43eb52cc0 --- /dev/null +++ b/play-scala-isolated-slick-example/modules/slick/src/main/resources/application.conf @@ -0,0 +1,28 @@ + +myapp = { + database = { + driver = org.h2.Driver + url = "jdbc:h2:./test" + user = "sa" + password = "" + + // The number of threads determines how many things you can *run* in parallel + // the number of connections determines you many things you can *keep in memory* at the same time + // on the database server. + // numThreads = (core_count (hyperthreading included)) + numThreads = 4 + + // queueSize = ((core_count * 2) + effective_spindle_count) + // on a MBP 13, this is 2 cores * 2 (hyperthreading not included) + 1 hard disk + queueSize = 5 + + // https://blog.knoldus.com/2016/01/01/best-practices-for-using-slick-on-production/ + // make larger than numThreads + queueSize + maxConnections = 10 + + connectionTimeout = 5000 + validationTimeout = 5000 + } +} + + diff --git a/play-scala-isolated-slick-example/modules/slick/src/main/scala/com/example/user/slick/SlickUserDAO.scala b/play-scala-isolated-slick-example/modules/slick/src/main/scala/com/example/user/slick/SlickUserDAO.scala new file mode 100644 index 000000000..1060efaa3 --- /dev/null +++ b/play-scala-isolated-slick-example/modules/slick/src/main/scala/com/example/user/slick/SlickUserDAO.scala @@ -0,0 +1,67 @@ +package com.example.user.slick + +import javax.inject.{Inject, Singleton} + +import org.joda.time.DateTime +import slick.jdbc.JdbcProfile +import slick.jdbc.JdbcBackend.Database +import com.example.user._ + +import scala.concurrent.{ExecutionContext, Future} +import scala.language.implicitConversions + +/** + * A User DAO implemented with Slick, leveraging Slick code gen. + * + * Note that you must run "flyway/flywayMigrate" before "compile" here. + * + * @param db the slick database that this user DAO is using internally, bound through Module. + * @param ec a CPU bound execution context. Slick manages blocking JDBC calls with its + * own internal thread pool, so Play's default execution context is fine here. + */ +@Singleton +class SlickUserDAO @Inject()(db: Database)(implicit ec: ExecutionContext) extends UserDAO with Tables { + + override val profile: JdbcProfile = _root_.slick.jdbc.H2Profile + + import profile.api._ + + private val queryById = Compiled( + (id: Rep[String]) => Users.filter(_.id === id)) + + def lookup(id: String): Future[Option[User]] = { + val f: Future[Option[UsersRow]] = db.run(queryById(id).result.headOption) + f.map(maybeRow => maybeRow.map(usersRowToUser)) + } + + def all: Future[Seq[User]] = { + val f = db.run(Users.result) + f.map(seq => seq.map(usersRowToUser)) + } + + def update(user: User): Future[Int] = { + db.run(queryById(user.id).update(userToUsersRow(user))) + } + + def delete(id: String): Future[Int] = { + db.run(queryById(id).delete) + } + + def create(user: User): Future[Int] = { + db.run( + Users += userToUsersRow(user.copy(createdAt = DateTime.now())) + ) + } + + def close(): Future[Unit] = { + Future.successful(db.close()) + } + + private def userToUsersRow(user: User): UsersRow = { + UsersRow(user.id, user.email, user.createdAt, user.updatedAt) + } + + private def usersRowToUser(usersRow: UsersRow): User = { + User(usersRow.id, usersRow.email, usersRow.createdAt, usersRow.updatedAt) + } +} diff --git a/play-scala-isolated-slick-example/project/Build.scala b/play-scala-isolated-slick-example/project/Build.scala new file mode 100644 index 000000000..9e5f7fba3 --- /dev/null +++ b/play-scala-isolated-slick-example/project/Build.scala @@ -0,0 +1,30 @@ +import sbt.Keys._ +import sbt.{Resolver, _} + +object Common { + + def projectSettings = Seq( + scalaVersion := "2.12.6", + javacOptions ++= Seq("-source", "1.8", "-target", "1.8"), + scalacOptions ++= Seq( + "-encoding", "UTF-8", // yes, this is 2 args + "-deprecation", + "-feature", + "-unchecked", + "-Xlint", + "-Yno-adapted-args", + "-Ywarn-numeric-widen" + ), + resolvers ++= Seq( + "scalaz-bintray" at "http://dl.bintray.com/scalaz/releases", + Resolver.sonatypeRepo("releases"), + Resolver.sonatypeRepo("snapshots")), + libraryDependencies ++= Seq( + "javax.inject" % "javax.inject" % "1", + "joda-time" % "joda-time" % "2.9.9", + "org.joda" % "joda-convert" % "1.9.2", + "com.google.inject" % "guice" % "4.1.0" + ), + scalacOptions in Test ++= Seq("-Yrangepos") + ) +} diff --git a/play-scala-isolated-slick-example/project/build.properties b/play-scala-isolated-slick-example/project/build.properties new file mode 100644 index 000000000..c0bab0494 --- /dev/null +++ b/play-scala-isolated-slick-example/project/build.properties @@ -0,0 +1 @@ +sbt.version=1.2.8 diff --git a/play-scala-isolated-slick-example/project/plugins.sbt b/play-scala-isolated-slick-example/project/plugins.sbt new file mode 100644 index 000000000..f131bb251 --- /dev/null +++ b/play-scala-isolated-slick-example/project/plugins.sbt @@ -0,0 +1,19 @@ +resolvers += "Typesafe repository" at "https://repo.typesafe.com/typesafe/releases/" + +resolvers += "Sonatype OSS Snapshots" at "https://oss.sonatype.org/content/repositories/snapshots" + +resolvers += "Flyway" at "https://flywaydb.org/repo" + +resolvers += "Flyway" at "https://davidmweber.github.io/flyway-sbt.repo" + +// Database migration +addSbtPlugin("org.flywaydb" % "flyway-sbt" % "4.2.0") + +// Slick code generation +// https://github.com/tototoshi/sbt-slick-codegen +addSbtPlugin("com.github.tototoshi" % "sbt-slick-codegen" % "1.3.0") + +libraryDependencies += "com.h2database" % "h2" % "1.4.196" + +// The Play plugin +addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.6.21") diff --git a/play-scala-isolated-slick-example/public/images/favicon.png b/play-scala-isolated-slick-example/public/images/favicon.png new file mode 100644 index 000000000..c7d92d2ae Binary files /dev/null and b/play-scala-isolated-slick-example/public/images/favicon.png differ diff --git a/play-scala-isolated-slick-example/public/javascripts/hello.js b/play-scala-isolated-slick-example/public/javascripts/hello.js new file mode 100644 index 000000000..209fbee59 --- /dev/null +++ b/play-scala-isolated-slick-example/public/javascripts/hello.js @@ -0,0 +1,3 @@ +if (window.console) { + console.log("Welcome to your Play application's JavaScript!"); +} \ No newline at end of file diff --git a/play-scala-isolated-slick-example/public/stylesheets/main.css b/play-scala-isolated-slick-example/public/stylesheets/main.css new file mode 100644 index 000000000..e69de29bb diff --git a/play-scala-isolated-slick-example/scripts/script-helper b/play-scala-isolated-slick-example/scripts/script-helper new file mode 100755 index 000000000..9a2faa643 --- /dev/null +++ b/play-scala-isolated-slick-example/scripts/script-helper @@ -0,0 +1,13 @@ +#!/usr/bin/env bash + +set -e +set -o pipefail + +java_version=$(java -version 2>&1 | java -version 2>&1 | awk -F '"' '/version/ {print $2}') + +if [[ $java_version = 1.8* ]] ; then + echo "The build is using Java 8 ($java_version). No addional JVM params needed." +else + echo "The build is using Java 9+ ($java_version). We need additional JVM parameters" + export _JAVA_OPTIONS="$_JAVA_OPTIONS --add-modules=java.xml.bind" +fi diff --git a/play-scala-isolated-slick-example/scripts/test-gradle b/play-scala-isolated-slick-example/scripts/test-gradle new file mode 100755 index 000000000..84a051a20 --- /dev/null +++ b/play-scala-isolated-slick-example/scripts/test-gradle @@ -0,0 +1,13 @@ +#!/usr/bin/env bash + +. "$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )/script-helper" + +# Using cut because TRAVIS_SCALA_VERSION is the full Scala +# version (for example 2.12.4), but Gradle expects just the +# binary version (for example 2.12) +scala_binary_version=$(echo $TRAVIS_SCALA_VERSION | cut -c1-4) + +echo "+------------------------------+" +echo "| Executing tests using Gradle |" +echo "+------------------------------+" +./gradlew -Dscala.binary.version=$scala_binary_version check -i --stacktrace diff --git a/play-scala-isolated-slick-example/scripts/test-sbt b/play-scala-isolated-slick-example/scripts/test-sbt new file mode 100755 index 000000000..95bcad236 --- /dev/null +++ b/play-scala-isolated-slick-example/scripts/test-sbt @@ -0,0 +1,8 @@ +#!/usr/bin/env bash + +. "$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )/script-helper" + +echo "+----------------------------+" +echo "| Executing tests using sbt |" +echo "+----------------------------+" +sbt ++$TRAVIS_SCALA_VERSION clean flyway/flywayMigrate slickCodegen compile test diff --git a/play-scala-isolated-slick-example/test/controller/FunctionalSpec.scala b/play-scala-isolated-slick-example/test/controller/FunctionalSpec.scala new file mode 100644 index 000000000..9e1b89f49 --- /dev/null +++ b/play-scala-isolated-slick-example/test/controller/FunctionalSpec.scala @@ -0,0 +1,21 @@ +package controller + +import org.scalatestplus.play.{BaseOneAppPerSuite, PlaySpec} +import play.api.test.FakeRequest +import play.api.test.Helpers._ + +/** + * Runs a functional test with the application, using an in memory + * database. Migrations are handled automatically by play-flyway + */ +class FunctionalSpec extends PlaySpec with BaseOneAppPerSuite with MyApplicationFactory { + + "HomeController" should { + + "work with in memory h2 database" in { + val future = route(app, FakeRequest(GET, "/")).get + contentAsString(future) must include("myuser@example.com") + } + } + +} diff --git a/play-scala-isolated-slick-example/test/controller/MyApplicationFactory.scala b/play-scala-isolated-slick-example/test/controller/MyApplicationFactory.scala new file mode 100644 index 000000000..d0e48263b --- /dev/null +++ b/play-scala-isolated-slick-example/test/controller/MyApplicationFactory.scala @@ -0,0 +1,44 @@ +package controller + +import java.util.Properties + +import com.google.inject.Inject +import org.flywaydb.core.Flyway +import org.flywaydb.core.internal.util.jdbc.DriverDataSource +import org.scalatestplus.play.FakeApplicationFactory +import play.api.inject.guice.GuiceApplicationBuilder +import play.api.inject.{Binding, Module} +import play.api.{Application, Configuration, Environment} + +/** + * Set up an application factory that runs flyways migrations on in memory database. + */ +trait MyApplicationFactory extends FakeApplicationFactory { + def fakeApplication(): Application = { + new GuiceApplicationBuilder() + .configure(Map("myapp.database.url" -> "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1")) + .bindings(new FlywayModule) + .build() + } +} + +class FlywayModule extends Module { + override def bindings(environment: Environment, configuration: Configuration): Seq[Binding[_]] = { + Seq(bind[FlywayMigrator].toSelf.eagerly() ) + } +} + +class FlywayMigrator @Inject()(env: Environment, configuration: Configuration) { + def onStart(): Unit = { + val driver = configuration.get[String]("myapp.database.driver") + val url = configuration.get[String]("myapp.database.url") + val user = configuration.get[String]("myapp.database.user") + val password = configuration.get[String]("myapp.database.password") + val flyway = new Flyway + flyway.setDataSource(new DriverDataSource(env.classLoader, driver, url, user, password, new Properties())) + flyway.setLocations("filesystem:modules/flyway/src/main/resources/db/migration") + flyway.migrate() + } + + onStart() +}