当前位置: 首页>>代码示例>>Scala>>正文


Scala DatabaseConfig类代码示例

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


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

示例1: Restaurante

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

import javax.inject._
import play.api.Application
import slick.driver.JdbcProfile
import slick.driver.MySQLDriver.api._
import play.api.db.slick.DatabaseConfigProvider
import slick.backend.DatabaseConfig
import scala.concurrent.Future


case class Restaurante (var id:Int,var nombre:String,var direccion:String)


class RestauranteTableDef(tag: Tag) extends Table[Restaurante](tag, "Restaurantes") {

  def id = column[Int]("id", O.PrimaryKey,O.AutoInc)
  def nombre = column[String]("Nombre")
  def direccion = column[String]("Direccion")

  override def * =
    (id, nombre, direccion) <>(Restaurante.tupled, Restaurante.unapply)
}

class Restaurantes @Inject() (appProvider: Provider[Application]) {

  def dbConfig(): DatabaseConfig[JdbcProfile] =
        DatabaseConfigProvider.get[JdbcProfile](appProvider.get())

  val restaurantes = TableQuery[RestauranteTableDef]

  var lista :List[Restaurante]={
    List(
      Restaurante(
        3
        ,"La casa blanca"
        ,"Argentina"
      ),
      Restaurante(
        4
        ,"La casa rosta"
        ,"Manizales"
      )
    )
  }

  def adicionar(restaurante: Restaurante)={
    lista = lista ::: List(restaurante)
  }

  def traerTodo:Future[Seq[Restaurante]]={
    dbConfig().db.run(restaurantes.result)
  }
} 
开发者ID:arbeyvillegas,项目名称:Restaurante,代码行数:55,代码来源:Restaurante.scala

示例2: UserDao

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

import javax.inject.Inject

import models.{Page, User, Users}
import slick.backend.DatabaseConfig
import slick.driver.JdbcProfile
import slick.driver.PostgresDriver.api._

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future

class UserDao @Inject() (val dbConfig: DatabaseConfig[JdbcProfile]) extends Dao[User] {

  private lazy val users = TableQuery[Users]

  
  private def count(filter: String): Future[Int] = {
    dbConfig.db.run(users.filter(_.fullName.toLowerCase like filter.toLowerCase()).length.result)
  }

  override def insert(user: User): Future[Int] = {
    dbConfig.db.run(users += user)
  }

  override def count: Future[Int] = {
    dbConfig.db.run(users.length.result)
  }

  override def update(id: Long, user: User): Future[Int] = {
    dbConfig.db.run(filterQuery(id).update(user))
  }

  override def findById(id: Long): Future[User] = {
    dbConfig.db.run(filterQuery(id).result.head)
  }

  override def delete(id: Long): Future[Int] = {
    dbConfig.db.run(filterQuery(id).delete)
  }

  override def list(page: Int = 0, pageSize: Int = 10, orderBy: Int = 1, filter: String = "%"): Future[Page[User]] = {
    val offset = pageSize * page
    val query =
      (for {
        user <- users if user.fullName.toLowerCase like filter.toLowerCase
      } yield user).drop(offset).take(pageSize)
    val totalRows = count(filter)
    val result = dbConfig.db.run(query.result)
    result flatMap (employees => totalRows map (rows => Page(employees, page, offset, rows)))
  }
} 
开发者ID:cloudwicklabs,项目名称:play-cloudwickone-slick-template,代码行数:53,代码来源:UserDao.scala

示例3: TagDao

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

import models.{Tag => TagM, TagTable}
import slick.backend.DatabaseConfig
import slick.driver.JdbcProfile
import scala.concurrent.Future
import play.api.libs.concurrent.Execution.Implicits.defaultContext

class TagDao(dbConfig: DatabaseConfig[JdbcProfile]) extends BaseDao[TagM] {
  import dbConfig.driver.api._

  val db = dbConfig.db
  val tags = TableQuery[TagTable]

  def add(tag: TagM): Future[TagM] = {
    db.run(tagsReturningRow += tag)
  }

  def findAll(): Future[Seq[TagM]] = db.run(tags.result)

  override def findById(id: Long): Future[Option[TagM]] =
    db.run(tags.filter(_.id === id).result.headOption)

  def findByName(name: String): Future[Option[TagM]] =
    db.run(tags.filter(_.text === name).result.headOption)

  override def remove(id: Long): Future[Int] =
    db.run(tags.filter(_.id === id).delete)

