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

Scala Flyway类代码示例

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

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



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

示例1: ApiSpec

//设置package包名称以及导入依赖的类
package au.csiro.data61.magda.registry

import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.testkit.ScalatestRouteTest
import akka.testkit.TestProbe
import ch.qos.logback.classic.{Level, Logger}
import org.flywaydb.core.Flyway
import org.scalatest.Matchers
import org.scalatest.fixture.FunSpec
import org.slf4j.LoggerFactory

import scala.concurrent.duration._
import scalikejdbc._

abstract class ApiSpec extends FunSpec with ScalatestRouteTest with Matchers with Protocols with SprayJsonSupport {
  case class FixtureParam(api: Api, webHookActorProbe: TestProbe)

  val databaseUrl = Option(System.getenv("npm_package_config_databaseUrl")).getOrElse("jdbc:postgresql://localhost:5432/postgres")

  // Stop Flyway from producing so much spam that Travis terminates the process.
  LoggerFactory.getLogger("org.flywaydb").asInstanceOf[Logger].setLevel(Level.WARN)

  val flyway = new Flyway()
  flyway.setDataSource(databaseUrl, "postgres", "")
  flyway.setSchemas("test")
  flyway.setLocations("classpath:/sql")

  override def testConfigSource =
    s"""
      |db.default.url = "${databaseUrl}?currentSchema=test"
      |authorization.skip = true
      |akka.loglevel = INFO
    """.stripMargin

  override def withFixture(test: OneArgTest) = {
    val webHookActorProbe = TestProbe()
    val api = new Api(webHookActorProbe.ref, testConfig, system, executor, materializer)

    webHookActorProbe.expectMsg(1 millis, WebHookActor.Process)

    DB localTx { implicit session =>
      sql"DROP SCHEMA IF EXISTS test CASCADE".update.apply()
      sql"CREATE SCHEMA test".update.apply()
    }

    flyway.migrate()

    super.withFixture(test.toNoArgTest(FixtureParam(api, webHookActorProbe)))
  }
} 
开发者ID:TerriaJS,项目名称:magda,代码行数:51,代码来源:ApiSpec.scala


示例2: dbHandle

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

import org.flywaydb.core.Flyway
import slick.jdbc.H2Profile.api._

trait DbInstance {
  val db: Database
}

trait MemDb extends DbInstance {
  lazy val db = Database.forConfig("memoryDb")
}

trait ServerDb extends DbInstance {
  lazy val db = dbHandle

  private def dbHandle = {
    val config = TestEnv.config.getConfig("fileDb")

    val flyway = new Flyway
    flyway.setDataSource(config.getString("url"), config.getString("user"), config.getString("password"))
    flyway.migrate()

    Database.forConfig("fileDb")
  }
} 
开发者ID:nexelem,项目名称:slick-101,代码行数:27,代码来源:DbInstances.scala


示例3: SchemaMigration

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

import org.flywaydb.core.Flyway
import slick.jdbc.DataSourceJdbcDataSource
import slick.jdbc.PostgresProfile.api._
import slick.jdbc.hikaricp.HikariCPJdbcDataSource

import scala.util.control.NonFatal

class SchemaMigration(val db: Database) {
  def withMigration(dir: Seq[String], schema: String = "public", baseline: Boolean = false, shutdown: => Unit = {}): Database = {
    val flyway = new Flyway()
    val ds = db.source match {
      case d: DataSourceJdbcDataSource =>
        d.ds
      case d: HikariCPJdbcDataSource =>
        d.ds
      case other =>
        throw new IllegalStateException("Unknown DataSource type: " + other)
    }

    flyway.setDataSource(ds)
    flyway.setLocations(dir: _*)
    flyway.setBaselineOnMigrate(baseline)
    flyway.setSchemas(schema)

    try {
      flyway.migrate()
    } catch {
      case NonFatal(ex) =>
        ex.printStackTrace()
        shutdown
    }

    db
  }
} 
开发者ID:snap-swap,项目名称:flyway-helper,代码行数:38,代码来源:SchemaMigration.scala


示例4: DatabaseHelpers

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

import org.flywaydb.core.Flyway
import scalikejdbc.ConnectionPool


object DatabaseHelpers {
  def connect(db: Databases.Value, dbConfig: DatabaseConfiguration): Unit = {
    ConnectionPool.add(db, dbConfig.connection, dbConfig.username, dbConfig.password)
  }

  def migrate(migrationName: String, dbConfig: DatabaseConfiguration): Unit = {
    val migration = new Flyway()

    migration.setDataSource(dbConfig.connection, dbConfig.username, dbConfig.password)
    migration.setLocations(s"classpath:db/$migrationName")
    migration.baseline()
    migration.migrate()
    migration.validate()
  }
} 
开发者ID:SKNZ,项目名称:SpinaciCore,代码行数:22,代码来源:DatabaseHelpers.scala


示例5: initFlyway

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

import java.sql.Connection
import javax.sql.DataSource

import org.flywaydb.core.Flyway
import org.flywaydb.core.api.MigrationInfo
import org.flywaydb.core.api.callback.FlywayCallback

trait FlywayInit {
  def initFlyway(ds: DataSource) = {
    val flyway = new Flyway()
    flyway.setDataSource(ds)
    flyway.setLocations("sql.migration")
    flyway.setCallbacks(new BeforeCleanCallback())
    flyway.setBaselineOnMigrate(true)
    //??????.sql?????????????.sql???
    //by Lining 2016/7/27
    flyway.setValidateOnMigrate(false)
    flyway
  }
}

class BeforeCleanCallback extends FlywayCallback {
  def afterBaseline(connection: Connection): Unit = {}
  def afterClean(connection: Connection): Unit = {}
  def afterEachMigrate(connection: Connection): Unit = {}
  def afterInfo(connection: Connection): Unit = {}
  def afterEachMigrate(connection: Connection, migrationInfo: MigrationInfo): Unit = {}
  def afterMigrate(connection: Connection): Unit = {}
  def afterRepair(connection: Connection): Unit = {}
  def afterValidate(connection: Connection): Unit = {}
  def beforeBaseline(connection: Connection): Unit = {}
  def beforeClean(connection: Connection): Unit = executeStmt(connection, """DROP EXTENSION IF EXISTS "ltree" CASCADE;""")
  def beforeEachMigrate(connection: Connection, migrationInfo: MigrationInfo): Unit = {}
  def beforeInfo(connection: Connection): Unit = {}
  def beforeInit(connection: Connection): Unit = {}
  def beforeMigrate(connection: Connection): Unit = {}
  def beforeRepair(connection: Connection): Unit = {}
  def beforeValidate(connection: Connection): Unit = {}
  def afterInit(connection: Connection): Unit = executeStmt(connection, """DROP EXTENSION IF EXISTS "ltree" CASCADE;""")

  def executeStmt(connection: Connection, statement: String): Unit = {
    if (connection.getMetaData().getDriverName().startsWith("PostgreSQL")) {
      val stmt = connection.prepareStatement(statement)
      try {
        stmt.execute()
      } finally {
        stmt.close()
      }
    }
  }

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


示例6: fakeApplication

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

import com.google.inject.Inject
import org.flywaydb.core.Flyway
import org.flywaydb.core.internal.util.jdbc.DriverDataSource
import org.scalatestplus.play.FakeApplicationFactory
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.inject.{Binding, Module}
import play.api.{Application, Configuration, Environment}


trait MyApplicationFactory extends FakeApplicationFactory {
  def fakeApplication(): Application = {
    new GuiceApplicationBuilder()
      .configure(Map("myapp.database.url" -> "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1"))
      .bindings(new FlywayModule)
      .build()
  }
}

class FlywayModule extends Module {
  override def bindings(environment: Environment, configuration: Configuration): Seq[Binding[_]] = {
    Seq(bind[FlywayMigrator].toSelf.eagerly() )
  }
}

class FlywayMigrator @Inject()(env: Environment, configuration: Configuration) {
  def onStart(): Unit = {
    val driver = configuration.underlying.getString("myapp.database.driver")
    val url = configuration.underlying.getString("myapp.database.url")
    val user = configuration.underlying.getString("myapp.database.user")
    val password = configuration.underlying.getString("myapp.database.password")
    val flyway = new Flyway
    flyway.setDataSource(new DriverDataSource(env.classLoader, driver, url, user, password))
    flyway.setLocations("filesystem:modules/flyway/src/main/resources/db/migration")
    flyway.migrate()
  }

  onStart()
} 
开发者ID:wouzar,项目名称:tracker,代码行数:41,代码来源:MyApplicationFactory.scala


示例7: beforeAll

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

import org.flywaydb.core.Flyway
import org.scalatest.{BeforeAndAfterAll, fixture}
import scalikejdbc.config.DBsWithEnv
import scalikejdbc.scalatest.AutoRollback
import scalikejdbc.{ConnectionPool, GlobalSettings}
import tests.support.MockitoSupport

trait FixtureTestSuite extends fixture.FunSuiteLike with AutoRollback with MockitoSupport with BeforeAndAfterAll {

  override def beforeAll(): Unit = {
    super.beforeAll()
    GlobalSettings.jtaDataSourceCompatible = true
    DBsWithEnv("test").setupAll()

    val flyway = new Flyway()
    flyway.setDataSource(ConnectionPool().dataSource)
    flyway.clean()
    flyway.migrate()
  }

  override def afterAll(): Unit = {
    super.afterAll()
    DBsWithEnv("test").closeAll()
  }
} 
开发者ID:lymr,项目名称:fun-chat,代码行数:28,代码来源:FixtureTestSuite.scala


示例8: Migration

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

import com.typesafe.config.ConfigFactory
import org.flywaydb.core.Flyway

object Migration {
  def apply() = {
    new Migration()
  }
}
class Migration {
  private val configuration = ConfigFactory.load()

  private val flyWay = new Flyway()
  flyWay.setDataSource(configuration.getString("storageDatabase.url"), "", "", "select 1")
  flyWay.setLocations(s"filesystem:${configuration.getString("storageDatabase.migrationFolder")}")
  flyWay.setSqlMigrationPrefix("")

  def migrate() = {
    flyWay.migrate()
  }
} 
开发者ID:waltsu,项目名称:wdht,代码行数:23,代码来源:Migration.scala


示例9: FlywayService

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

import org.flywaydb.core.Flyway

class FlywayService(jdbcUrl: String, dbUser: String, dbPassword: String) {

  private val flyway = new Flyway()
  flyway.setDataSource(jdbcUrl, dbUser, dbPassword)

  def migrateDatabase = {
    flyway.migrate()
    this
  }

  def dropDatabase = {
    flyway.clean()
    this
  }
} 
开发者ID:greven77,项目名称:AkkaHTTPBookstore,代码行数:20,代码来源:FlywayService.scala


示例10: VerifiableFileSpec

//设置package包名称以及导入依赖的类
package org.plunderknowledge.sumcrawler.model.test

import org.specs2.mutable.Specification
import org.plunderknowledge.sumcrawler.model.VerifiableFile

import scala.reflect.io.File
import scala.util.Random
import com.roundeights.hasher.Implicits._
import org.specs2.specification.BeforeAll
import scalikejdbc._
import scalikejdbc.config._
import scalikejdbc.specs2.mutable.AutoRollback

import org.flywaydb.core.Flyway



class VerifiableFileSpec extends Specification with BeforeAll {

  override def beforeAll(): Unit = {
    DBsWithEnv("test").setupAll()
    val flyway = new Flyway()
    flyway.setDataSource(ConnectionPool.dataSource('default))
    flyway.migrate()
  }

  sequential

  "Verifiable file should correctly identify correct sums" in new AutoRollback {
    val verifiable = VerifiableFile(VerifiableFileSpec.correctFileUrl, VerifiableFileSpec.correctFileSum, "md5", None)
    verifiable.verify() must beTrue
    sql"""select count(*) as success_count from signature
          where success = true""".map(rs => rs.int("success_count")).single.apply() must beEqualTo(Some(1))
  }
}

object VerifiableFileSpec {

  def kestrel[A](x: A)(f: A => Unit): A = { f(x); x }

  def writeFile(bytes: Array[Byte]): String = {
    val f = File.makeTemp()
    f.outputStream().write(bytes)
    f.toAbsolute.path
  }

  val correctFileBytes = kestrel(Array.fill[Byte](200)(0))(Random.nextBytes)
  val tempFileName = writeFile(correctFileBytes)
  val correctFileSum = correctFileBytes.md5.hex
  val correctFileUrl = s"file://${tempFileName}"

} 
开发者ID:PlunderKnowledge,项目名称:SumCrawler,代码行数:53,代码来源:VerifiableFileSpec.scala


示例11: DatabaseInitializer

//设置package包名称以及导入依赖的类
package pl.touk.nussknacker.ui.db

import java.io.PrintWriter
import java.sql.Connection
import java.util.logging.Logger
import javax.sql.DataSource

import org.flywaydb.core.Flyway
import slick.jdbc.JdbcBackend

class DatabaseInitializer(db: JdbcBackend.Database) {
  def initDatabase(): JdbcBackend.Database = {
    migrateIfNeeded(db)
    db
  }

  private def migrateIfNeeded(db: JdbcBackend.Database) = {
    val flyway = new Flyway()
    flyway.setDataSource(new DatabaseDataSource(db))
    flyway.setBaselineOnMigrate(true)
    flyway.migrate()
  }
}

class DatabaseDataSource(db: JdbcBackend.Database) extends DataSource {
  private val conn = db.createSession().conn

  override def getConnection: Connection = conn
  override def getConnection(username: String, password: String): Connection = conn
  override def unwrap[T](iface: Class[T]): T = conn.unwrap(iface)
  override def isWrapperFor(iface: Class[_]): Boolean = conn.isWrapperFor(iface)

  override def setLogWriter(out: PrintWriter): Unit = ???
  override def getLoginTimeout: Int = ???
  override def setLoginTimeout(seconds: Int): Unit = ???
  override def getParentLogger: Logger = ???
  override def getLogWriter: PrintWriter = ???
} 
开发者ID:TouK,项目名称:nussknacker,代码行数:39,代码来源:DatabaseInitializer.scala


示例12: FlywayPreparerLocation

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

import javax.sql.DataSource

import com.opentable.db.postgres.embedded.DatabasePreparer
import org.flywaydb.core.Flyway

case class FlywayPreparerLocation(location: String, schema: Option[String] = None)

class FlywayPreparer(locations: Seq[FlywayPreparerLocation]) extends DatabasePreparer {
  private val flyways: Seq[(Flyway, Option[String])] =
    locations.groupBy(_.schema).map { case (schema, groupedLocations) =>
      val flyway = new Flyway
      flyway.setLocations(groupedLocations.map(_.location): _*)

      (flyway, schema)
    }.toSeq

  override def prepare(ds: DataSource): Unit = {
    flyways.foreach { case (flyway, schema) =>
      flyway.setDataSource(ds)
      schema.foreach(s => flyway.setSchemas(s))
      flyway.migrate
    }
  }
}

object FlywayPreparer {
  def apply(locations: (String, Option[String])*): FlywayPreparer = {
    val flywayLocation = locations.map { case (location, schema) =>
      FlywayPreparerLocation(location, schema)
    }

    new FlywayPreparer(flywayLocation)
  }
} 
开发者ID:snap-swap,项目名称:slick-postgres-testkit,代码行数:37,代码来源:FlywayPreparer.scala


示例13: runCommand

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

import javax.sql.DataSource
import doobie.hikari.hikaritransactor.HikariTransactor
import doobie.imports._
import fs2.Task
import org.flywaydb.core.Flyway
import org.postgresql.ds.PGSimpleDataSource


trait Db {
  def runCommand[A](command: ConnectionIO[A]): Task[A]
}

class DbImpl(transactor: Transactor[IOLite]) extends Db {
  def runCommand[A](command: ConnectionIO[A]): Task[A] = Task.delay(command.transact(transactor).unsafePerformIO)
}

object Db {

  def unsafeCreate(config: DbConfig): Db = unsafeCreate(
    s"jdbc:postgresql://${config.hostname}:${config.port}/${config.databaseName}", config.username, config.password)

  def unsafeCreate(jdbcUrl: String, username: String, password: String): Db = {
    val transactor = HikariTransactor[IOLite]("org.postgresql.Driver", jdbcUrl, username, password).unsafePerformIO
    new DbImpl(transactor)
  }

  def createDataSource(config: DbConfig): DataSource =
    new PGSimpleDataSource {
      setServerName(config.hostname)
      setPortNumber(config.port)
      setDatabaseName(config.databaseName)
      setUser(config.username)
      setPassword(config.password)
      setApplicationName("PSA")
    }


  def migrateSchema(dataSource: DataSource): Unit =
    new Flyway() {
      setDataSource(dataSource)
    }.migrate()
}

case class DbConfig(
  hostname: String,
  port: Int,
  databaseName: String,
  username: String,
  password: String
) 
开发者ID:ahamdy88,项目名称:JobForce,代码行数:53,代码来源:Db.scala


示例14: AuthServerMain

//设置package包名称以及导入依赖的类
package xyz.lascuolaopensource.coo2xyz.auth

import com.twitter.finagle.http.{Request, Response}
import com.twitter.finatra.http.HttpServer
import com.twitter.finatra.http.filters.{CommonFilters, LoggingMDCFilter, TraceIdMDCFilter}
import com.twitter.finatra.http.routing.HttpRouter
import com.typesafe.config.ConfigFactory
import org.flywaydb.core.Flyway
import slick.jdbc.DatabaseUrlDataSource
import xyz.lascuolaopensource.coo2xyz.auth.controllers.{AssetsController, AuthController}
import xyz.lascuolaopensource.coo2xyz.auth.filters.SessionFilter


object AuthServerMain extends AuthServer {

	private[auth] val config = ConfigFactory.load()

	override protected def start() = {
		val flyway = new Flyway
		val dbSource = new DatabaseUrlDataSource
		dbSource.setUrl(config.getString("pgdb.properties.url"))
		flyway.setDataSource(dbSource)
		flyway.baseline()
		flyway.migrate

		super.start
	}

}

class AuthServer extends HttpServer {

	override protected def defaultFinatraHttpPort = AuthServerMain.config.getString("http.port")

	override def defaultHttpPort = AuthServerMain.config.getString("http.port").tail.toInt

	override protected def disableAdminHttpServer = true

	override protected def configureHttp(router: HttpRouter) = {
		router
			.filter[LoggingMDCFilter[Request, Response]]
			.filter[TraceIdMDCFilter[Request, Response]]
			.filter[CommonFilters]
			.add[SessionFilter, AuthController]
			.add[AssetsController]
	}

} 
开发者ID:coompany,项目名称:coo2xyz-auth,代码行数:49,代码来源:AuthServer.scala


示例15: TableProvisioner

//设置package包名称以及导入依赖的类
package uk.ac.wellcome.platform.idminter.database

import com.google.inject.Inject
import com.twitter.inject.annotations.Flag
import org.flywaydb.core.Flyway

import scala.collection.JavaConversions._

class TableProvisioner @Inject()(@Flag("aws.rds.host") host: String,
                                 @Flag("aws.rds.port") port: String,
                                 @Flag("aws.rds.userName") userName: String,
                                 @Flag("aws.rds.password") password: String) {

  def provision(database: String, tableName: String): Unit = {
    val flyway = new Flyway()
    flyway.setDataSource(s"jdbc:mysql://$host:$port/$database",
                         userName,
                         password)
    flyway.setPlaceholders(
      Map("database" -> database, "tableName" -> tableName))
    flyway.migrate()
  }

} 
开发者ID:wellcometrust,项目名称:platform-api,代码行数:25,代码来源:TableProvisioner.scala


示例16: Migrate

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


import org.flywaydb.core.Flyway
import journal.Logger
import scalaz.concurrent.Task


object Migrate {

  val log = Logger[Migrate.type]

  def migrate(cfg: DatabaseConfig): Task[Unit] =
    Task.delay {
      val flyway = new Flyway
      flyway.setDataSource(
        cfg.connection,
        cfg.username.getOrElse(""),
        cfg.password.getOrElse(""))

      try {
        log.info("Conducting database schema migrations if needed.")
        val completed = flyway.migrate()
        log.info(s"Completed $completed succsessful migrations.")
      } catch {
        case e: Throwable => {
          // attempt a repair (useful for local debugging)
          log.error(s"Failed to migrate database. ${e.getMessage}")
          log.info("Repairing database before retrying migration")
          flyway.repair()
          val completed = flyway.migrate()
          log.info(s"After repair, completed $completed succsessful migrations.")
        }
      }
    }
} 
开发者ID:Verizon,项目名称:nelson,代码行数:38,代码来源:Migrate.scala


示例17: Migrator

//设置package包名称以及导入依赖的类
package io.github.morgaroth.eventsmanger

import com.typesafe.config.Config
import org.flywaydb.core.Flyway

import scala.util.Try


case class Migrator(fw: Flyway, enabled: Boolean) {
  def migrate() = if (enabled) fw.migrate() else -1
}

trait FlyWayEvolutions {
  def initMigrator(cfg: Config) = {
    val flyway = new Flyway()
    val user = cfg.getString("properties.user")
    val password = cfg.getString("properties.password")
    val dbName = cfg.getString("properties.databaseName")
    val server = cfg.getString("properties.serverName")
    val port = cfg.getInt("properties.portNumber")
    val url = s"jdbc:postgresql://$server:$port/$dbName"
    val enabled = Try(cfg.getBoolean("evolutions")).getOrElse(true)
    flyway.setDataSource(url, user, password)
    flyway.setBaselineOnMigrate(true)
    Migrator(flyway, enabled)
  }

  def migrate(cfg: Config) = {
    initMigrator(cfg).migrate()
  }
}

object FlyWayEvolutions extends FlyWayEvolutions 
开发者ID:Morgaroth,项目名称:events_manager,代码行数:34,代码来源:FlyWayEvolutions.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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