• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Scala DBIO类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Scala中slick.dbio.DBIO的典型用法代码示例。如果您正苦于以下问题:Scala DBIO类的具体用法?Scala DBIO怎么用?Scala DBIO使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了DBIO类的18个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。

示例1: PlayWithFoodWithTestComponents

//设置package包名称以及导入依赖的类
package testhelpers

import config.ExampleComponents
import org.scalatest.BeforeAndAfterEach
import org.scalatestplus.play.PlaySpec
import org.scalatestplus.play.components.OneServerPerTestWithComponents
import play.api.db.evolutions.Evolutions
import play.api.http.Status
import play.api.libs.ws.WSClient
import play.api.test.{DefaultAwaitTimeout, FutureAwaits, Helpers, TestServer}
import play.api.{Application, Configuration}
import slick.dbio.DBIO

trait PlayWithFoodWithServerBaseTest extends PlaySpec
  with OneServerPerTestWithComponents
  with DefaultFutureDuration
  with DefaultExecutionContext
  with Status
  with DefaultAwaitTimeout
  with FutureAwaits
  with BeforeAndAfterEach {

  class PlayWithFoodWithTestComponents extends ExampleComponents(context) {

    override def configuration: Configuration = {
      val testConfig = Configuration.from(TestUtils.config)
      val config = super.configuration
      val testConfigMerged = config ++ testConfig
      config.toString
      testConfigMerged
    }

    implicit lazy val testWsClient: WSClient = wsClient
  }

  override def components: PlayWithFoodWithTestComponents = new PlayWithFoodWithTestComponents

  private def runServerAndCleanUpInMemDb(c: PlayWithFoodWithTestComponents) = {
    runServerAndExecute(c.application) {
      val dbapi = c.dbApi
      Evolutions.cleanupEvolutions(dbapi.database("default"))
    }
  }

  override protected def afterEach(): Unit = {
    runServerAndCleanUpInMemDb(components)
  }

  protected def runServerAndExecute[T](app: Application)(blockWithComponents: => T): T = {
    Helpers.running(TestServer(port, app))(blockWithComponents)
  }

  def runAndAwaitResult[T](action: DBIO[T])(implicit components: ExampleComponents): T = {
    TestUtils.runAndAwaitResult(action)(components.actionRunner, duration)
  }

} 
开发者ID:Dasiu,项目名称:play-framework-scala-example-project,代码行数:58,代码来源:PlayWithFoodWithServerBaseTest.scala


示例2: Initializer

//设置package包名称以及导入依赖的类
package slick3.common

import slick.dbio.DBIO
import slick.driver.MySQLDriver.api._

object Initializer {

  def init(): DBIO[Unit] =
    DBIO.seq(
      sqlu"""DELETE FROM items""",
      sqlu"""DELETE FROM users""",
      sqlu"""DELETE FROM companies""",
      sqlu"""INSERT INTO companies (id, name) VALUES
                (1, '?????')
               ,(2, '?????')
               ,(3, '?????')""",
      sqlu"""INSERT INTO users (id, name, age, companyId) VALUES
                (1, '?????', 23, 1)
               ,(2, '?????', 30, 2)
               ,(3, '?????', 36, 1)
               ,(4, '?????', 20, 2)""",
      sqlu"""INSERT INTO items (userId, name, status) VALUES
                (1, '????', 0)
               ,(1, '??????', 1)
               ,(1, '????', 2)
               ,(3, '????', 0)
               ,(3, '?????', 1)
               ,(3, '??????', 2)""",
      sqlu"""DELETE FROM includeSomeType""",
      sqlu"""INSERT INTO includeSomeType (column02, column03, column04, column05, column06, column07, column08, column09) VALUES
                ('AAA', 'BBB', 1, 2, 3, 4, '2016-11-13 13:00;00', CURRENT_TIME)
               ,('CCC', 'DDD', 5, 6, 7, 8, '2016-11-13 13:00;00', CURRENT_TIME)""",
      sqlu"""DELETE FROM columns22over""",
      sqlu"""INSERT INTO columns22over (column02, column03, column04, column05, column06, column07, column08, column09, column10, column11, column12, column13, column14, column15, column16, column17, column18, column19, column20, column21, column22, column23) VALUES
                ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V')"""
    )

} 
开发者ID:shinharad,项目名称:scala-db-lab,代码行数:39,代码来源:Initializer.scala