  private def tagsReturningRow =
    tags returning tags.map(_.id) into { (b, id) =>
      b.copy(id = id)
    }
} 
开发者ID:greven77,项目名称:PlaySlickTest,代码行数:35,代码来源:TagDao.scala

示例4: 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

示例5: ComandoController

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

import javax.inject._

import domain.PersonExample1
import persistence.repos.personRepoReader
import play.api.libs.json.Json
import play.api.mvc._
import slick.backend.DatabaseConfig
import slick.driver.JdbcProfile

import scala.concurrent.ExecutionContext

@Singleton
class ComandoController @Inject() extends Controller {

  def insertarPersonaReader() = Action.async { request =>
    implicit val empleadoFormat = Json.format[PersonExample1]
    val json = request.body.asJson.get
    val p = json.as[PersonExample1]
    implicit val ec: ExecutionContext = persistence.repos.personaRepoCommandExecutionContext
    val dbconfig: DatabaseConfig[JdbcProfile] = DatabaseConfig.forConfig[JdbcProfile]("slick.dbs.mydatabase")
    personRepoReader.insert(p)
      .run(dbconfig)
      .map{
        x =>  Ok("Persona insertada")
      }
      .recover{
        case e: Exception =>  InternalServerError(s"Ha ocurrido un error en insertarPersonaReader: ${e}")
      }


  }
} 
开发者ID:julianGonzalezV,项目名称:scala-play-micros-basepj,代码行数:35,代码来源:ComandoController.scala

示例6: MysqlDBConnection

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

import slick.driver.JdbcProfile
import slick.backend.DatabaseConfig
import slick.jdbc.JdbcBackend.Database


trait DBConnectionComponent {
  
  val dbConnection: DBConnection
  
  class MysqlDBConnection extends DBConnection {
    lazy val profile = slick.driver.MySQLDriver
    lazy val config:String = "default"
    lazy val dc = DatabaseConfig.forConfig[JdbcProfile](config)
    
  }
}
trait DBConnection {
   val dc: DatabaseConfig[JdbcProfile]
   val profile: slick.driver.JdbcProfile
   val db = dc.db
} 
开发者ID:sushanttal,项目名称:BookSharing,代码行数:24,代码来源:DBConnection.scala

示例7: DetailsToDB

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

import models.Tables.{TesttakenRow, UsersRow}
import java.util.Calendar

import play.api.libs.json._
import slick.dbio
import play.api.db.slick.DatabaseConfigProvider
import slick.backend.DatabaseConfig
import slick.dbio.Effect
import slick.lifted.Query
import slick.dbio
import slick.driver.PostgresDriver.api._

import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.impl.Future

object DetailsToDB {
  def createUser(userRow: UsersRow) = {
    val insert = dbio.DBIO.seq(userTable += userRow)
    dbConfig.db.run(insert)
  }




  def insertTest(testTakenRow: TesttakenRow) = {
    val insert = dbio.DBIO.seq(testTakenTable += testTakenRow)
    dbConfig.db.run(insert)
  }

} 
开发者ID:pandiarajan277,项目名称:dcapp,代码行数:34,代码来源:DetailsToDB.scala

示例8: SubscriptionRepository

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

import javax.inject.Inject

import models.entity.Subscription
import play.api.db.slick.DatabaseConfigProvider
import slick.backend.DatabaseConfig
import slick.driver.JdbcProfile

import scala.concurrent.Future


class SubscriptionRepository @Inject()(protected val tables: Tables,
                                       protected val dbConfigProvider: DatabaseConfigProvider) {


  val dbConfig: DatabaseConfig[JdbcProfile] = dbConfigProvider.get[JdbcProfile]
  val db = dbConfig.db

  import dbConfig.driver.api._

  val Subscriptions = TableQuery[tables.SubscriptionTable]

  def getAll(): Future[Seq[Subscription]] = db.run {
    Subscriptions.result
  }

  def getByManga(mangaId: Int): Future[Option[Subscription]] = db.run {
    Subscriptions.filter(s => s.mangaId === mangaId).result.headOption
  }
  def getByMangaAndUser(mangaId: Int, userId: Int):Future[Option[(String, String)]] = {
    //    Subscriptions.filter(s => s.mangaId === mangaId && s.userId === userId).returning().map(_.)
    val Mangas = TableQuery[tables.MangaTable]
    val Users = TableQuery[tables.UserTable]

    val query: Query[(Rep[String], Rep[String]), (String, String), Seq] = for {
      (s1, m) <- Subscriptions join Mangas on (_.mangaId === _.id)
      (s2, u) <- Subscriptions join Users on (_.userId === _.id)
    } yield (m.title, u.email)

    val r: Future[Option[(String, String)]] = db.run {
      query.result.headOption
    }
    r
  }

  def insert(subscription: Subscription) = db.run {
    Subscriptions += subscription
  }

} 
开发者ID:LeonardoZ,项目名称:scrapms,代码行数:52,代码来源:SubscriptionRepository.scala

