diff options
author | vlad <vlad@drivergrp.com> | 2016-12-01 21:44:31 -0800 |
---|---|---|
committer | vlad <vlad@drivergrp.com> | 2016-12-01 21:44:31 -0800 |
commit | 18f21d9438ccb39f0cd567f5a0e83cbb3427488f (patch) | |
tree | 3337819f82f87456ac757a2c53c00b8e2d419b8b /src/main/scala/xyz | |
parent | 594e292e6b1c1d0ac4f49ab14a17ef13b3181f39 (diff) | |
download | driver-core-0.9.22.tar.gz driver-core-0.9.22.tar.bz2 driver-core-0.9.22.zip |
Useful abstractions to craft DALsv0.9.22
Diffstat (limited to 'src/main/scala/xyz')
-rw-r--r-- | src/main/scala/xyz/driver/core/database.scala | 54 |
1 files changed, 53 insertions, 1 deletions
diff --git a/src/main/scala/xyz/driver/core/database.scala b/src/main/scala/xyz/driver/core/database.scala index f846b15..3f4af40 100644 --- a/src/main/scala/xyz/driver/core/database.scala +++ b/src/main/scala/xyz/driver/core/database.scala @@ -5,7 +5,8 @@ import slick.dbio.{DBIOAction, NoStream} import slick.driver.JdbcProfile import xyz.driver.core.time.Time -import scala.concurrent.Future +import scala.concurrent.{ExecutionContext, Future} +import scalaz.Monad object database { @@ -56,4 +57,55 @@ object database { def createTables(): Future[Unit] = Future.successful(()) def disconnect(): Unit = {} } + + trait Dal { + + type T[_] + implicit val monadT: Monad[T] + + def execute[D](operations: T[D]): Future[D] + def executeTransaction[D](operations: T[D]): Future[D] + def noAction[V](v: V): T[V] + def customAction[R](action: => Future[R]): T[R] + } + + class FutureDal(executionContext: ExecutionContext) extends Dal { + + implicit val exec = executionContext + + override type T[_] = Future[_] + implicit val monadT: Monad[T] = new Monad[T] { + override def point[A](a: => A): T[A] = Future(a) + override def bind[A, B](fa: T[A])(f: A => T[B]): T[B] = fa.flatMap(a => f(a.asInstanceOf[A])) + } + + def execute[D](operations: T[D]): Future[D] = operations.asInstanceOf[Future[D]] + def executeTransaction[D](operations: T[D]): Future[D] = operations.asInstanceOf[Future[D]] + def noAction[V](v: V): T[V] = Future.successful(v) + def customAction[R](action: => Future[R]): T[R] = action + } + + class SlickDal(database: Database, executionContext: ExecutionContext) extends Dal { + + import database.profile.api._ + + implicit val exec = executionContext + + override type T[_] = slick.dbio.DBIO[_] + val monadT: Monad[T] = new Monad[T] { + override def point[A](a: => A): T[A] = DBIO.successful(a) + override def bind[A, B](fa: T[A])(f: A => T[B]): T[B] = fa.flatMap(a => f(a.asInstanceOf[A])) + } + + def execute[D](operations: T[D]): Future[D] = { + database.database.run(operations.asInstanceOf[slick.dbio.DBIO[D]]) + } + + def executeTransaction[D](readOperations: T[D]): Future[D] = { + database.database.run(readOperations.asInstanceOf[slick.dbio.DBIO[D]].transactionally) + } + + def noAction[V](v: V): slick.dbio.DBIO[V] = DBIO.successful(v) + def customAction[R](action: => Future[R]): T[R] = DBIO.from(action) + } } |