示例3: DataStore

//设置package包名称以及导入依赖的类
package controllers.datastore

import play.api.db.slick.DatabaseConfigProvider
import play.api.db.slick.HasDatabaseConfigProvider
import slick.dbio.DBIO
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import slick.driver.JdbcProfile
import scala.concurrent.Future
import scala.util.{Try, Success, Failure}
import javax.inject._

class DataStore @Inject()(protected val dbConfigProvider: DatabaseConfigProvider,
                          private val users: Users,
                          private val stockPrices: StockPrices,
                          private val exchangeRates: ExchangeRates)
    extends HasDatabaseConfigProvider[JdbcProfile] {

  // val initializer = DBIO.seq(users.schema.create,
  //                            stockPrices.schema.create,
  //                            exchangeRates.schema.create)

  // def initialize = db.run(initializer)
  
} 
开发者ID:omefire,项目名称:Scodex,代码行数:25,代码来源:DataStore.scala


示例4: FileRpcErrors

//设置package包名称以及导入依赖的类
package im.actor.api.rpc

import cats.data.Xor
import im.actor.server.acl.ACLUtils

import scala.concurrent.ExecutionContext
import akka.actor.ActorSystem
import slick.dbio.DBIO
import im.actor.api.rpc.files.ApiFileLocation
import im.actor.server.persist.files.FileRepo

object FileRpcErrors {
  val FileNotFound = RpcError(404, "FILE_NOT_FOUND", "File not found.", false, None)
  val FileTooLarge = RpcError(400, "FILE_TOO_LARGE", "File is too large.", false, None)
  val LocationInvalid = RpcError(400, "LOCATION_INVALID", "", false, None)
  val UnsupportedSignatureAlgorithm = RpcError(400, "SIGNATURE_ALGO_NOT_SUPPORTED", "", false, None)
}

object FileHelpers {

  def withFileLocation[R <: RpcResponse](fileLocation: ApiFileLocation, maxSize: Long)(f: ? DBIO[RpcError Xor R])(implicit ec: ExecutionContext, s: ActorSystem) = {
    FileRepo.find(fileLocation.fileId) flatMap {
      case Some(file) ?
        if (!file.isUploaded) {
          DBIO.successful(Error(FileRpcErrors.LocationInvalid))
        } else if (file.size > maxSize) {
          DBIO.successful(Error(FileRpcErrors.FileTooLarge))
        } else if (ACLUtils.fileAccessHash(file.id, file.accessSalt) != fileLocation.accessHash) {
          DBIO.successful(Error(FileRpcErrors.LocationInvalid))
        } else {
          f
        }
      case None ? DBIO.successful(Error(FileRpcErrors.FileNotFound))
    }
  }

} 
开发者ID:wex5,项目名称:dangchat-server,代码行数:38,代码来源:FileHelpers.scala


示例5: SecurityUserService

//设置package包名称以及导入依赖的类
package authentication.services

import authentication.models.api.{NewSecurityUser, PlainTextPassword}
import authentication.models.{PasswordHash, SecurityUser, SecurityUserId}
import authentication.repositories.SecurityUserRepo
import authentication.services.api.{SecurityUserCreator, SecurityUserProvider}
import javax.inject.Inject

import commons.models.Login
import org.mindrot.jbcrypt.BCrypt
import slick.dbio.DBIO

private[authentication] class SecurityUserService(securityUserRepo: SecurityUserRepo)
  extends SecurityUserProvider
    with SecurityUserCreator {

  override def create(newSecUser: NewSecurityUser): DBIO[SecurityUser] = {
    require(newSecUser != null)

    val passwordHash = hashPass(newSecUser.password)
    securityUserRepo.create(SecurityUser(SecurityUserId(-1), newSecUser.login, passwordHash, null, null))
  }

  private def hashPass(password: PlainTextPassword): PasswordHash = {
    val hash = BCrypt.hashpw(password.value, BCrypt.gensalt())
    PasswordHash(hash)
  }

  override def byLogin(login: Login): DBIO[Option[SecurityUser]] = {
    require(login != null)

    securityUserRepo.byLogin(login)
  }
} 
开发者ID:Dasiu,项目名称:play-framework-scala-example-project,代码行数:35,代码来源:SecurityUserService.scala