示例9: IncomeOutcomeDAO

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

import java.sql.Date
import javax.inject.Inject

import models.{IncomeOutcome, User}
import play.api.db.slick.DatabaseConfigProvider
import play.db.NamedDatabase
import slick.backend.DatabaseConfig
import slick.driver.JdbcProfile
import slick.driver.SQLiteDriver.api._
import slick.lifted.{ForeignKeyQuery, ProvenShape}
import utils.Const

import scala.concurrent.{ExecutionContext, Future}

class IncomeOutcomeDAO @Inject()(@NamedDatabase(Const.DbName) dbConfigProvider: DatabaseConfigProvider,
                                 val userDAO: UserDAO)(implicit executionContext: ExecutionContext) {
  private val dbConfig: DatabaseConfig[JdbcProfile] = dbConfigProvider.get[JdbcProfile]
  // initialisation of foreign keys in SQLite
  dbConfig.db.run(DBIO.seq(sqlu"PRAGMA foreign_keys = ON;")).map { _ => () }

  private val incomesOutcomes: TableQuery[IncomeOutcomeTable] = TableQuery[IncomeOutcomeTable]

  def insert(incomeOutcome: IncomeOutcome): Future[Unit] = {
    dbConfig.db.run(incomesOutcomes += incomeOutcome).map { _ => () }
  }

  def findAll(userEmail: String): Future[Seq[IncomeOutcome]] = {
    dbConfig.db.run(incomesOutcomes.join(userDAO.users).on(_.userId === _.id).filter(_._2.email === userEmail)
      .map(_._1).result)
  }

  private class IncomeOutcomeTable(tag: Tag) extends Table[IncomeOutcome](tag, "income_outcome") {
    def id: Rep[Int] = column[Int]("id", O.PrimaryKey, O.AutoInc)
    def userId: Rep[Int] = column[Int]("userId")
    def date: Rep[Date] = column[Date]("date")
    def income: Rep[Double] = column[Double]("income")
    def outcome: Rep[Double] = column[Double]("outcome")

    // A reified foreign key relation to an user that can be navigated to create a join
    // n to one relationship
    def user: ForeignKeyQuery[userDAO.UserTable, User] = {
      // when an user is deleted, his income and outcome values are also deleted (same with update)
      foreignKey("user_FK", userId, userDAO.users)(_.id, onDelete = ForeignKeyAction.Cascade,
        onUpdate = ForeignKeyAction.Cascade)
    }

    def * : ProvenShape[IncomeOutcome] = {
      (date, income, outcome, userId) <> ((IncomeOutcome.apply _).tupled, IncomeOutcome.unapply)
    }
  }
} 
开发者ID:MathieuUrstein,项目名称:HEIG.SCALA.Projet,代码行数:54,代码来源:IncomeOutcomeDAO.scala

示例10: Application

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

import scala.concurrent.Await
import scala.concurrent.Future
import scala.concurrent.duration.Duration

import javax.inject.Inject
import models.Flavor
import models.Flavors
import models.Ratings
import models.Roasting
import models.Roastings
import play.api.db.slick.DatabaseConfigProvider
import play.api.mvc.Action
import play.api.mvc.Controller
import slick.backend.DatabaseConfig
import slick.driver.H2Driver.api.Database
import slick.driver.H2Driver.api.streamableQueryActionExtensionMethods
import slick.driver.JdbcProfile

class Application @Inject()(dbConfigProvider: DatabaseConfigProvider) extends Controller {

  def index = Action {
    Ok(views.html.Application.index())
  }

