本文整理汇总了Scala中slick.dbio.DBIOAction类的典型用法代码示例。如果您正苦于以下问题:Scala DBIOAction类的具体用法?Scala DBIOAction怎么用?Scala DBIOAction使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了DBIOAction类的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。
示例1: EitherT
//设置package包名称以及导入依赖的类
package io.slicker.instances
import slick.dbio.{DBIOAction, Effect, NoStream}
import scala.concurrent.ExecutionContext
class EitherT[A, B, E <: Effect](val value: DBIOAction[Either[A, B], NoStream, E]) {
def map[C](f: B => C)(implicit
ec: ExecutionContext): EitherT[A, C, E] = new EitherT(value.map({
case Right(b) => Right(f(b))
case Left(a) => Left(a)
}))
def flatMap[C, F <: Effect](f: B => EitherT[A, C, F])(implicit
ec: ExecutionContext): EitherT[A, C, E with F] = {
new EitherT(value.flatMap {
case Right(b) => f(b).value
case Left(a) => DBIOAction.successful(Left(a))
})
}
def flatMapF[C, F <: Effect](f: B => DBIOAction[Either[A, C], NoStream, F])(implicit
ec: ExecutionContext): EitherT[A, C, E with F] = {
new EitherT(value.flatMap {
case Right(b) => f(b)
case Left(a) => DBIOAction.successful(Left(a))
})
}
def ensure(onFailure: => A)(predicate: B => Boolean)(implicit
ec: ExecutionContext): EitherT[A, B, E] = {
new EitherT(value.map {
case Right(b) if predicate(b) => Right(b)
case _ => Left(onFailure)
})
}
def assure(onFailure: B => A)(predicate: B => Boolean)(implicit
ec: ExecutionContext): EitherT[A, B, E] = {
new EitherT(value.map {
case Right(b) if predicate(b) => Right(b)
case Right(b) => Left(onFailure(b))
case Left(a) => Left(a)
})
}
def leftMap[D](f: A => D)(implicit
ec: ExecutionContext): EitherT[D, B, E] = new EitherT(value.map {
case Right(b) => Right(b)
case Left(a) => Left(f(a))
})
}
object EitherT {
def apply[A, B, E <: Effect](dBIOAction: DBIOAction[Either[A, B], NoStream, E]) = new EitherT(dBIOAction)
}
开发者ID:ImLiar,项目名称:slicker,代码行数:59,代码来源:EitherT.scala
示例2: DeleteAction
//设置package包名称以及导入依赖的类
package eventsource.slick
import akka.actor.Scheduler
import eventsource.models.{Action, Entity, Event}
import play.api.Logger
import slick.dbio.DBIOAction
import slick.jdbc.JdbcProfile
import scala.concurrent.duration._
import scala.concurrent.{ExecutionContext, Future}
class DeleteAction[Key, ETT, E <: Entity[Key]](
adapter: SlickAdapter[Key, ETT, E],
val driver: JdbcProfile,
db: JdbcProfile#Backend#Database,
override val logger: Logger
)(implicit ec: ExecutionContext, s: Scheduler)
extends Action[Key, ETT, Option[E]]
with Retrying {
import driver.api._
def errorHandler: PartialFunction[(Throwable, Int), Future[Option[E]]] =
PartialFunction.empty
override def processEvent(event: Event[Key, ETT]): Future[Option[E]] =
retry(10, 100.millis, errorHandler) {
db.run(adapter
.findByEventWithLock(event)
.flatMap {
case Some(entity) if event.version.isNewerThan(entity.lastModifiedVersion) =>
logger.debug(
s"Got newer lastModifiedVersion ${event.version} > ${entity.lastModifiedVersion} for ${event.key}. Deleting ...")
adapter.deleteByEvent(event).map(_ => Some(entity))
case Some(entity) =>
logger.debug(
s"Got older lastModifiedVersion ${event.version} <= ${entity.lastModifiedVersion} for ${event.key}. Ignoreing ...")
DBIOAction.successful(None)
case None =>
logger.debug(s"Entity ${event.key} does not exists, ignore delete")
DBIOAction.successful(None)
}
.transactionally)
}
}
开发者ID:21re,项目名称:play-eventsource,代码行数:46,代码来源:DeleteAction.scala
示例3: CreateAction
//设置package包名称以及导入依赖的类
package eventsource.slick
import akka.actor.Scheduler
import eventsource.models.{Action, Entity, Event}
import play.api.Logger
import slick.dbio.DBIOAction
import slick.jdbc.JdbcProfile
import scala.concurrent.duration._
import scala.concurrent.{ExecutionContext, Future}
abstract class CreateAction[Key, ETT, E <: Entity[Key]](
adapter: SlickAdapter[Key, ETT, E],
val driver: JdbcProfile,
db: JdbcProfile#Backend#Database,
override val logger: Logger
)(implicit ec: ExecutionContext, s: Scheduler)
extends Action[Key, ETT, Option[E]]
with Retrying {
protected def entityFromEvent(event: Event[Key, ETT]): E
import driver.api._
def errorHandler: PartialFunction[(Throwable, Int), Future[Option[E]]] =
PartialFunction.empty
override def processEvent(event: Event[Key, ETT]): Future[Option[E]] =
retry(10, 100.millis, errorHandler) {
db.run(adapter
.findByEventWithLock(event)
.flatMap {
case Some(entity) if entity.createdVersion == event.version =>
logger.debug(s"createdVersion=${event.version} already exists. Nothing to do...")
DBIOAction.successful(Some(entity))
case Some(entity) if entity.createdVersion.isNewerThan(event.version) =>
logger.debug(
s"Got older createdVersion ${event.version} < ${entity.createdVersion} for ${event.key}. Updating ...")
val olderEntity = entityFromEvent(event)
logger.debug(s"Update with $olderEntity")
adapter.update(olderEntity).map(_ => Some(olderEntity))
case Some(entity) =>
logger.debug(
s"Got newer createdVersion ${event.version} >= ${entity.createdVersion} for ${event.key}. Ignoring ...")
DBIOAction.successful(None)
case None =>
val entity = entityFromEvent(event)
logger.debug(s"Insert new $entity")
adapter.insert(entity).map(_ => Some(entity))
}
.transactionally)
}
}
开发者ID:21re,项目名称:play-eventsource,代码行数:54,代码来源:CreateAction.scala
示例4: SimpleUpdateAction
//设置package包名称以及导入依赖的类
package eventsource.slick
import akka.actor.Scheduler
import eventsource.models.{Action, Entity, Event}
import play.api.Logger
import slick.dbio.DBIOAction
import slick.jdbc.JdbcProfile
import scala.concurrent.duration._
import scala.concurrent.{ExecutionContext, Future}
abstract class SimpleUpdateAction[Key, ETT, E <: Entity[Key]](
adapter: SlickAdapter[Key, ETT, E],
val driver: JdbcProfile,
db: JdbcProfile#Backend#Database,
override val logger: Logger
)(implicit ec: ExecutionContext, s: Scheduler)
extends Action[Key, ETT, Option[E]]
with Retrying {
import driver.api._
def updateEntity(entity: E, event: Event[Key, ETT]): E
def errorHandler: PartialFunction[(Throwable, Int), Future[Option[E]]] =
PartialFunction.empty
override def processEvent(event: Event[Key, ETT]): Future[Option[E]] =
retry(10, 100.millis, errorHandler) {
db.run(adapter
.findByEventWithLock(event)
.flatMap {
case Some(entity) if event.version == entity.lastModifiedVersion =>
logger.debug(s"lastModifiedVersion=${event.version} already exists. Nothing to do")
DBIOAction.successful(Some(entity))
case Some(entity) if event.version.isNewerThan(entity.lastModifiedVersion) =>
logger.debug(
s"Got newer lastModifiedVersion ${event.version} > ${entity.lastModifiedVersion} for ${event.key}. Updating ...")
val newerEntity = updateEntity(entity, event)
logger.debug(s"Update with $newerEntity")
adapter.update(newerEntity).map(_ => Some(newerEntity))
case Some(entity) =>
logger.debug(
s"Got older lastModifiedVersion ${event.version} <= ${entity.lastModifiedVersion} for ${event.key}. Ignoreing ...")
DBIOAction.successful(None)
case None =>
logger.debug(s"Entity ${event.key} does not exists, ignore update")
DBIOAction.successful(None)
}
.transactionally)
}
}
开发者ID:21re,项目名称:play-eventsource,代码行数:54,代码来源:SimpleUpdateAction.scala
示例5: run
//设置package包名称以及导入依赖的类
package tutor.repo
import slick.dbio.{DBIOAction, NoStream}
import slick.jdbc.{H2Profile, JdbcProfile, OracleProfile}
import scala.concurrent.Future
trait DBConfigProvider {
val jdbcProfile: JdbcProfile
def run[T](action: DBIOAction[T, NoStream, Nothing]):Future[T]
}
trait OracleDB extends DBConfigProvider {
val jdbcProfile: JdbcProfile = OracleProfile
}
trait H2DB extends DBConfigProvider {
val jdbcProfile: JdbcProfile = H2Profile
def run[T](action: DBIOAction[T, NoStream, Nothing]):Future[T] = {
import jdbcProfile.api._
val db = Database.forConfig("h2mem1")
try {
db.run(action)
}finally db.close()
}
}
开发者ID:notyy,项目名称:CodeAnalyzerTutorial,代码行数:29,代码来源:DBConfigProvider.scala
示例6: runAsync
//设置package包名称以及导入依赖的类
package services.db
import javax.inject.{ Inject, Singleton }
import com.google.inject.ImplementedBy
import play.api.db.slick.DatabaseConfigProvider
import slick.dbio.{ DBIOAction, NoStream }
import slick.driver.JdbcProfile
import scala.concurrent.duration.Duration
import scala.concurrent.{ Await, Future }
@ImplementedBy(classOf[DBServiceImpl])
trait DBService {
def runAsync[R](a: DBIOAction[R, NoStream, Nothing]): Future[R]
def run[R](a: DBIOAction[R, NoStream, Nothing]): R
}
@Singleton
class DBServiceImpl @Inject() (val dbConfigProvider: DatabaseConfigProvider) extends DBService {
private val db = dbConfigProvider.get[JdbcProfile].db
def runAsync[R](a: DBIOAction[R, NoStream, Nothing]): Future[R] = {
db.run(a)
}
def run[R](a: DBIOAction[R, NoStream, Nothing]): R = {
Await.result(runAsync(a), Duration.Inf)
}
}
开发者ID:workingDog,项目名称:SilverworkReact,代码行数:32,代码来源:DBService.scala
示例7: SilentDbImporter
//设置package包名称以及导入依赖的类
package com.snapswap.db.helpers.runner
import java.sql.BatchUpdateException
import com.snapswap.db.errors.{DataError, EntityNotFound, InternalDataError, OverrideNotAllowed}
import org.postgresql.util.PSQLException
import slick.basic.BasicBackend
import slick.dbio.{DBIOAction, NoStream}
import slick.util.TreePrinter
import scala.annotation.tailrec
import scala.concurrent.{ExecutionContext, Future}
trait DbRunSafe {
private[this] val pSQLExceptionErrCodes = Set("23505", "23503")
implicit class SilentDbImporter[D <: BasicBackend#DatabaseDef](db: D) {
def runSafe[R](a: DBIOAction[R, NoStream, Nothing])(implicit ec: ExecutionContext): Future[R] = {
def additionalInfo = TreePrinter.default.get(a)
db.run(a).recoverWith {
case ex: UnsupportedOperationException if ex.getMessage == "empty.head" => // When query returns no results then UnsupportedOperationException("empty.head") is thrown instead of NoSuchElementException
Future.failed[R](EntityNotFound(dbDetails = Some(additionalInfo)))
case _: NoSuchElementException =>
Future.failed[R](EntityNotFound(dbDetails = Some(additionalInfo)))
case ex: PSQLException =>
// wrap with Option to avoid NullPointerException
Option(ex.getServerErrorMessage).flatMap(msg => Option(msg.getSQLState)) match {
case Some(sqlState) if pSQLExceptionErrCodes.contains(sqlState) =>
Future.failed[R](OverrideNotAllowed(dbDetails = Some(additionalInfo)))
case _ =>
Future.failed[R](InternalDataError(ex.getMessage, dbDetails = Some(additionalInfo)))
}
case ex: DataError =>
Future.failed[R](ex)
case ex: BatchUpdateException =>
Future.failed[R](InternalDataError(ex.getMessage, dbDetails = Some(getAllExceptions(ex))))
case ex =>
Future.failed[R](InternalDataError(ex.getMessage, dbDetails = Some(additionalInfo)))
}
}
}
@tailrec
private[this] def getAllExceptions(exception: BatchUpdateException, msg: List[String] = List.empty): String = exception match {
case ex: BatchUpdateException =>
ex.getNextException match {
case next: BatchUpdateException =>
getAllExceptions(ex, s"${next.getClass.getSimpleName}: ${next.getMessage}" :: msg)
case ex: PSQLException =>
(s"${ex.getClass.getSimpleName}: ${ex.getMessage}" :: msg).reverse.mkString(",")
}
case _ =>
msg.reverse.mkString(",")
}
}
object DbRunHelper extends DbRunSafe
开发者ID:snap-swap,项目名称:slick-postgres-helpers,代码行数:60,代码来源:DbRunHelper.scala
示例8: runAsync
//设置package包名称以及导入依赖的类
package services.db
import javax.inject.{Inject, Singleton}
import com.google.inject.ImplementedBy
import play.api.db.slick.DatabaseConfigProvider
import slick.dbio.{DBIOAction, NoStream}
import slick.driver.JdbcProfile
import scala.concurrent.duration.Duration
import scala.concurrent.{Await, Future}
@ImplementedBy(classOf[DBServiceImpl])
trait DBService {
def runAsync[R](a: DBIOAction[R, NoStream, Nothing]): Future[R]
def run[R](a: DBIOAction[R, NoStream, Nothing]): R
}
@Singleton
class DBServiceImpl @Inject()(val dbConfigProvider: DatabaseConfigProvider) extends DBService {
private val db = dbConfigProvider.get[JdbcProfile].db
def runAsync[R](a: DBIOAction[R, NoStream, Nothing]): Future[R] = {
db.run(a)
}
def run[R](a: DBIOAction[R, NoStream, Nothing]): R = {
Await.result(runAsync(a), Duration.Inf)
}
}
开发者ID:alexFrankfurt,项目名称:nest-api,代码行数:32,代码来源:DBService.scala
示例9: runAsync
//设置package包名称以及导入依赖的类
package services
import javax.inject.{Inject, Singleton}
import com.google.inject.ImplementedBy
import play.api.db.slick.DatabaseConfigProvider
import slick.dbio.{DBIOAction, NoStream}
import slick.driver.JdbcProfile
import scala.concurrent.duration.Duration
import scala.concurrent.{Await, Future}
@ImplementedBy(classOf[DBServiceImpl])
trait DBService {
def runAsync[R](a: DBIOAction[R, NoStream, Nothing]): Future[R]
def run[R](a: DBIOAction[R, NoStream, Nothing]): R
}
@Singleton
class DBServiceImpl @Inject()(val dbConfigProvider: DatabaseConfigProvider) extends DBService {
private val db = dbConfigProvider.get[JdbcProfile].db
def runAsync[R](a: DBIOAction[R, NoStream, Nothing]): Future[R] = {
db.run(a)
}
def run[R](a: DBIOAction[R, NoStream, Nothing]): R = {
Await.result(runAsync(a), Duration.Inf)
}
}
开发者ID:asciiu,项目名称:halo,代码行数:32,代码来源:DBService.scala
示例10: runAsync
//设置package包名称以及导入依赖的类
package services
import javax.inject.{Inject, Singleton}
import com.google.inject.ImplementedBy
import play.api.db.slick.DatabaseConfigProvider
import slick.backend.DatabasePublisher
import slick.dbio.{DBIOAction, NoStream, Streaming}
import slick.driver.JdbcProfile
import scala.concurrent.duration.Duration
import scala.concurrent.{Await, Future}
@ImplementedBy(classOf[DBServiceImpl])
trait DBService {
def runAsync[R](a: DBIOAction[R, NoStream, Nothing]): Future[R]
def run[R](a: DBIOAction[R, NoStream, Nothing]): R
def stream[R](a: DBIOAction[_, Streaming[R], Nothing]): DatabasePublisher[R]
}
@Singleton
class DBServiceImpl @Inject()(val dbConfigProvider: DatabaseConfigProvider) extends DBService {
private val db = dbConfigProvider.get[JdbcProfile].db
def runAsync[R](a: DBIOAction[R, NoStream, Nothing]): Future[R] = {
db.run(a)
}
def run[R](a: DBIOAction[R, NoStream, Nothing]): R = {
Await.result(runAsync(a), Duration.Inf)
}
def stream[R](a: DBIOAction[_, Streaming[R], Nothing]): DatabasePublisher[R] = {
db.stream(a)
}
}
开发者ID:asciiu,项目名称:polo,代码行数:39,代码来源:DBService.scala
示例11: migrate
//设置package包名称以及导入依赖的类
package com.github.xirc.slickx.migrator
import com.github.xirc.slickx.differ.ModelDiffer
import com.github.xirc.slickx.generator.SqlGenerator
import org.slf4j.LoggerFactory
import slick.dbio.{DBIOAction, Effect, NoStream}
import slick.driver.JdbcDriver
import slick.model.Model
import scala.concurrent.ExecutionContext
trait OtfMigrator {
type Database = driver.api.Database
lazy val logger = LoggerFactory.getLogger(getClass)
val driver: JdbcDriver
val generator: SqlGenerator
def migrate(newModel: Model)(
implicit executionContext: ExecutionContext
): DBIOAction[Unit, NoStream, Effect.All] =
{
import driver.api._
driver.createModel().map(oldModel => {
val diff = new ModelDiffer().diffModel(oldModel, newModel)
val sqls = generator.unwrap(generator.generateModel(diff))
val actions = sqls.map(sql => sqlu"#${sql}")
logger.debug(
s"""
|On the fly update (mysql)
|SQLs:
|${sqls.mkString("\n")}
""".stripMargin
)
// Don't use DBIO.sequence and DBIO.seq because these composer apply SQLs eagerly :-)
DBIO.fold(actions, 0)(_ + _).withPinnedSession
})
}
}
开发者ID:xirc,项目名称:slick-extensions,代码行数:41,代码来源:OtfMigrator.scala
注:本文中的slick.dbio.DBIOAction类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论