Fix migration if executed two or more times

This commit is contained in:
2019-08-04 22:23:57 +02:00
parent 01a0000b15
commit 13f0f12c1b

View File

@@ -1,7 +1,6 @@
package fr.postgresjson.migration
import com.fasterxml.jackson.core.type.TypeReference
import com.github.jasync.sql.db.util.size
import fr.postgresjson.connexion.Connection
import fr.postgresjson.definition.Function.FunctionNotFound
import fr.postgresjson.entity.Entity
@@ -39,13 +38,23 @@ data class Migrations private constructor(
private val queries: MutableMap<String, Query> = mutableMapOf(),
private val functions: MutableMap<String, Function> = mutableMapOf()
) {
private var directories: List<File> = emptyList()
private val logger: Logger? by LoggerDelegate()
constructor(directory: File, connection: Connection): this(listOf(directory), connection)
constructor(directories: List<File>, connection: Connection): this(connection) {
initDB()
this.directories = directories
reset()
}
fun reset() {
queries.clear()
functions.clear()
getMigrationFromDB()
getMigrationFromDirectory(directories)
queries.forEach { (_, query) ->
if (query.doExecute === null) {
query.doExecute = Action.DOWN
@@ -97,11 +106,11 @@ data class Migrations private constructor(
it.isFile
}.forEach { file ->
if (file.name.endsWith(".up.sql")) {
file.path.substring(0, file.path.size - 7).let {
file.path.substring(0, file.path.length - 7).let {
try {
val down = File("$it.down.sql").readText()
val up = file.readText()
val name = file.name.substring(0, file.name.size - 7)
val name = file.name.substring(0, file.name.length - 7)
addQuery(name, up, down)
} catch (e: FileNotFoundException) {
throw DownMigrationNotDefined("$it.down.sql", e)
@@ -244,6 +253,7 @@ data class Migrations private constructor(
sendQuery("COMMIT")
}
logger?.info("Migration done")
reset()
return list.toMap()
}
@@ -264,6 +274,7 @@ data class Migrations private constructor(
sendQuery("COMMIT")
}
logger?.info("Migration DOWN done")
reset()
return list.toMap()
}