  def debug = Action {
    val dbConfig: DatabaseConfig[JdbcProfile] = dbConfigProvider.get[JdbcProfile]
    val database: Database = dbConfig.db

    val roastingsQuery = Roastings.roastings
    val roastingsAction = roastingsQuery.result
    val roastingsFutureResults: Future[Seq[Roastings#TableElementType]] = database.run(roastingsAction)
    val roastings: Seq[Roasting] = Await.result(roastingsFutureResults, Duration.Inf)

    val flavorQuery = Roastings.roastings.flatMap(_.flavor)
    val flavorAction = flavorQuery.result
    val flavorFutureResult = database.run(flavorAction)
    val flavors: Seq[Flavor] = Await.result(flavorFutureResult, Duration.Inf)

    Ok(views.html.Application.debug(flavors, roastings))
  }
} 
开发者ID:LucidTaZ,项目名称:Coffee,代码行数:44,代码来源:Application.scala

示例11: generateDDL

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

import persistence.dals._
import persistence.entities._
import persitence.handlers.OAuth2DataHandler
import slick.backend.DatabaseConfig
import slick.driver.JdbcProfile

import scalaoauth2.provider.DataHandler


trait Profile {
	val profile: JdbcProfile
}


trait DbModule extends Profile{
	val db: JdbcProfile#Backend#Database
}

trait PersistenceModule {
	val accountsDal: AccountsDal
	val oauthAuthorizationCodesDal: OAuthAuthorizationCodesDal
	val oauthClientsDal: OAuthClientsDal
	val oauthAccessTokensDal:  OAuthAccessTokensDal
	val oauth2DataHandler : DataHandler[Account]
	def generateDDL : Unit
}


trait PersistenceModuleImpl extends PersistenceModule with DbModule{
	this: Configuration  =>

	// use an alternative database configuration ex:
	// private val dbConfig : DatabaseConfig[JdbcProfile]  = DatabaseConfig.forConfig("pgdb")
	private val dbConfig : DatabaseConfig[JdbcProfile]  = DatabaseConfig.forConfig("h2db")

	override implicit val profile: JdbcProfile = dbConfig.driver
	override implicit val db: JdbcProfile#Backend#Database = dbConfig.db

	override val accountsDal = new AccountsDalImpl
	override val oauthAuthorizationCodesDal = new OAuthAuthorizationCodesDalImpl
        override val oauthClientsDal = new OAuthClientsDalImpl(this)
        override val oauthAccessTokensDal = new  OAuthAccessTokensDalImpl(this)
	override val oauth2DataHandler = new OAuth2DataHandler(this)

	override def generateDDL(): Unit = {
		accountsDal.createTable()
		oauthAccessTokensDal.createTable()
		oauthAuthorizationCodesDal.createTable()
		oauthClientsDal.createTable()
	}

} 
开发者ID:cdiniz,项目名称:slick-akka-http-oauth2,代码行数:55,代码来源:PersistenceModule.scala

示例12: syncResult

//设置package包名称以及导入依赖的类
import org.joda.time.DateTime
import play.api.libs.json._
import slick.backend.DatabaseConfig
import slick.driver.MySQLDriver.api._

import scala.concurrent.{Await, Future}
import scala.concurrent.duration.Duration

package object model {
  // settings
  implicit val JavaUtilDateMapper =
    MappedColumnType.base[java.util.Date, java.sql.Timestamp] (
      d => new java.sql.Timestamp(d.getTime),
      d => new java.util.Date(d.getTime))

  val dateFormatter = "yyyy-MM-dd"
  implicit val dateRead1 = (__ \ "updateDate").read[String].map(x => new DateTime(x))
  implicit val dateRead2 = (__ \ "createDate").read[String].map(x => new DateTime(x))
  implicit val dateRead3 = (__ \ "startDate").read[String].map(x => new DateTime(x))
  implicit val dateRead4 = (__ \ "endDate").read[String].map(x => new DateTime(x))

  implicit val jodaDateTimeReads = Reads.jodaDateReads(dateFormatter)
  implicit val jodaDateTimeWrites = Writes.jodaDateWrites(dateFormatter)
  implicit val jodaDateTimeFormats = Format(jodaDateTimeReads, jodaDateTimeWrites)

  // Table Queries
  lazy val users = TableQuery[Users]

  // default methods
  def syncResult[R](action:slick.dbio.DBIOAction[R, slick.dbio.NoStream, scala.Nothing])(implicit dbConfig:DatabaseConfig[_]):R = {
    Await.result(dbConfig.db.run(action), Duration.Inf)
  }

  def asyncResult[R](action:slick.dbio.DBIOAction[R, slick.dbio.NoStream, scala.Nothing])(implicit dbConfig:DatabaseConfig[_]):Future[R] = {
    dbConfig.db.run(action)
  }
} 
开发者ID:cailhuiris,项目名称:play-base,代码行数:38,代码来源:package.scala

示例13: dateTimeMapper

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

import java.sql.Timestamp
import com.netaporter.uri.Uri
import org.joda.time.DateTime
import slick.driver.JdbcProfile
import play.api.db.slick.DatabaseConfigProvider
import play.api.db.slick.HasDatabaseConfig
import play.api.Play
import slick.backend.DatabaseConfig


trait ColumnTypeMapper extends HasDatabaseConfig[JdbcProfile] {
  protected val dbConfig: DatabaseConfig[JdbcProfile] = DatabaseConfigProvider.get[JdbcProfile](Play.current)
  import driver.api._

  implicit def dateTimeMapper = {
    MappedColumnType.base[DateTime, Timestamp] (
      dt => new Timestamp(dt.getMillis),
      ts => new DateTime(ts.getTime)
    )
  }

  implicit def dateTimeOrdering: Ordering[DateTime] = Ordering.fromLessThan(_ isBefore _)

  implicit def uriMapper = MappedColumnType.base[Uri, String] (
    dt => dt.toString(),
    ts => Uri.parse(ts)
  )
} 
开发者ID:marius-carp,项目名称:work-time-app,代码行数:31,代码来源:ColumnTypeMapper.scala

示例14: User

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

import slick.backend.DatabaseConfig
import slick.driver.JdbcProfile

import java.sql.Timestamp
import org.joda.time.Instant


case class User (
  id:           Long,
  login:        String,
  password:     String,
  salt:         Int,
  roleId:       Int,
  connected:    Boolean,
  lastActivity: Option[Instant]
)

trait UserTable {
  val dc: DatabaseConfig[JdbcProfile]

  import dc.driver.api._

  private[UserTable] class Usuarios(tag: Tag) extends Table[User](tag, "users") {
    def id           = column[Long]  ("id", O.PrimaryKey, O.AutoInc)
    def login        = column[String]("login")
    def password     = column[String]("password")
    def salt         = column[Int]("salt")
    def roleId       = column[Int]("role_id")
    def connected    = column[Boolean]("connected")
    def lastActivity = column[Option[Timestamp]]("last_activity")

    def idxLogin = index("uk_login", login, unique = true)

    def * = (id, login, password, salt, roleId, connected, lastActivity).shaped <> (userTupled, userUnapply)
  }

  // User -> Option[Tuple]
  def userUnapply(u: User) =
    Some((u.id, u.login, u.password, u.salt, u.roleId, u.connected, u.lastActivity.map(instant2Timestamp)))

  // Tuple -> User
  def userTupled(row: (Long, String, String, Int, Int, Boolean, Option[Timestamp])): User = {
    val (id, login, pwd, salt, roleId, connected, oLastAct) = row
    User(id, login, pwd, salt, roleId, connected, oLastAct.map(timestamp2Instant))
  }

  // Conversions
  def instant2Timestamp(i: Instant): Timestamp = new Timestamp(i.getMillis())
  def timestamp2Instant(ts: Timestamp): Instant = new Instant(ts.getTime())


  lazy val users = TableQuery[Usuarios]
} 
开发者ID:kdoomsday,项目名称:doomcart,代码行数:56,代码来源:User.scala

示例15: ProductCategory

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

import slick.backend.DatabaseConfig
import slick.driver.JdbcProfile

case class ProductCategory(
  val productId : Long,
  val categoryId: Int
)

trait ProductCategoryTable extends ProductTable with CategoryTable {
  val dc: DatabaseConfig[JdbcProfile]

  import dc.driver.api._

  private[ProductCategoryTable] class ProductCats(tag: Tag)
      extends Table[ProductCategory](tag, "product_category")
  {
    def productId  = column[Long]("product_id")
    def categoryId = column[Int] ("category_id")

    def pk = primaryKey("pk_productCategory", (productId, categoryId))
    def product =
      foreignKey("fk_prodcat_product", productId, products)(
        _.id,
        onUpdate = ForeignKeyAction.Restrict,
        onDelete = ForeignKeyAction.Cascade
      )

    def * = (productId, categoryId) <> (ProductCategory.tupled, ProductCategory.unapply)

  }

  lazy val productCategories = TableQuery[ProductCats]
} 
开发者ID:kdoomsday,项目名称:doomcart,代码行数:36,代码来源:ProductCategory.scala


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