示例6: SecurityUserRepo

//设置package包名称以及导入依赖的类
package authentication.repositories

import authentication.models.{PasswordHash, SecurityUser, SecurityUserId}
import commons.models.{IdMetaModel, Login, Property}
import commons.repositories._
import commons.repositories.mappings.{JavaTimeDbMappings, LoginDbMappings}
import slick.dbio.DBIO
import slick.jdbc.MySQLProfile.api.{DBIO => _, MappedTo => _, Rep => _, TableQuery => _, _}
import slick.lifted.{ProvenShape, _}

private[authentication] class SecurityUserRepo(
                                                         override protected val dateTimeProvider: DateTimeProvider)
  extends BaseRepo[SecurityUserId, SecurityUser, SecurityUserTable]
    with AuditDateTimeRepo[SecurityUserId, SecurityUser, SecurityUserTable]
    with LoginDbMappings
    with SecurityUserDbMappings {

  def byLogin(login: Login): DBIO[Option[SecurityUser]] = {
    query
      .filter(_.login === login)
      .result
      .headOption
  }

  override protected val mappingConstructor: Tag => SecurityUserTable = new SecurityUserTable(_)

  override protected val modelIdMapping: BaseColumnType[SecurityUserId] = MappedColumnType.base[SecurityUserId, Long](
    vo => vo.value,
    id => SecurityUserId(id)
  )

  override protected val metaModel: IdMetaModel = SecurityUserMetaModel

  override protected val metaModelToColumnsMapping: Map[Property[_], (SecurityUserTable) => Rep[_]] = Map(
    SecurityUserMetaModel.id -> (table => table.id),
    SecurityUserMetaModel.login -> (table => table.login),
    SecurityUserMetaModel.password -> (table => table.password)
  )

}

protected class SecurityUserTable(tag: Tag) extends IdTable[SecurityUserId, SecurityUser](tag, "security_user")
  with AuditDateTimeTable
  with JavaTimeDbMappings
  with LoginDbMappings
  with SecurityUserDbMappings {

  def login: Rep[Login] = column("login")

  def password: Rep[PasswordHash] = column("password")

  def * : ProvenShape[SecurityUser] = (id, login, password, createdAt, modifiedAt) <> (SecurityUser.tupled,
    SecurityUser.unapply)
}

private[authentication] object SecurityUserMetaModel extends IdMetaModel {
  override type ModelId = SecurityUserId

  val login: Property[Login] = Property("login")
  val password: Property[PasswordHash] = Property("password")
} 
开发者ID:Dasiu,项目名称:play-framework-scala-example-project,代码行数:62,代码来源:SecurityUserRepo.scala


示例7: create

//设置package包名称以及导入依赖的类
package commons.repositories

import java.time.LocalDateTime

import commons.models.WithDateTimes
import commons.repositories.mappings.JavaTimeDbMappings
import slick.dbio.DBIO
import slick.jdbc.MySQLProfile.api.{DBIO => _, MappedTo => _, Rep => _, TableQuery => _, _}
import slick.lifted._

trait AuditDateTimeRepo[ModelId <: BaseId[Long],
WithDatesModel <: WithId[Long, ModelId] with WithDateTimes[WithDatesModel],
ModelTable <: IdTable[ModelId, WithDatesModel] with AuditDateTimeTable]
  extends BaseRepo[ModelId, WithDatesModel, ModelTable]
    with JavaTimeDbMappings {
  protected val dateTimeProvider: DateTimeProvider

  override def create(model: WithDatesModel): DBIO[WithDatesModel] = {
    val now = dateTimeProvider.now
    val modelWithDates = model.updateCreatedAt(now)
      .updateModifiedAt(now)
    super.create(modelWithDates)
  }

  override def update(model: WithDatesModel): DBIO[WithDatesModel] = {
    val now = dateTimeProvider.now
    val modelWithDates = model.updateModifiedAt(now)
    super.update(modelWithDates)
  }


}

trait AuditDateTimeTable {
  _: Table[_] with JavaTimeDbMappings =>

  def createdAt: Rep[LocalDateTime] = column("created_at")

