本文整理汇总了Scala中slick.basic.DatabaseConfig类的典型用法代码示例。如果您正苦于以下问题:Scala DatabaseConfig类的具体用法?Scala DatabaseConfig怎么用?Scala DatabaseConfig使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了DatabaseConfig类的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: 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")
}
}
示例2: 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)
}
示例3: ExampleApplicationLoader
//设置package包名称以及导入依赖的类
package config
import _root_.controllers.AssetsComponents
import authentication.AuthenticationsComponents
import be.objectify.deadbolt.scala.ActionBuilders
import play.api.ApplicationLoader.Context
import play.api._
import play.api.db.evolutions.{DynamicEvolutions, EvolutionsComponents}
import play.api.db.slick._
import play.api.db.slick.evolutions.SlickEvolutionsComponents
import play.api.i18n._
import play.api.libs.ws.ahc.AhcWSComponents
import play.api.routing.Router
import play.filters.HttpFiltersComponents
import slick.basic.{BasicProfile, DatabaseConfig}
import users.UsersComponents
class ExampleApplicationLoader extends ApplicationLoader {
def load(context: Context): Application = new ExampleComponents(context).application
}
class ExampleComponents(context: Context) extends BuiltInComponentsFromContext(context)
with SlickComponents
with SlickEvolutionsComponents
with AssetsComponents
with I18nComponents
with HttpFiltersComponents
with EvolutionsComponents
with AhcWSComponents
with AuthenticationsComponents
with UsersComponents {
override lazy val slickApi: SlickApi =
new DefaultSlickApi(environment, configuration, applicationLifecycle)(executionContext)
override lazy val databaseConfigProvider: DatabaseConfigProvider = new DatabaseConfigProvider {
def get[P <: BasicProfile]: DatabaseConfig[P] = slickApi.dbConfig[P](DbName("default"))
}
override lazy val dynamicEvolutions: DynamicEvolutions = new DynamicEvolutions
def onStart(): Unit = {
// applicationEvolutions is a val and requires evaluation
applicationEvolutions
}
onStart()
// set up logger
LoggerConfigurator(context.environment.classLoader).foreach {
_.configure(context.environment, context.initialConfiguration, Map.empty)
}
lazy val actionBuilders: ActionBuilders = createActionBuilders(playBodyParsers)
lazy val router: Router = Router.from(userRoutes.orElse(authenticationRoutes))
}
示例4: patienceConfig
//设置package包名称以及导入依赖的类
package com.github.j5ik2o.scala.ddd.functional.slick
import com.github.j5ik2o.scala.ddd.functional.slick.test.FlywayWithMySQLSpecSupport
import com.typesafe.config.ConfigFactory
import org.scalatest.TestSuite
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.time.{ Millis, Seconds, Span }
import slick.basic.DatabaseConfig
import slick.jdbc.JdbcProfile
import scala.concurrent.ExecutionContext
trait Slick3SpecSupport extends ScalaFutures { this: TestSuite with FlywayWithMySQLSpecSupport =>
override implicit def patienceConfig: PatienceConfig =
PatienceConfig(timeout = scaled(Span(5, Seconds)), interval = scaled(Span(15, Millis)))
private var _dbConfig: DatabaseConfig[JdbcProfile] = _
private var _profile: JdbcProfile = _
private var _ec: ExecutionContext = _
def jdbcPort: Int = mySQLdConfig.port.get
protected def dbConfig = _dbConfig
protected def profile = _profile
implicit def ec: ExecutionContext = _ec
def startSlick(): Unit = {
val config = ConfigFactory.parseString(s"""
|free {
| profile = "slick.jdbc.MySQLProfile$$"
| db {
| connectionPool = disabled
| driver = "com.mysql.jdbc.Driver"
| url = "jdbc:mysql://localhost:$jdbcPort/free?useSSL=false"
| user = "free"
| password = "passwd"
| }
|}
""".stripMargin)
_dbConfig = DatabaseConfig.forConfig[JdbcProfile]("free", config)
_profile = dbConfig.profile
_ec = dbConfig.db.executor.executionContext
}
def stopSlick(): Unit = {
dbConfig.db.shutdown
}
}
示例5: DatabaseMessageOwnership
//设置package包名称以及导入依赖的类
package score.discord.generalbot.functionality.ownership
import net.dv8tion.jda.core.JDA
import net.dv8tion.jda.core.entities.{Message, User}
import score.discord.generalbot.collections.Cache
import score.discord.generalbot.util.DBUtils
import score.discord.generalbot.wrappers.jda.Conversions._
import score.discord.generalbot.wrappers.jda.ID
import slick.basic.DatabaseConfig
import slick.jdbc.JdbcProfile
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
class DatabaseMessageOwnership(dbConfig: DatabaseConfig[_ <: JdbcProfile],
cacheBase: Cache[ID[Message], Option[ID[User]]]) extends MessageOwnership {
import dbConfig.profile.api._
private class MessageOwnershipTable(tag: Tag, name: String) extends Table[(ID[Message], ID[User])](tag, name) {
val messageId = column[ID[Message]]("message", O.PrimaryKey)
val userId = column[ID[User]]("user")
override def * = (messageId, userId)
}
private val database = dbConfig.db
private val tableName = "message_ownership"
private val messageOwnershipTable = TableQuery[MessageOwnershipTable](new MessageOwnershipTable(_: Tag, tableName))
private val lookupQuery = Compiled((messageId: ConstColumn[ID[Message]]) => {
messageOwnershipTable.filter(t => t.messageId === messageId).map(_.userId)
})
DBUtils.ensureTableCreated(dbConfig, messageOwnershipTable, tableName)
private[this] val cache = new cacheBase.Backend[ID[Message]] {
override def keyToId(key: ID[Message]): ID[Message] = key
override def missing(key: ID[Message]): Future[Option[ID[User]]] =
database.run(lookupQuery(key).result).map(_.headOption)
}
override def apply(jda: JDA, messageId: ID[Message]): Future[Option[User]] =
cache(messageId).map(_ flatMap jda.findUser)
override def update(message: Message, user: User): Unit = {
cache(message.id) = Some(user.id)
database.run(messageOwnershipTable.insertOrUpdate(message.id, user.id))
}
override def remove(messageId: ID[Message]): Unit = {
database.run(lookupQuery(messageId).delete).foreach { _ =>
cache.invalidate(messageId)
}
}
}
示例6: DBUtils
//设置package包名称以及导入依赖的类
package score.discord.generalbot.util
import slick.basic.DatabaseConfig
import slick.jdbc.meta.MTable
import slick.lifted.TableQuery
import slick.relational.RelationalProfile
import scala.concurrent.Await
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration.Duration
object DBUtils {
def ensureTableCreated(dbConfig: DatabaseConfig[_ <: RelationalProfile],
table: TableQuery[_ <: RelationalProfile#Table[_]],
tableName: String) {
import dbConfig.profile.api._
// Ensure table is created on startup
Await.result(dbConfig.db.run(MTable.getTables).map(v => {
val names = v.map(mt => mt.name.name)
if (!names.contains(tableName)) {
Await.result(dbConfig.db.run(table.schema.create), Duration.Inf)
}
}), Duration.Inf)
}
}
示例7: CommandPermissionLookup
//设置package包名称以及导入依赖的类
package score.discord.generalbot.collections
import net.dv8tion.jda.core.entities.{Guild, ISnowflake, Role}
import score.discord.generalbot.command.Command
import score.discord.generalbot.util.DBUtils
import score.discord.generalbot.wrappers.jda.Conversions._
import score.discord.generalbot.wrappers.jda.ID
import slick.basic.DatabaseConfig
import slick.jdbc.JdbcProfile
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
class CommandPermissionLookup(dbConfig: DatabaseConfig[_ <: JdbcProfile],
cacheBase: Cache[(ID[Command], ID[Guild]), Option[ID[Role]]],
tableName: String) {
import dbConfig.profile.api._
private class CommandPermissionTable(tag: Tag) extends Table[(ID[Command], ID[Guild], ID[Role])](tag, tableName) {
val commandId = column[ID[Command]]("command")
val guildId = column[ID[Guild]]("guild")
val roleId = column[ID[Role]]("role")
val pk = primaryKey("primary", (commandId, guildId))
override def * = (commandId, guildId, roleId)
}
private val commandPermissionTable = TableQuery[CommandPermissionTable]
private[this] val lookupQuery = Compiled((commandId: ConstColumn[ID[Command]], guildId: ConstColumn[ID[Guild]]) =>
commandPermissionTable.filter(t => t.commandId === commandId && t.guildId === guildId).map(_.roleId)
)
private[this] val cache = new cacheBase.Backend[(Command with ISnowflake, Guild)] {
override def keyToId(key: (Command with ISnowflake, Guild)): (ID[Command], ID[Guild]) = (key._1.id, key._2.id)
override def missing(key: (Command with ISnowflake, Guild)): Future[Option[ID[Role]]] =
dbConfig.db.run(lookupQuery(key._1.id, key._2.id).result).map(_.headOption)
}
DBUtils.ensureTableCreated(dbConfig, commandPermissionTable, tableName)
def apply(command: Command with ISnowflake, guild: Guild, default: Option[Role] = None): Future[Option[Role]] =
cache((command, guild)).map(_ map guild.findRole getOrElse default)
def update(command: Command with ISnowflake, guild: Guild, role: Role): Unit = {
cache((command, guild)) = Some(role.id)
dbConfig.db.run(commandPermissionTable.insertOrUpdate(command.id, guild.id, role.id))
}
def remove(command: Command with ISnowflake, guild: Guild) {
cache((command, guild)) = None
dbConfig.db.run(lookupQuery(command.id, guild.id).delete)
}
}
示例8: StringByMessage
//设置package包名称以及导入依赖的类
package score.discord.generalbot.collections
import net.dv8tion.jda.core.entities.Message
import score.discord.generalbot.util.DBUtils
import score.discord.generalbot.wrappers.jda.ID
import slick.basic.DatabaseConfig
import slick.jdbc.JdbcProfile
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
class StringByMessage(dbConfig: DatabaseConfig[_ <: JdbcProfile],
cacheBase: Cache[ID[Message], Option[String]],
tableName: String) {
import dbConfig.profile.api._
private class StringByMessage(tag: Tag, name: String) extends Table[(ID[Message], String)](tag, name) {
val messageId = column[ID[Message]]("message", O.PrimaryKey)
val text = column[String]("text")
override def * = (messageId, text)
}
private val database = dbConfig.db
private val stringByMessage = TableQuery[StringByMessage](new StringByMessage(_: Tag, tableName))
private val lookupQuery = Compiled({ (id: ConstColumn[ID[Message]]) =>
stringByMessage.filter(t => t.messageId === id).map(_.text)
})
DBUtils.ensureTableCreated(dbConfig, stringByMessage, tableName)
private[this] val cache = new cacheBase.Backend[ID[Message]] {
override def keyToId(key: ID[Message]): ID[Message] = key
override def missing(key: ID[Message]): Future[Option[String]] =
database.run(lookupQuery(key).result).map(_.headOption)
}
def apply(messageId: ID[Message]): Future[Option[String]] = cache(messageId)
def update(messageId: ID[Message], text: String) {
cache(messageId) = Some(text)
database.run(stringByMessage.insertOrUpdate(messageId, text))
}
def remove(messageId: ID[Message]) {
database.run(lookupQuery(messageId).delete).foreach { _ =>
cache.invalidate(messageId)
}
}
}
示例9: RoleByGuild
//设置package包名称以及导入依赖的类
package score.discord.generalbot.collections
import net.dv8tion.jda.core.entities.{Guild, Role}
import score.discord.generalbot.util.DBUtils
import score.discord.generalbot.wrappers.jda.Conversions._
import score.discord.generalbot.wrappers.jda.ID
import slick.basic.DatabaseConfig
import slick.jdbc.JdbcProfile
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
class RoleByGuild(dbConfig: DatabaseConfig[_ <: JdbcProfile],
cacheBase: Cache[ID[Guild], Option[ID[Role]]],
tableName: String) {
import dbConfig.profile.api._
private class RoleByGuild(tag: Tag, name: String) extends Table[(ID[Guild], ID[Role])](tag, name) {
val guildId = column[ID[Guild]]("guild", O.PrimaryKey)
val roleId = column[ID[Role]]("role")
override def * = (guildId, roleId)
}
private val database = dbConfig.db
private val roleByGuildTable = TableQuery[RoleByGuild](new RoleByGuild(_: Tag, tableName))
private val lookupQuery = Compiled((guildId: ConstColumn[ID[Guild]]) => {
roleByGuildTable.filter(t => t.guildId === guildId).map(_.roleId)
})
private val cache = new cacheBase.Backend[Guild] {
override def keyToId(key: Guild): ID[Guild] = key.id
override def missing(key: Guild): Future[Option[ID[Role]]] =
dbConfig.db.run(lookupQuery(key.id).result).map(_.headOption)
}
DBUtils.ensureTableCreated(dbConfig, roleByGuildTable, tableName)
def apply(guild: Guild): Future[Option[Role]] = cache(guild).map(_.flatMap(guild.findRole))
def update(guild: Guild, role: Role) {
cache(guild) = Some(role.id)
database.run(roleByGuildTable.insertOrUpdate(guild.id, role.id))
}
def remove(guild: Guild): Unit = remove(guild.id)
def remove(guild: ID[Guild]) {
cache.updateById(guild, None)
database.run(lookupQuery(guild).delete)
}
}
示例10: TableSchemaPreparation
//设置package包名称以及导入依赖的类
package com.ltk.auth.db
import com.google.inject.Inject
import com.ltk.auth.Configuration
import com.ltk.auth.Predef._
import com.ltk.auth.db.table.{TokenTable, UserInfoTable, UserTable}
import slick.basic.DatabaseConfig
import slick.jdbc.JdbcProfile
import slick.jdbc.meta.MTable
import scala.util.Try
class TableSchemaPreparation @Inject() (override val dbConfig: DatabaseConfig[JdbcProfile])
extends DatabaseComponent with UserTable with UserInfoTable with TokenTable {
import dbConfig.profile.api._
val tables = Set((usersTable.schema, userTableName),
(usersInfoTable.schema, userInfoTableName),
(tokenTable.schema, tokenTableName))
val existingTables: Try[Vector[MTable]] = repeat(Configuration.retries) {
db.run(MTable.getTables)
}
val toCreateSchemas: Set[String] = tables.filterNot { table =>
existingTables
.getOrElse(Vector())
.map(_.name.name)
.contains(table._2)
}.map(_._2)
repeatWithExceptionCondition(Configuration.retries) {
db.run(tables
.filter(table => toCreateSchemas.contains(table._2))
.map(_._1)
.reduceLeft(_ ++ _)
.create)
}(toCreateSchemas.nonEmpty)
}
示例11: UserInfoRepositoryImpl
//设置package包名称以及导入依赖的类
package com.ltk.auth.db.repository
import com.google.inject.{Inject, Singleton}
import com.ltk.auth.db.DatabaseComponent
import com.ltk.auth.db.table.UserInfoTable
import com.ltk.auth.dto.UserInfo
import slick.basic.DatabaseConfig
import slick.jdbc.JdbcProfile
import scala.concurrent.{ExecutionContext, Future}
@Singleton
class UserInfoRepositoryImpl @Inject() (override val dbConfig: DatabaseConfig[JdbcProfile]) extends DatabaseComponent
with UserInfoTable with UserInfoRepository {
import dbConfig.profile.api._
implicit private val executionContext: ExecutionContext = dbConfig.db.executor.executionContext
override def get(userId: Long, attrName: String): Future[Option[UserInfo]] = {
db.run { usersInfoTable
.filter(_.userId === userId)
.filter(_.attrName === attrName)
.result
.headOption
}
}
override def put(info: UserInfo): Future[Int] = {
get(info.userId, info.attrName).flatMap {
case Some(_) => db.run { usersInfoTable
.filter(_.userId === info.userId)
.filter(_.attrName === info.attrName)
.map(_.attrValue)
.update(info.attrValue)
}
case None => db.run(usersInfoTable += info)
}
}
override def getAll(userId: Long): Future[Seq[UserInfo]] = {
db.run { usersInfoTable
.filter(_.userId === userId)
.result
}
}
override def remove(userId: Long, attrName: String): Future[Int] = {
db.run { usersInfoTable
.filter(_.userId === userId)
.filter(_.attrName === attrName)
.delete
}
}
}
示例12: DatabaseUnitSpec
//设置package包名称以及导入依赖的类
package com.ltk.auth
import java.util.concurrent.atomic.AtomicBoolean
import com.ltk.auth.TestData.UserData
import com.ltk.auth.db.repository.UserRepositoryImpl
import com.ltk.auth.db.{DatabaseConnectionFactory, TableSchemaPreparation}
import com.ltk.auth.dto.User
import org.scalatest.BeforeAndAfterAll
import slick.basic.DatabaseConfig
import slick.jdbc.JdbcProfile
import scala.concurrent.Await
import scala.concurrent.duration._
import scala.language.postfixOps
abstract class DatabaseUnitSpec extends UnitSpec with BeforeAndAfterAll {
protected val dbConfig: DatabaseConfig[JdbcProfile] = DatabaseConnectionFactory.initialize()
protected val defaultUser: User = CrossSuitesData.defaultUser
implicit protected val duration: Duration = 1 minute
override def beforeAll(): Unit = {
if (!CrossSuitesData.tableSchemaWasCreated) {
CrossSuitesData.getClass.synchronized {
if (!CrossSuitesData.tableSchemaWasCreated) {
new TableSchemaPreparation(dbConfig)
Await.result(new UserRepositoryImpl(dbConfig).save(defaultUser), duration)
CrossSuitesData.tableSchemaWasCreated = true
}
}
}
}
override def afterAll(): Unit = {
dbConfig.db.close()
}
}
object CrossSuitesData {
@volatile var tableSchemaWasCreated: Boolean = false
val defaultUser: User = UserData.valid.copy(id = Some(1))
}