本文整理汇总了Scala中slick.jdbc.JdbcProfile类的典型用法代码示例。如果您正苦于以下问题:Scala JdbcProfile类的具体用法?Scala JdbcProfile怎么用?Scala JdbcProfile使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了JdbcProfile类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。
示例1: UserSlickDBIOStorageDriver
//设置package包名称以及导入依赖的类
package com.github.j5ik2o.scala.ddd.functional.example.driver.cats
import cats.data.Kleisli
import com.github.j5ik2o.scala.ddd.functional.driver.StorageDriver
import com.github.j5ik2o.scala.ddd.functional.example.domain.{ User, UserId }
import com.github.j5ik2o.scala.ddd.functional.example.driver.slick3.UserDaoComponent
import slick.jdbc.JdbcProfile
import scala.concurrent.ExecutionContext
case class UserSlickDBIOStorageDriver(profile: JdbcProfile, db: JdbcProfile#Backend#Database)
extends UserDaoComponent {
type EvalType[A] = Kleisli[profile.api.DBIO, ExecutionContext, A]
implicit object InternalDriver extends StorageDriver[User, EvalType] {
override type RecordType = UserRecord
protected val dao = UserDao
import profile.api._
override protected def convertToRecord(aggregate: User): UserRecord =
UserRecord(id = aggregate.id.value, name = aggregate.name)
override protected def convertToAggregate(record: Option[UserRecord]): Option[User] =
record.map(e => User(id = UserId(e.id), name = e.name))
override def store(aggregate: User): EvalType[Unit] = Kleisli { implicit ec =>
val record = convertToRecord(aggregate)
val action = (for {
n <- dao.filter(_.id === aggregate.id.value).update(record)
_ <- if (n == 0) dao.forceInsert(record) else DBIO.successful(n)
} yield ()).transactionally
action.asInstanceOf[DBIO[Unit]]
}
override def resolveBy(id: UserId): EvalType[Option[User]] = Kleisli { implicit ec =>
val action =
dao
.filter(_.id === id.value)
.result
.headOption
.map(convertToAggregate)
action.asInstanceOf[DBIO[Option[User]]]
}
override def deleteById(id: UserId): EvalType[Unit] = Kleisli { implicit ec =>
val action = dao.filter(_.id === id.value).delete
action
.flatMap { v =>
if (v == 1)
DBIO.successful(())
else
DBIO.failed(new Exception())
}
.asInstanceOf[DBIO[Unit]]
}
}
}
开发者ID:j5ik2o,项目名称:scala-ddd-base-functional,代码行数:61,代码来源:UserSlickDBIOStorageDriver.scala
示例2: DatabaseInitializer
//设置package包名称以及导入依赖的类
package essentials.petstore.database
import slick.basic.DatabaseConfig
import slick.jdbc.meta.MTable
import slick.jdbc.JdbcProfile
import com.typesafe.scalalogging.LazyLogging
import scala.concurrent.duration._
import scala.concurrent.Await
class DatabaseInitializer(val dbConfig: DatabaseConfig[JdbcProfile], petsRepo: PetsRepository, recordsRepo: PetRecordsRepository) extends Db with LazyLogging {
import dbConfig.profile.api._
def initDatabaseTables(): Unit = {
logger.info("Setting up database")
// Get all existing tables
val tables = Await.result(db.run(MTable.getTables), 10 seconds)
val petsTableName = petsRepo.pets.baseTableRow.tableName
if (!tables.exists(existingTable => existingTable.name.name == petsTableName)) {
logger.info(s"Creating table '$petsTableName'")
Await.result(db.run(petsRepo.pets.schema.create), 10 seconds)
} else {
logger.info(s"Table '$petsTableName' already exists")
}
val recordsTableName = recordsRepo.records.baseTableRow.tableName
if (!tables.exists(existingTable => existingTable.name.name == recordsTableName)) {
logger.info(s"Creating table '$recordsTableName'")
Await.result(db.run(recordsRepo.records.schema.create), 10 seconds)
} else {
logger.info(s"Table '$recordsTableName' already exists")
}
logger.info("Finished setting up database")
}
}
开发者ID:littlenag,项目名称:scala-essentials-petstore,代码行数:39,代码来源:DatabaseInitializer.scala
示例3: LocalDateTimeColumnType
//设置package包名称以及导入依赖的类
package com.dbrsn.datatrain.slick
import java.time.LocalDateTime
import cats.~>
import com.dbrsn.datatrain.dsl.meta.ResourceDSL
import com.dbrsn.datatrain.dsl.meta.ResourceDSL.Create
import com.dbrsn.datatrain.model.Resource
import com.dbrsn.datatrain.model.ResourceId
import shapeless.Generic
import shapeless.HNil
import slick.jdbc.JdbcProfile
import slick.lifted.ProvenShape
import slickless._
case class LocalDateTimeColumnType[P <: JdbcProfile](implicit columnType: P#BaseColumnType[LocalDateTime])
trait ResourceJdbcComponent[P <: JdbcProfile] {
val localDateTimeColumnType: LocalDateTimeColumnType[P]
val profile: P
import profile.api._
import localDateTimeColumnType._
type ResourceJdbcDSL[A] = ResourceDSL[A]
def resourceTableName: String = "dt_resource"
class ResourceTable(tag: Tag) extends Table[Resource](tag, resourceTableName) {
def id: Rep[ResourceId] = column[ResourceId]("id", O.PrimaryKey)
def createdAt: Rep[LocalDateTime] = column[LocalDateTime]("created_at")
override def * : ProvenShape[Resource] = (id :: createdAt :: HNil).mappedWith(Generic[Resource])
}
lazy val resourceTableQuery: TableQuery[ResourceTable] = TableQuery[ResourceTable]
object ResourceInterpreter extends (ResourceJdbcDSL ~> DBIO) {
override def apply[A](fa: ResourceJdbcDSL[A]): DBIO[A] = fa match {
case Create(resource) => (resourceTableQuery returning resourceTableQuery.map(_.id) into ((v, _) => v)) += resource
}
}
}
开发者ID:dborisenko,项目名称:data-train,代码行数:46,代码来源:ResourceJdbcComponent.scala
示例4: contentTableName
//设置package包名称以及导入依赖的类
package com.dbrsn.datatrain.slick
import java.time.LocalDateTime
import cats.~>
import com.dbrsn.datatrain.dsl.meta.ContentDSL
import com.dbrsn.datatrain.dsl.meta.ContentDSL.Create
import com.dbrsn.datatrain.model.Content
import com.dbrsn.datatrain.model.ContentId
import com.dbrsn.datatrain.model.ContentType
import com.dbrsn.datatrain.model.Resource
import com.dbrsn.datatrain.model.ResourceId
import shapeless.Generic
import shapeless.HNil
import slick.jdbc.JdbcProfile
import slick.lifted.ForeignKeyQuery
import slick.lifted.ProvenShape
import slickless._
trait ContentJdbcComponent[P <: JdbcProfile] {
self: ResourceJdbcComponent[P] =>
val profile: P
import profile.api._
import localDateTimeColumnType._
type ContentJdbcDSL[A] = ContentDSL[A]
def contentTableName: String = "dt_content"
class ContentTable(tag: Tag) extends Table[Content](tag, contentTableName) {
def id: Rep[ContentId] = column[ContentId]("id", O.PrimaryKey)
def createdAt: Rep[LocalDateTime] = column[LocalDateTime]("created_at")
def resourceId: Rep[ResourceId] = column[ResourceId]("resource_id")
def contentType: Rep[Option[ContentType]] = column[Option[ContentType]]("content_type")
def contentName: Rep[String] = column[String]("content_name")
override def * : ProvenShape[Content] = (id :: createdAt :: resourceId :: contentType :: contentName :: HNil).mappedWith(Generic[Content])
def resourceIdFk: ForeignKeyQuery[ResourceTable, Resource] = foreignKey(s"fk_${contentTableName}_resource_id", resourceId, resourceTableQuery)(_.id)
}
lazy val contentTableQuery: TableQuery[ContentTable] = TableQuery[ContentTable]
object ContentInterpreter extends (ContentJdbcDSL ~> DBIO) {
override def apply[A](fa: ContentJdbcDSL[A]): DBIO[A] = fa match {
case Create(content) => (contentTableQuery returning contentTableQuery.map(_.id) into ((v, _) => v)) += content
}
}
}
开发者ID:dborisenko,项目名称:data-train,代码行数:53,代码来源:ContentJdbcComponent.scala
示例5: contentMetadataTableName
//设置package包名称以及导入依赖的类
package com.dbrsn.datatrain.slick
import cats.~>
import com.dbrsn.datatrain.dsl.meta.ContentMetadataDSL
import com.dbrsn.datatrain.model.Content
import com.dbrsn.datatrain.model.ContentId
import com.dbrsn.datatrain.model.Metadata
import com.dbrsn.datatrain.model.MetadataKey
import com.dbrsn.datatrain.model.MetadataValue
import shapeless.Generic
import shapeless.HNil
import slick.jdbc.JdbcProfile
import slick.lifted.ForeignKeyQuery
import slick.lifted.ProvenShape
import slickless._
trait ContentMetadataJdbcComponent[P <: JdbcProfile] {
self: ContentJdbcComponent[P] =>
val profile: P
val metadataKeyColumnType: MetadataKeyColumnType[P]
import ContentMetadataDSL._
import profile.api._
import metadataKeyColumnType._
type ContentMetadataJdbcDSL[A] = ContentMetadataDSL[A]
def contentMetadataTableName: String = "dt_content_metadata"
class ContentMetadataTable(tag: Tag) extends Table[Metadata[Content]](tag, contentMetadataTableName) {
def id: Rep[ContentId] = column[ContentId]("id", O.PrimaryKey)
def key: Rep[MetadataKey] = column[MetadataKey]("key")
def value: Rep[MetadataValue] = column[MetadataValue]("value")
override def * : ProvenShape[Metadata[Content]] = (id :: key :: value :: HNil).mappedWith(Generic[Metadata[Content]])
def idFk: ForeignKeyQuery[ContentTable, Content] = foreignKey(s"fk_dt_${contentMetadataTableName}_id", id, contentTableQuery)(_.id)
}
lazy val contentMetadataTableQuery: TableQuery[ContentMetadataTable] = TableQuery[ContentMetadataTable]
object ContentMetadataInterpreter extends (ContentMetadataJdbcDSL ~> DBIO) {
override def apply[A](fa: ContentMetadataJdbcDSL[A]): DBIO[A] = fa match {
case Create(metadata) => (contentMetadataTableQuery returning contentMetadataTableQuery.map(_.id) into ((v, _) => v)) += metadata
}
}
}
开发者ID:dborisenko,项目名称:data-train,代码行数:50,代码来源:ContentMetadataJdbcComponent.scala
示例6: MetadataKeyColumnType
//设置package包名称以及导入依赖的类
package com.dbrsn.datatrain.slick
import cats.~>
import com.dbrsn.datatrain.dsl.meta.ResourceMetadataDSL
import com.dbrsn.datatrain.model.Metadata
import com.dbrsn.datatrain.model.MetadataKey
import com.dbrsn.datatrain.model.MetadataValue
import com.dbrsn.datatrain.model.Resource
import com.dbrsn.datatrain.model.ResourceId
import shapeless.Generic
import shapeless.HNil
import slick.jdbc.JdbcProfile
import slick.lifted.ForeignKeyQuery
import slick.lifted.ProvenShape
import slickless._
case class MetadataKeyColumnType[P <: JdbcProfile](implicit columnType: P#BaseColumnType[MetadataKey])
trait ResourceMetadataJdbcComponent[P <: JdbcProfile] {
self: ResourceJdbcComponent[P] =>
val profile: P
val metadataKeyColumnType: MetadataKeyColumnType[P]
import ResourceMetadataDSL._
import profile.api._
import metadataKeyColumnType._
type ResourceMetadataJdbcDSL[A] = ResourceMetadataDSL[A]
def resourceMetadataTableName: String = "dt_resource_metadata"
class ResourceMetadataTable(tag: Tag) extends Table[Metadata[Resource]](tag, resourceMetadataTableName) {
def id: Rep[ResourceId] = column[ResourceId]("id", O.PrimaryKey)
def key: Rep[MetadataKey] = column[MetadataKey]("key")
def value: Rep[MetadataValue] = column[MetadataValue]("value")
override def * : ProvenShape[Metadata[Resource]] = (id :: key :: value :: HNil).mappedWith(Generic[Metadata[Resource]])
def idFk: ForeignKeyQuery[ResourceTable, Resource] = foreignKey(s"fk_dt_${resourceMetadataTableName}_id", id, resourceTableQuery)(_.id)
}
lazy val resourceMetadataTableQuery: TableQuery[ResourceMetadataTable] = TableQuery[ResourceMetadataTable]
object ResourceMetadataInterpreter extends (ResourceMetadataJdbcDSL ~> DBIO) {
override def apply[A](fa: ResourceMetadataJdbcDSL[A]): DBIO[A] = fa match {
case Create(metadata) => (resourceMetadataTableQuery returning resourceMetadataTableQuery.map(_.id) into ((v, _) => v)) += metadata
}
}
}
开发者ID:dborisenko,项目名称:data-train,代码行数:52,代码来源:ResourceMetadataJdbcComponent.scala
示例7: Boot
//设置package包名称以及导入依赖的类
package boot
import controllers.DevicesController
import play.api.ApplicationLoader.Context
import play.api.db.evolutions.EvolutionsComponents
import play.api.db.slick.evolutions.SlickEvolutionsComponents
import play.api.db.slick.{DbName, DefaultSlickApi}
import play.api.{Application, ApplicationLoader, BuiltInComponentsFromContext}
import play.filters.HttpFiltersComponents
import router.Routes
import services.DataSource
import slick.basic.DatabaseConfig
import services.DataSourceJdbc
import slick.jdbc.JdbcProfile
class Boot extends ApplicationLoader {
def load(context: Context): Application = {
val components = new BootComponents(context)
components.applicationEvolutions // Run the evolutions
components.application
}
}
class BootComponents(context: Context)
extends BuiltInComponentsFromContext(context)
with HttpFiltersComponents
with controllers.AssetsComponents
with EvolutionsComponents
with SlickEvolutionsComponents {
override def api: DefaultSlickApi = new DefaultSlickApi(environment, configuration, applicationLifecycle)
private[this] val defaultDBName: DbName = DbName("devices")
private[this] val dbConfig: DatabaseConfig[JdbcProfile] = slickApi.dbConfig[JdbcProfile](defaultDBName)
// TODO put this into config
private[this] val dbPoolSize = 10
private[this] lazy val dataSource: DataSource = new DataSourceJdbc(dbConfig, dbPoolSize)
private[this] lazy val devicesController: DevicesController = new DevicesController(controllerComponents, dataSource)
override lazy val router: Routes = new Routes(httpErrorHandler, devicesController, assets)
}
开发者ID:openada,项目名称:adaweather,代码行数:41,代码来源:Boot.scala
示例8: 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
示例9: 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
示例10: 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
示例11: ChangeAction
//设置package包名称以及导入依赖的类
package eventsource.slick
import akka.actor.Scheduler
import eventsource.models.{Action, Event, VersionedEntity}
import play.api.Logger
import slick.jdbc.JdbcProfile
import scala.concurrent.duration._
import scala.concurrent.{ExecutionContext, Future}
abstract class ChangeAction[Key, ETT, E <: VersionedEntity](
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 findByEventWithLock(event: Event[Key, ETT]): DBIOAction[Option[E], NoStream, Effect.Read]
def applyChange(currentEntity: Option[E],
event: Event[Key, ETT]): DBIOAction[Option[E], NoStream, Effect.All]
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(findByEventWithLock(event).flatMap {
case Some(entity) if event.version == entity.lastModifiedVersion =>
logger.debug(s"lastModifiedVersion=${event.version} already exists. Nothing to do")
DBIO.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 ...")
applyChange(Some(entity), event)
case Some(entity) =>
logger.debug(
s"Got older lastModifiedVersion ${event.version} <= ${entity.lastModifiedVersion} for ${event.key}. Ignoreing ...")
DBIO.successful(None)
case None =>
logger.debug(s"Entity ${event.key} does not exists, ignore update")
applyChange(None, event)
}.transactionally)
}
}
}
开发者ID:21re,项目名称:play-eventsource,代码行数:50,代码来源:ChangeAction.scala
示例12: UpdateAction
//设置package包名称以及导入依赖的类
package eventsource.slick
import akka.actor.Scheduler
import eventsource.models.{Action, Entity, Event}
import play.api.Logger
import slick.jdbc.JdbcProfile
import scala.concurrent.duration._
import scala.concurrent.{ExecutionContext, Future}
abstract class UpdateAction[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
def applyUpdate(currentEntity: E,
event: Event[Key, ETT]): DBIOAction[Option[E], NoStream, Effect.All]
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")
DBIO.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 ...")
applyUpdate(entity, event)
case Some(entity) =>
logger.debug(
s"Got older lastModifiedVersion ${event.version} <= ${entity.lastModifiedVersion} for ${event.key}. Ignoreing ...")
DBIO.successful(None)
case None =>
logger.debug(s"Entity ${event.key} does not exists, ignore update")
DBIO.successful(None)
}
.transactionally)
}
}
开发者ID:21re,项目名称:play-eventsource,代码行数:52,代码来源:UpdateAction.scala
示例13: 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
示例14: currentJdbcProfile
//设置package包名称以及导入依赖的类
package db
import slick.jdbc.{JdbcProfile, PostgresProfile}
import currentJdbcProfile.profile
private[db] sealed trait DatabaseConfigProvider[P <: JdbcProfile] {
val db: P#Backend#Database
}
private[db] trait JdbcDatabaseConfigProvider extends DatabaseConfigProvider[profile.type] {
import currentJdbcProfile.api.Database
override lazy val db = Database.forConfig("database")
}
private[db] object currentJdbcProfile {
val profile = PostgresProfile
lazy val api = profile.api
}
开发者ID:kkrzys,项目名称:eShop,代码行数:20,代码来源:DatabaseConfigProvider.scala
示例15: instantToTimeStamp
//设置package包名称以及导入依赖的类
package de.twentyone.slick.mappings
import java.sql.Timestamp
import java.time.Instant
import slick.jdbc.JdbcProfile
import slick.jdbc.{GetResult, PositionedParameters, PositionedResult, SetParameter}
trait JavaInstantMappings {
protected val driver: JdbcProfile
import driver.api._
// scalastyle:off
private def instantToTimeStamp(instant: Instant) =
if (instant == null) null else new Timestamp(instant.toEpochMilli)
private def timeStampToInstant(timestamp: Timestamp) =
if (timestamp == null) null else timestamp.toInstant
// scalastyle:on
protected implicit val instantMappedColumnType: JdbcProfile#BaseColumnType[Instant] =
MappedColumnType.base[Instant, Timestamp](
d => instantToTimeStamp(d),
d => timeStampToInstant(d)
)
protected implicit val instantGetResult: GetResult[Instant] = new GetResult[Instant] {
override def apply(positionedResult: PositionedResult): Instant =
timeStampToInstant(positionedResult.nextTimestamp())
}
protected implicit val instantOptionGetResult: GetResult[Option[Instant]] =
new GetResult[Option[Instant]] {
override def apply(positionedResult: PositionedResult): Option[Instant] =
positionedResult.nextTimestampOption().map(timestamp => timeStampToInstant(timestamp))
}
protected implicit val instantSetParameter: SetParameter[Instant] = new SetParameter[Instant] {
override def apply(instant: Instant, positionedParameter: PositionedParameters): Unit =
positionedParameter.setTimestamp(instantToTimeStamp(instant))
}
protected implicit val instantOptionSetParameter: SetParameter[Option[Instant]] =
new SetParameter[Option[Instant]] {
override def apply(instantOption: Option[Instant],
positionedParameter: PositionedParameters): Unit =
positionedParameter.setTimestampOption(
instantOption.map(instant => instantToTimeStamp(instant)))
}
}
开发者ID:21re,项目名称:slick-micro-tools,代码行数:53,代码来源:JavaInstantMappings.scala
示例16: AnyValMapping
//设置package包名称以及导入依赖的类
package de.twentyone.slick.mappings
import slick.jdbc.{GetResult, JdbcProfile, JdbcType, SetParameter}
import scala.reflect.ClassTag
class AnyValMapping[T <: AnyVal, V](anyValApply: (V => T), anyValUnapply: (T => Option[V]))(
implicit val driver: JdbcProfile,
innerGetResult: GetResult[V],
innerOptionGetResult: GetResult[Option[V]],
innerSetParameter: SetParameter[V],
optionInnerSetParameter: SetParameter[Option[V]],
classTag: ClassTag[T])
extends PureMappingSupport {
val getResult: GetResult[T] = getResultPure { positionedResult =>
anyValApply(innerGetResult(positionedResult))
}
val optionGetResult: GetResult[Option[T]] = getResultPure { positionedResult =>
innerOptionGetResult(positionedResult).map(anyValApply)
}
val setParameter: SetParameter[T] = setParameterPure { (value, positionedParameters) =>
innerSetParameter.apply(anyValUnapply(value).get, positionedParameters)
}
val optionSetParameter: SetParameter[Option[T]] = setParameterPure {
(value, positionedParameters) =>
optionInnerSetParameter.apply(value.flatMap(anyValUnapply), positionedParameters)
}
import driver.api._
def mappedColumnType(implicit baseColumnType: BaseColumnType[V]): JdbcType[T] =
MappedColumnType.base[T, V](t => anyValUnapply(t).get, s => anyValApply(s))
}
开发者ID:21re,项目名称:slick-micro-tools,代码行数:38,代码来源:AnyValMapping.scala
示例17: EnumMappings
//设置package包名称以及导入依赖的类
package de.twentyone.slick.mappings
import slick.jdbc.JdbcProfile
import slick.jdbc.{GetResult, SetParameter}
class EnumMappings[T <: Enumeration](enu: T)(implicit val driver: JdbcProfile)
extends PureMappingSupport {
val getResult: GetResult[T#Value] = getResultPure { positionedResult =>
enu.withName(positionedResult.nextString())
}
val optionGetResult: GetResult[Option[T#Value]] = getResultPure { positionedResult =>
positionedResult.nextStringOption().map(enu.withName)
}
val setParameter: SetParameter[T#Value] = setParameterPure { (value, positionedParameters) =>
positionedParameters.setString(value.toString)
}
val optionSetParameter: SetParameter[Option[T#Value]] = setParameterPure {
(value, positionedParameters) =>
positionedParameters.setStringOption(value.map(v => value.toString))
}
import driver.api._
val mappedColumnType = MappedColumnType.base[T#Value, String](_.toString, s => enu.withName(s))
}
开发者ID:21re,项目名称:slick-micro-tools,代码行数:29,代码来源:EnumMappings.scala
示例18: DAL
//设置package包名称以及导入依赖的类
package com.github.oopman.collectioneer.model
import java.sql.Timestamp
import java.time.Instant
import slick.jdbc.JdbcProfile
class DAL(val driver: JdbcProfile) extends Tables with DriverComponent {
import driver.api._
val now = Timestamp.from(Instant.now)
val create = (
categories.schema ++ collections.schema ++ items.schema ++ collectionItems.schema ++
collectionParentCollections.schema ++ tags.schema ++ tagCollections.schema ++ tagItems.schema).create
val populateCollections = collections.map(c => (c.name, c.dateTimeCreated, c.dateTimeModified)) ++= Seq(
("Bits", now, now),
("Bobs", now, now),
("Misc", now, now)
)
}
开发者ID:OOPMan,项目名称:Collectioneer,代码行数:23,代码来源:DAL.scala
示例19: DBController
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.{Inject, Singleton}
import dao.{DatabrickAuditLogDAO, UserDAO}
import play.api.db.slick.{DatabaseConfigProvider, HasDatabaseConfigProvider}
import play.api.mvc.{AbstractController, ControllerComponents}
import slick.jdbc.JdbcProfile
import scala.concurrent.ExecutionContext
@Singleton
class DBController @Inject()(
userDao:UserDAO,
databrickAuditLogDao: DatabrickAuditLogDAO,
protected val dbConfigProvider: DatabaseConfigProvider,
cc: ControllerComponents
)
(implicit ec: ExecutionContext)
extends AbstractController(cc) with HasDatabaseConfigProvider[JdbcProfile] {
def init = Action { implicit request =>
Ok("success")
}
}
开发者ID:bkstha,项目名称:my-log-api,代码行数:27,代码来源:DBController.scala
示例20: DAO
//设置package包名称以及导入依赖的类
import cog.ty.scraper.{Challenge, Difficulty, Response, User}
import slick.lifted.{ProvenShape, Tag}
import slick.jdbc.JdbcProfile
import java.util.Date
import java.net.URL
class DAO(driver: JdbcProfile) {
import driver.api._
class Users(tag: Tag) extends Table[User](tag, "USERS") {
def username = column[String]("USERNAME", O.PrimaryKey)
override def * : ProvenShape[User] = username <> (User.apply, User.unapply)
}
val users = TableQuery[Users]
class Challenges(tag: Tag) extends Table[Challenge](tag, "CHALLENGES") {
def id = column[String]("ID", O.PrimaryKey)
def created = column[Date]("CREATED")
def link = column[String]("LINK")
def title = column[String]("TITLE")
def body = column[String]("BODY")
def difficulty = column[String]("DIFFICULTY")
override def * : ProvenShape[Challenge] = (id, created, link, title, body, difficulty) <> (
(row: (String, Date, String, String, String, String)) =>
Challenge(row._1, row._2, new URL(row._3), row._4, row._5, Difficulty(row._6)),
(ch: Challenge) =>
Some(ch.id, ch.created, ch.link.toString, ch.title, ch.body, ch.difficulty.difficulty))
}
val challenges = TableQuery[Challenges]
class Responses(tag: Tag) extends Table[(String, String, String, Date, Option[String], String)](tag, "RESPONSES") {
def id = column[String]("ID", O.PrimaryKey)
def challengeID = column[String]("CHALLENGE_ID")
def username = column[String]("USERNAME")
def created = column[Date]("CREATED")
def link = column[Option[String]]("LINK")
def body = column[String]("BODY")
def challenge = foreignKey("CHALLENGE_ID", challengeID, challenges)(_.id, onUpdate=ForeignKeyAction.Restrict, onDelete=ForeignKeyAction.Cascade)
def user = foreignKey("USERNAME", username, users)(_.username, onUpdate=ForeignKeyAction.Restrict, onDelete=ForeignKeyAction.Cascade)
override def * : (Rep[String], Rep[String], Rep[String], Rep[Date], Rep[Option[String]], Rep[String]) =
(id, challengeID, username, created, link, body)
}
object responses extends TableQuery(new Responses(_)) {
def insertRow(id: String, chId: String, uname: String, created: Date, link: Option[String], body: String) = {
this += ((id, chId, uname, created, link, body))
}
val insertCompiled = Compiled(insertRow _)
// def insertResponse(r: Response) = insertCompiled(r.id, r.challenge.id, r.user.username, r.created, r.link.map(_.toString), r.body)
}
}
开发者ID:Ophirr33,项目名称:daily-programmer-scraper,代码行数:52,代码来源:tables.scala
注:本文中的slick.jdbc.JdbcProfile类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论