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

Scala MTable类代码示例

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

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



在下文中一共展示了MTable类的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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")
  }
} 
开发者ID:littlenag,项目名称:scala-essentials-petstore,代码行数:39,代码来源:DatabaseInitializer.scala


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


示例3: HanaConnectExample

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

import slick.jdbc.HanaProfile.api._
import slick.jdbc.meta.MTable
import slick.relational.HanaTable

import scala.concurrent.duration.Duration
import scala.concurrent.{Await, Future}
import scala.concurrent.ExecutionContext.Implicits.global

object HanaConnectExample extends App {
  val db = Database.forConfig("hana")

  try {
    class Students(tag: Tag) extends HanaTable[(Int, String)](tag, Some("TEST_CASE"), "STUDENTS") {
      def id = column[Int]("ID", O.PrimaryKey)
      def fullname = column[String]("NAME")

      def * = (id, fullname)
    }

    val students = TableQuery[Students]

    println(students.schema.createStatements.toList.head)

    val tableChecker: Future[Vector[MTable]] = db.run(MTable.getTables(Some(""), Some("TEST_CASE"), Some("STUDENTS"), None))
    val setupAction = DBIO.seq(
      students.schema.create,

      students ++= Seq(
        (1, "Ram"),
        (2, "Shyam")
      )
    )

    val setupFuture = tableChecker.flatMap(result =>
      if (result.isEmpty) {
        db.run(setupAction)
      } else {
        Future.successful()
      }
    )

    val update = students.filter(_.id === 1).map(record => (record.id, record.fullname)).update(1, "Jadu")
    println(update.statements.toList.head)
    val updateFuture = setupFuture.flatMap(_ =>
      db.run(update)
    )

    println(students.result.statements.head)
    val f = updateFuture.flatMap(_ =>
      db.run(students.result).map(println)
    )

    Await.result(f, Duration.Inf)
  } finally {
    db.close()
  }
} 
开发者ID:sbcd90,项目名称:slick-hana,代码行数:60,代码来源:HanaConnectExample.scala


示例4: 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)
  }
} 
开发者ID:ScoreUnder,项目名称:canti-bot,代码行数:26,代码来源:DBUtils.scala


示例5: 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)

} 
开发者ID:adolbin,项目名称:lw-test-kit,代码行数:44,代码来源:TableSchemaPreparation.scala


示例6: Main

//设置package包名称以及导入依赖的类
package ua.kyiv.a3

import slick.jdbc.H2Profile.api._
import slick.jdbc.meta.MTable
import ua.kyiv.a3.db.{ChecklistDao, DatabaseSchema, InitialData}

import scala.util.Failure

//TODO: replace execution context?
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration.Duration
import scala.concurrent.{Await, Future}
import scala.util.Success

object Main extends App with DatabaseSchema with InitialData {

//  val db = Database.forConfig("h2")
  val db = Database.forConfig("postgresDB")

  //TODO: remove before testing in UAT
  val dropCmd = DBIO.seq(allSchemas.drop)

  private val future = createSchemaIfNotExists().flatMap(_ => insertInitialData())
  Await.ready(future, Duration.Inf)

  val dao = new ChecklistDao(db)



  val selectedChoices = dao.getChoicesBundle
  print("selectedChoices: ")
  printResults(selectedChoices)

  val allQuestions = dao.getQuestions
  print("all questions: ")
  printResults(allQuestions)

  def createSchemaIfNotExists(): Future[Unit] = {
    db.run(MTable.getTables).flatMap {
      case tables if tables.isEmpty =>
        db.run(allSchemas.create).andThen {
          case Success(_) => println("Schema created")
          case Failure(e) => println(s"Schema creation failed ${e.getMessage}")
        }
      case tables if tables.nonEmpty =>
        println("Schema already exists")
        println(s"${tables}")
        Future.successful()
    }
  }

  def printResults[T](f: Future[Iterable[T]]): Unit = {
    Await.result(f, Duration.Inf).foreach(println)
    println()
  }
} 
开发者ID:nikitajz,项目名称:ks-checklist-slick,代码行数:57,代码来源:Main.scala


示例7: FeedH2Dao

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

import javax.inject.Inject
import scala.concurrent.ExecutionContext.Implicits.global

import com.newsreader.feeds.domain.Feed
import slick.driver.H2Driver
import slick.driver.H2Driver.api._
import slick.jdbc.meta.MTable

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

class FeedH2Dao @Inject() (db: Database) extends FeedDbDao(H2Driver) {
    Await.result(
      db.run(MTable.getTables).flatMap(
        v => {
          val names = v.map(m => m.name.name)
          val create = Seq(table).filter(
            t => !names.contains(t.baseTableRow.tableName)
          ).map(_.schema.create)
          db.run(DBIO.sequence(create))
        }
      ), Duration.Inf)

  def store(feed: Feed) : Long = {
    Await.result(
      db.run(storeDBIO(feed)),
      Duration.Inf
    )
  }

  def load: Seq[Feed] = {
    Await.result(
      db.run(loadDBIO),
      Duration.Inf
    )
  }

} 
开发者ID:mprzybylak,项目名称:news-radar,代码行数:41,代码来源:FeedH2Dao.scala


示例8: MailTokenUser

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

import java.sql.Timestamp
import java.time.LocalDateTime
import java.util.UUID
import javax.inject.Inject

import models.db.generic.{GenericCrud, HasId}
import play.api.db.slick.DatabaseConfigProvider
import slick.driver.JdbcProfile

import scala.concurrent.Future
import slick.jdbc.meta.MTable
import slick.jdbc.meta.MTable.getTables
import com.github.t3hnar.bcrypt._
import models.Common
import org.joda.time.DateTime
import services.MailToken

case class MailTokenUser( id: UUID,
                          email: String,
                          expirationTime: DateTime,
                          isSignUp: Boolean
               ) extends MailToken with HasId {

}

class MailTokenUsers @Inject()(protected val dbConfigProvider: DatabaseConfigProvider) extends GenericCrud[MailTokenUser] {

  import driver.api._

  override type SpecificTable = MailTokenUsersTable
  override protected val query = TableQuery[SpecificTable]

  override protected val TableName = "MAIL_TOKEN_USER"
  // db.run(query.schema.create)

  def findById(id: UUID): Future[Option[MailTokenUser]] =
    db.run(query.filter(_.id === id).result.headOption)

  def findByEmail(email: String): Future[Option[MailTokenUser]] =
    db.run(query.filter(_.email === email).result.headOption)

  def all: Future[List[MailTokenUser]] =
    db.run(query.to[List].result)

  

  }

  override protected val testData = {
    List(
    )
  }
} 
开发者ID:ygpark2,项目名称:play-ain-board,代码行数:56,代码来源:MailTokenUser.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Scala Callback类代码示例发布时间:2022-05-23
下一篇:
Scala ImageView类代码示例发布时间: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