  def modifiedAt: Rep[LocalDateTime] = column("modified_at")
} 
开发者ID:Dasiu,项目名称:play-framework-scala-example-project,代码行数:41,代码来源:AuditDateTimeRepo.scala


示例8: byName

//设置package包名称以及导入依赖的类
package commons.repositories

import commons.models.WithName
import slick.dbio.DBIO
import slick.jdbc.MySQLProfile.api.{DBIO => _, MappedTo => _, Rep => _, TableQuery => _, _}
import slick.lifted._

trait UniqueNameRepo[ModelId <: BaseId[Long],
WithNameModel <: WithId[Long, ModelId] with WithName,
ModelTable <: IdTable[ModelId, WithNameModel] with WithNameBaseTable]
  extends BaseRepo[ModelId, WithNameModel, ModelTable] {

  def byName(name: String): DBIO[Option[WithNameModel]] = {
    query
      .filter(_.name === name)
      .result
      .headOption
  }

}

trait WithNameBaseTable {
  self: Table[_] =>

  def name: Rep[String] = column("name")
} 
开发者ID:Dasiu,项目名称:play-framework-scala-example-project,代码行数:27,代码来源:UniqueNameRepo.scala


示例9: UserRegistrationService

//设置package包名称以及导入依赖的类
package users.services

import javax.inject.Inject

import authentication.models.api.NewSecurityUser
import authentication.services.api.SecurityUserCreator
import commons.exceptions.ValidationException
import commons.validations.{Failure, Success}
import slick.dbio.DBIO
import users.models.{User, UserId, UserRegistration}
import users.services.api.UserCreator

import scala.concurrent.ExecutionContext.Implicits.global

private[users] class UserRegistrationService(userRegistrationValidator: UserRegistrationValidator,
                                                       securityUserCreator: SecurityUserCreator,
                                                       userCreator: UserCreator) {

  def register(userRegistration: UserRegistration): DBIO[User] = {
    userRegistrationValidator.validate(userRegistration) match {
      case Success => doRegister(userRegistration)
      case Failure(violatedConstraints) => throw new ValidationException(violatedConstraints)
    }
  }

  private def doRegister(userRegistration: UserRegistration) = {
    val newSecurityUser = NewSecurityUser(userRegistration.login, userRegistration.password)
    userCreator.create(User(UserId(-1), userRegistration.login))
      .zip(securityUserCreator.create(newSecurityUser))
      .map(_._1)
  }
} 
开发者ID:Dasiu,项目名称:play-framework-scala-example-project,代码行数:33,代码来源:UserRegistrationService.scala


示例10: UserRepo

//设置package包名称以及导入依赖的类
package users.repositories

import javax.inject.Inject

import commons.models.{IdMetaModel, Login, Property}
import commons.repositories.mappings.LoginDbMappings
import commons.repositories.{BaseRepo, IdTable}
import slick.lifted.ProvenShape
import users.models.{User, UserId, UserMetaModel}
import slick.dbio.DBIO
import slick.jdbc.MySQLProfile.api.{DBIO => _, MappedTo => _, Rep => _, TableQuery => _, _}
import slick.lifted._

class UserRepo()
  extends BaseRepo[UserId, User, UserTable] {

  def byLogin(login: Login): DBIO[Option[User]] = {
    query
      .filter(_.login === login)
      .result
      .headOption
  }

  override protected val mappingConstructor: Tag => UserTable = new UserTable(_)

  override protected val modelIdMapping: BaseColumnType[UserId] = MappedColumnType.base[UserId, Long](
    vo => vo.value,
    id => UserId(id)
  )

  override protected val metaModel: IdMetaModel = UserMetaModel

  override protected val metaModelToColumnsMapping: Map[Property[_], (UserTable) => Rep[_]] = Map(
    UserMetaModel.id -> (table => table.id),
    UserMetaModel.login -> (table => table.login)
  )

  // TODO use shared login mapping
  implicit val loginMapping: BaseColumnType[Login] = MappedColumnType.base[Login, String](
    login => login.value,
    str => Login(str)
  )

}

