forked from SteamWar/SteamWar
@@ -83,6 +83,113 @@ fun <T> JdbcTransaction.executeSingle(sql: String, transform: (ResultSet) -> T):
|
||||
}.single()
|
||||
}
|
||||
|
||||
fun JdbcTransaction.executeScript(sql: String) {
|
||||
for (statement in splitSqlScript(sql)) {
|
||||
exec(statement) { }
|
||||
}
|
||||
}
|
||||
|
||||
private fun splitSqlScript(sql: String): List<String> {
|
||||
val statements = mutableListOf<String>()
|
||||
val current = StringBuilder()
|
||||
var quote: Char? = null
|
||||
var inLineComment = false
|
||||
var inBlockComment = false
|
||||
var index = 0
|
||||
|
||||
fun addStatement() {
|
||||
val statement = current.toString().trim()
|
||||
if (statement.isNotEmpty()) {
|
||||
statements += statement
|
||||
}
|
||||
current.clear()
|
||||
}
|
||||
|
||||
while (index < sql.length) {
|
||||
val char = sql[index]
|
||||
val next = sql.getOrNull(index + 1)
|
||||
|
||||
if (inLineComment) {
|
||||
current.append(char)
|
||||
if (char == '\n') {
|
||||
inLineComment = false
|
||||
}
|
||||
index++
|
||||
continue
|
||||
}
|
||||
|
||||
if (inBlockComment) {
|
||||
current.append(char)
|
||||
if (char == '*' && next == '/') {
|
||||
current.append(next)
|
||||
inBlockComment = false
|
||||
index += 2
|
||||
} else {
|
||||
index++
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
if (quote != null) {
|
||||
current.append(char)
|
||||
if (char == '\\' && quote != '`' && next != null) {
|
||||
current.append(next)
|
||||
index += 2
|
||||
continue
|
||||
}
|
||||
if (char == quote) {
|
||||
if (next == quote) {
|
||||
current.append(next)
|
||||
index += 2
|
||||
continue
|
||||
}
|
||||
quote = null
|
||||
}
|
||||
index++
|
||||
continue
|
||||
}
|
||||
|
||||
when {
|
||||
char == '-' && next == '-' -> {
|
||||
current.append(char).append(next)
|
||||
inLineComment = true
|
||||
index += 2
|
||||
}
|
||||
|
||||
char == '#' -> {
|
||||
current.append(char)
|
||||
inLineComment = true
|
||||
index++
|
||||
}
|
||||
|
||||
char == '/' && next == '*' -> {
|
||||
current.append(char).append(next)
|
||||
inBlockComment = true
|
||||
index += 2
|
||||
}
|
||||
|
||||
char == '\'' || char == '"' || char == '`' -> {
|
||||
current.append(char)
|
||||
quote = char
|
||||
index++
|
||||
}
|
||||
|
||||
char == ';' -> {
|
||||
addStatement()
|
||||
index++
|
||||
}
|
||||
|
||||
else -> {
|
||||
current.append(char)
|
||||
index++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
addStatement()
|
||||
return statements
|
||||
}
|
||||
|
||||
fun useDb(statement: JdbcTransaction.() -> Unit) {
|
||||
de.steamwar.db.Database.ensureConnected()
|
||||
transaction(de.steamwar.db.Database.db, statement = statement)
|
||||
|
||||
Reference in New Issue
Block a user