|
1 |
| -import org.jooq.DSLContext |
2 |
| -import org.jooq.impl.DSL |
| 1 | +import java.sql.Connection |
| 2 | +import java.sql.DriverManager |
3 | 3 |
|
4 | 4 | class DatabaseCopier(
|
5 | 5 | private val host: String,
|
6 | 6 | private val port: Int,
|
7 | 7 | private val user: String,
|
8 | 8 | private val password: String
|
9 | 9 | ) {
|
| 10 | + private fun <R> withConnection(url: String, user: String, password: String, block: (Connection) -> R) { |
| 11 | + DriverManager.getConnection(url, user, password).use { |
| 12 | + block(it) |
| 13 | + } |
| 14 | + } |
| 15 | + |
| 16 | + private fun Connection.execute(query: String) { |
| 17 | + this.createStatement().use { |
| 18 | + it.execute(query) |
| 19 | + } |
| 20 | + } |
10 | 21 |
|
11 | 22 | fun copy(from: String, to: String) {
|
12 | 23 |
|
13 | 24 | synchronized(this) {
|
14 | 25 |
|
15 | 26 | val url = jdbcUrl(host, port, from)
|
16 | 27 |
|
17 |
| - DSL.using(url, user, password).use({ db: DSLContext -> |
18 |
| - |
| 28 | + withConnection(url, user, password) { db -> |
19 | 29 | withExclusiveConnectionTo(db, to, from) {
|
20 | 30 | db.execute("drop database if exists $to;")
|
21 | 31 | db.execute("create database $to template $from;")
|
22 | 32 | }
|
23 |
| - |
24 |
| - }) |
| 33 | + } |
25 | 34 | }
|
26 | 35 | }
|
27 | 36 |
|
| 37 | + |
28 | 38 | private fun jdbcUrl(host: String, port: Int, database: String) =
|
29 | 39 | "jdbc:postgresql://$host:$port/$database?ApplicationName=database-copier"
|
30 | 40 |
|
31 |
| - private fun withExclusiveConnectionTo(db: DSLContext, vararg databaseNames: String, fn: () -> Unit) { |
| 41 | + private fun withExclusiveConnectionTo(db: Connection, vararg databaseNames: String, fn: () -> Unit) { |
32 | 42 |
|
33 | 43 | val whereDatNames = databaseNames.asSequence().map({ "datname = '$it'" }).joinToString(" or ")
|
34 | 44 |
|
|
0 commit comments