protected class UserTable(tag: Tag) extends IdTable[UserId, User](tag, "user")
  with LoginDbMappings {
  def login: Rep[Login] = column[Login]("login")

  def * : ProvenShape[User] = (id, login) <> (User.tupled, User.unapply)
} 
开发者ID:Dasiu,项目名称:play-framework-scala-example-project,代码行数:52,代码来源:UserRepo.scala


示例11: GrimeyDatabaseContext

//设置package包名称以及导入依赖的类
package com.grimey

import com.grimey.staticpage.StaticPagesTable
import slick.backend.DatabaseConfig
import slick.dbio.{DBIO, DBIOAction}
import slick.driver.MySQLDriver
import slick.jdbc.meta.MTable
import slick.lifted.TableQuery
import slick.driver.MySQLDriver.api._

import scala.concurrent.Await
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global

class GrimeyDatabaseContext(config: DatabaseContextConfig) {
  private lazy val dbConfig: DatabaseConfig[MySQLDriver] = DatabaseConfig.forConfig("slick.dbs.default")
  lazy val db = dbConfig.db

  init()

  private def init(): Unit = {
    if (tableExists("static_pages") == false) {  // Todo: Don't hard code the table name.
      val staticPages = TableQuery[StaticPagesTable]

      val setup: DBIO[Unit] = DBIOAction.seq(staticPages.schema.create)
      val setupFuture = db.run(setup)

      val result = setupFuture.map { r =>  }

      Await.result(result, config.defaultTimeout)
    }
  }

  def tableExists(name: String) = {
    Await.result(db.run(MTable.getTables), config.defaultTimeout)
      .toList
      .map(_.name.name)
      .contains(name)
  }
} 
开发者ID:CSGrimey,项目名称:grimey-cms-scala,代码行数:41,代码来源:GrimeyDatabaseContext.scala


示例12: PlaceRepository

//设置package包名称以及导入依赖的类
package infrastructure.repository

import Tables._
import domain.model.Place
import slick.dbio.DBIO
import util.Id64
import Tables.profile.api._

import scala.concurrent.ExecutionContext


class PlaceRepository {
  def register(place: Place)(implicit ec: ExecutionContext): DBIO[Int] = {
    Places += PlacesRow(place.id, place.name, place.address)
  }

  def update(id: Long, place: Place)(implicit ec: ExecutionContext): DBIO[Int] = {
    Places.filter(_.placeId === id.bind)
      .map(row => (row.name, row.address))
      .update((place.name, place.address))
  }

  def findBy(placeId: Long)(implicit ec: ExecutionContext): DBIO[Option[Place]] = {
    Places
      .filter(_.placeId === placeId.bind)
      .result
      .headOption
      .map(_.map(p => Place(p.placeId, p.name, p.address)))
  }

  def findBy(placeName: String)(implicit ec: ExecutionContext): DBIO[Option[Place]] = {
    Places
      .filter(_.name === placeName.bind)
      .result
      .headOption
      .map(_.map(p => Place(p.placeId, p.name, p.address)))
  }

} 
开发者ID:FScoward,项目名称:billets-en-concert,代码行数:40,代码来源:PlaceRepository.scala


示例13: PlaceService

//设置package包名称以及导入依赖的类
package domain.service

import javax.inject.Inject

import domain.model.Place
import infrastructure.repository.PlaceRepository
import util.Id64
import slick.dbio.DBIO

import scala.concurrent.ExecutionContext


class PlaceService @Inject() (placeRepository: PlaceRepository) {
  def find(placeName: String)(implicit ec: ExecutionContext): DBIO[Place] = {
    for {
      place <- placeRepository.findBy(placeName)
      p <- place.fold {
        val newPlace = Place(Id64.nextAscId(), placeName, "")
        placeRepository.register(newPlace).map(_ => newPlace)
      }(p => DBIO.successful(p))
    } yield p
  }
} 
开发者ID:FScoward,项目名称:billets-en-concert,代码行数:24,代码来源:PlaceService.scala


示例14: FarmTable

//设置package包名称以及导入依赖的类
package spider.database

import slick.jdbc.MySQLProfile.api._
import slick.lifted.Tag
import slick.dbio.DBIO

import com.github.nscala_time.time.Imports._

import java.sql.Date

import spider.spider3w3n.Record3w3n
import spider.Util.DateTimeUtil.{ toSQLDate, stripHourMinSec }

class FarmTable(tag: Tag)
  extends Table[(String, Option[String], Double, String, Date)](
    tag, Some("farm"), "Farm") {
  def name = column[String]("NAME")
  def subtype = column[Option[String]]("SUBTYPE")
  def price = column[Double]("PRICE")
  def market = column[String]("MARKET")
  def date = column[Date]("DATE")
  def * = (name, subtype, price, market, date)
}

object FarmTable extends TableQuery(new FarmTable(_)) {
  def insert(name: String, record: Record3w3n) = {
    this += ((
      name,
      Some(record.name),
      record.price,
      record.market,
      toSQLDate(record.date)))
  }

  def clearRecordsAction(dates: Seq[DateTime]) = {
    DBIO.sequence(
      dates map { date ?
        (this filter (_.date === toSQLDate(stripHourMinSec(date)))).delete
      })
  }
}

class CategoryTable(tag: Tag)
  extends Table[(String, String)](tag, Some("farm"), "Category") {
  def category = column[String]("CATEGORY")
  def name = column[String]("NAME")
  def * = (category, name)
}

object CategoryTable extends TableQuery(new CategoryTable(_)) {
  def insert(category: String, name: String) = {
    this += ((category, name))
  }
  def clearAll = this.delete
} 
开发者ID:VinaLx,项目名称:farm-spider,代码行数:56,代码来源:table.scala


示例15: FarmDB

//设置package包名称以及导入依赖的类
package spider
package database

import slick.jdbc.JdbcBackend._
import slick.jdbc.MySQLProfile.api.{ Database ? _, DBIOAction ? _, _ }
import slick.dbio.DBIO
import slick.dbio._

import scala.concurrent.{ Await, ExecutionContext }
import scala.concurrent.duration.Duration.Inf

import com.typesafe.scalalogging.Logger

object FarmDB {

  lazy val logger = Logger("spider.database")

  def prepareDbAndTable(config: DBConfig): Unit = {
    import scala.concurrent.ExecutionContext.Implicits.global
    if (config.db.isEmpty) return
    val db = getConnection(config.copy(db = None))
    val actions = Seq(
      createDatabaseSQL(config.db.get),
      createProductTable,
      createCategoryTable)
    actions map { action ?
      Await.result(db.run(action) recover {
        case e ? logger.info(e.getMessage)
      }, Inf)
    }
  }

  def getConnection(config: DBConfig): Database = {
    prepareDbAndTable(config)
    Database.forURL(mysqlURL(config), driver = "com.mysql.jdbc.Driver")
  }

  private def createDatabaseSQL(db: String) = {
    // NO INJECTION PREVENTION
    sqlu"CREATE DATABASE IF NOT EXISTS #$db"
  }

  private def mysqlURL(config: DBConfig): String = {
    val builder = new StringBuilder(s"jdbc:mysql://${config.host}:${config.port}")
    for (db ? config.db) builder ++= s"/$db"
    builder ++= s"?user=${config.username}"
    for (pass ? config.password) builder ++= s"&password=$pass"
    for ((key, value) ? config.properties) builder ++= s"&$key=$value"
    builder.toString
  }

  def createProductTable = FarmTable.schema.create
  def createCategoryTable = CategoryTable.schema.create

  implicit class SyncDB(db: Database) {
    def runSync[R](a: DBIOAction[R, NoStream, Nothing])(
      implicit ec: ExecutionContext): R = {
      Await.result(db.run(a), Inf)
    }
  }
} 
开发者ID:VinaLx,项目名称:farm-spider,代码行数:62,代码来源:database.scala


示例16: CommentLikeService

//设置package包名称以及导入依赖的类
package services

import javax.inject.Inject

import models.{CommentId, CommentLike, _}
import repositories.{CommentLikeRepository, CommentsRepository, JdbcProfileProvider}
import slick.dbio.DBIO

import scala.concurrent.{ExecutionContext, Future}

class CommentLikeService @Inject()(
  eventPublisher: EventPublisher,
  commentLikeRepository: CommentLikeRepository,
  commentRepository: CommentsRepository,
  jdbc: JdbcProfileProvider)(implicit exec: ExecutionContext) {

  //Slick implicits for db.run
  import jdbc.provider._


  def like(newCommentLike: NewCommentLike): Future[CommentLike] = db.run {
  
    commentLikeRepository
      .insert(CommentLike(commentId = newCommentLike.commentId, userId = newCommentLike.userId))
      .zip(getGitHubRepositoryIdByCommentId(newCommentLike.commentId))
      .map { case (commentLike, gitHubRepositoryId) =>
        publishEvent(commentLike, gitHubRepositoryId)
      }
  }

  def getLikes(commentId: CommentId): Future[Seq[CommentLike]] = db.run {
    commentLikeRepository.getLikes(commentId)
  }

  private def getGitHubRepositoryIdByCommentId(commentId: CommentId): DBIO[GitHubRepositoryId] = {
    commentRepository.getComment(commentId)
      .map(comment => GitHubRepositoryId(comment.repositoryOwner, comment.repositoryName))
  }

  private def publishEvent(commentLike: CommentLike, gitHubRepositoryId: GitHubRepositoryId): CommentLike = {
    eventPublisher.publish(NewCommentLikeEvent(gitHubRepositoryId, commentLike.commentId))
    commentLike
  }
} 
开发者ID:Antanukas,项目名称:play-reactive-workshop,代码行数:45,代码来源:CommentLikeService.scala


示例17: DBIOExtensions

//设置package包名称以及导入依赖的类
package au.com.agiledigital.dao.slick

import au.com.agiledigital.dao.slick.exceptions.{ NoRowsAffectedException, TooManyRowsAffectedException }
import slick.dbio.DBIO

import scala.concurrent.ExecutionContext

object DBIOExtensions {

  implicit class UpdateActionExtensionMethods(dbAction: DBIO[Int]) {

    def mustAffectOneSingleRow(implicit exc: ExecutionContext): DBIO[Int] = {
      dbAction.flatMap {
        case 1 => DBIO.successful(1) // expecting one result
        case 0 => DBIO.failed(NoRowsAffectedException)
        case n if n > 1 => DBIO.failed(new TooManyRowsAffectedException(affectedRowCount = n, expectedRowCount = 1))
      }
    }

    def mustAffectAtLeastOneRow(implicit exc: ExecutionContext): DBIO[Int] = {

      dbAction.flatMap {
        case n if n >= 1 => DBIO.successful(n) // expecting one or more results
        case 0 => DBIO.failed(NoRowsAffectedException)
      }
    }
  }

  implicit class SelectSingleExtensionMethods[R](dbAction: DBIO[Seq[R]]) {

    def mustSelectSingleRecord(implicit exc: ExecutionContext): DBIO[R] = {
      dbAction.flatMap {
        case s if s.size == 1 => DBIO.successful(s.head)
        case s if s.isEmpty => DBIO.failed(NoRowsAffectedException)
        case s => DBIO.failed(new TooManyRowsAffectedException(affectedRowCount = s.size, expectedRowCount = 1))
      }
    }
  }

} 
开发者ID:agiledigital,项目名称:slick-dao,代码行数:41,代码来源:DBIOExtensions.scala


示例18: getAll

//设置package包名称以及导入依赖的类
package service

import dao.Tables._
import scala.concurrent.Future
import slick.dbio.DBIO
import utils.DatabaseConfig._
import utils.DatabaseConfig.profile.api._

trait AthleteService {
  def getAll(): Future[Seq[AppointmentRow]]
  def get(): Future[Option[AppointmentRow]]
}

object AthleteService extends AthleteService with TimestampHelper {
  override def getAll(): Future[Seq[AppointmentRow]] = db.run {
    getAllAppointment
  }

  override def get(): Future[Option[AppointmentRow]] = db.run {
    getAppointment(1)
  }

  private def getAllAppointment(): DBIO[Seq[AppointmentRow]] = Appointment.result
  private def getAppointment(id: Long): DBIO[Option[AppointmentRow]] = Appointment.filter(_.id === id).result.headOption
} 
开发者ID:blueguitarenator,项目名称:biggsix,代码行数:26,代码来源:AthleteService.scala



注:本文中的slick.dbio.DBIO类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala ObservableBuffer类代码示例发布时间:2022-05-23
下一篇:
Scala EssentialAction类代码示例发布时间:2022-05-23
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap