/
DBMigration.scala
71 lines (62 loc) · 2.28 KB
/
DBMigration.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package skinny.dbmigration
import org.flywaydb.core.Flyway
import skinny.util.TypesafeConfigReader
import skinny.{ SkinnyEnv, DBSettings }
import scalikejdbc.ConnectionPool
import com.typesafe.config.ConfigFactory
import scala.collection.JavaConverters._
import skinny.exception.DBSettingsException
object DBMigration extends DBMigration
/**
* DB migration tool.
*/
trait DBMigration {
def migrate(env: String = SkinnyEnv.Development, poolName: String = ConnectionPool.DEFAULT_NAME.name) = {
val skinnyEnv = SkinnyEnv.get()
try {
System.setProperty(SkinnyEnv.PropertyKey, env)
DBSettings.initialize()
try {
val pool = ConnectionPool.get(Symbol(poolName))
val flyway = new Flyway
flyway.setDataSource(pool.dataSource)
val migrationConfigPath = s"db.${poolName}.migration"
val rootConfig = TypesafeConfigReader.config(env)
if (rootConfig.hasPath(migrationConfigPath)) {
rootConfig.getConfig(migrationConfigPath).entrySet.asScala.foreach(println)
val locations = rootConfig.getConfig(migrationConfigPath)
.getStringList("locations").asScala.map(l => "db.migration." + l.replaceAll("/", "."))
if (!locations.isEmpty) {
flyway.setLocations(locations: _*)
}
}
flyway.migrate()
} catch {
case e: IllegalStateException =>
throw new DBSettingsException(s"ConnectionPool named $poolName is not found.")
}
} finally {
skinnyEnv.foreach { env => System.setProperty(SkinnyEnv.PropertyKey, env) }
DBSettings.initialize()
}
}
def repair(env: String = SkinnyEnv.Development, poolName: String = ConnectionPool.DEFAULT_NAME.name) = {
val skinnyEnv = SkinnyEnv.get()
try {
System.setProperty(SkinnyEnv.PropertyKey, env)
DBSettings.initialize()
try {
val pool = ConnectionPool.get(Symbol(poolName))
val flyway = new Flyway
flyway.setDataSource(pool.dataSource)
flyway.repair()
} catch {
case e: IllegalStateException =>
throw new DBSettingsException(s"ConnectionPool named $poolName is not found.")
}
} finally {
skinnyEnv.foreach { env => System.setProperty(SkinnyEnv.PropertyKey, env) }
DBSettings.initialize()
}
}
}