Skip to content

Instantly share code, notes, and snippets.

@koizuss
Last active August 12, 2016 12:46
Show Gist options
  • Save koizuss/cc00b59087b8e1f74f66c6cb69e63f26 to your computer and use it in GitHub Desktop.
Save koizuss/cc00b59087b8e1f74f66c6cb69e63f26 to your computer and use it in GitHub Desktop.
Slick (play-slick) でクエリの共有 ref: http://qiita.com/koizuss@github/items/7e5cc8a566736b056e29
package repositories
import javax.inject.Inject
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import play.api.db.slick.{DatabaseConfigProvider, HasDatabaseConfigProvider}
import com.google.inject.ImplementedBy
import models.Tables
import models.Tables._
import slick.driver.JdbcProfile
@ImplementedBy(classOf[FooRepository])
trait FooRepositoryLike
extends HasDatabaseConfigProvider[JdbcProfile] {
def findById(id: String): Future[Option[(FooRow, BarRow)]]
}
class FooRepository @Inject()(protected val dbConfigProvider: DatabaseConfigProvider)
extends FooRepositoryLike {
import driver.api._
def findById(id: String): Future[Option[(FooRow, BarRow)]] = {
val query = for {
f <- Foo if f.id === id.bind
b <- Bar if b.id === f.barId
// and more...
} yield (f, b)
db.run(query.result.headOption)
}
}
class FooRepository @Inject()(protected val dbConfigProvider: DatabaseConfigProvider)
extends FooRepositoryLike {
import driver.api._
/*
* 切り出したクエリ
*/
lazy val fooQuery = for {
f <- Foo if f.id === id.bind
b <- Bar if b.id === f.barId
// and more...
} yield (f, b)
def findById(id: String): Future[Option[(FooRow, BarRow)]] =
db.run(fooQuery.filter(_._1.id === id.bind).result.headOption)
def findAll(): Future[Seq[(FooRow, BarRow)]] =
db.run(fooQuery.sortBy(_._1.createAt.desc).result)
}
/*
* 切り出したクエリ
*/
trait FooQuery
extends HasDatabaseConfigProvider[JdbcProfile] {
import driver.api._
lazy val fooQuery = for {
f <- Foo if f.id === id.bind
b <- Bar if b.id === f.barId
// and more...
} yield (f, b)
}
class FooRepository @Inject()(protected val dbConfigProvider: DatabaseConfigProvider)
extends FooRepositoryLike with FooQuery {
import driver.api._
def findById(id: String): Future[Option[(FooRow, BarRow)]] =
db.run(fooQuery.filter(_._1.id === id.bind).result.headOption)
def findAll(): Future[Seq[(FooRow, BarRow)]] =
db.run(fooQuery.sortBy(_._1.createAt.desc).result)
}
// ----------------
class BazRepository @Inject()(protected val dbConfigProvider: DatabaseConfigProvider)
extends BazRepositoryLike with FooQuery {
import driver.api._
def findById(id: String): Future[Option[(BazRow, FooRow, BarRow)]] = {
val query = for {
bz <- Baz if bz.id === id.bind
(f, b) <- fooQuery if f.id === bz.fooId
} yield (bz, f, b)
db.run(query.result.headOption)
}
}
trait FooQuery
extends HasDatabaseConfigProvider[JdbcProfile] {
import driver.api._
// ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment