[Editor] Add support inserting data from Query Result view

This commit is contained in:
2021-03-26 13:33:05 +01:00
parent c7e5c3d8ce
commit 3b0e117541
3 changed files with 38 additions and 14 deletions

View File

@@ -1,5 +1,6 @@
package com.bartlomiejpluta.base.editor.database.controller
import com.bartlomiejpluta.base.editor.database.model.data.DataRecord
import com.bartlomiejpluta.base.editor.database.model.data.Query
import com.bartlomiejpluta.base.editor.database.service.DatabaseService
import org.springframework.stereotype.Component
@@ -19,14 +20,27 @@ class DatabaseController : Controller() {
null
}
fun execute(op: Connection.() -> Unit) {
databaseService.run<Unit> {
try {
op(this)
} catch (e: SQLException) {
sqlErrorAlert(e)
fun execute(op: Connection.() -> Unit): Boolean = databaseService.run {
try {
op(this)
true
} catch (e: SQLException) {
sqlErrorAlert(e)
false
}
} ?: false
fun submitBatch(table: String, records: List<DataRecord>) = execute {
autoCommit = false
records.forEach {
it.prepareStatement(table)?.let { sql ->
val statement = prepareStatement(sql)
it.fields.values.forEachIndexed { index, field -> statement.setObject(index + 1, field.value) }
statement.execute()
}
}
commit()
}
private fun sqlErrorAlert(e: SQLException) =

View File

@@ -3,10 +3,8 @@ package com.bartlomiejpluta.base.editor.database.model.data
import tornadofx.getValue
import tornadofx.setValue
import tornadofx.toProperty
import kotlin.collections.Map
import kotlin.collections.component1
import kotlin.collections.component2
import kotlin.collections.forEach
class DataRecord(val fields: Map<String, DataField>, operation: Operation = Operation.DO_NOTHING) {
val operationProperty = operation.toProperty()
@@ -15,4 +13,11 @@ class DataRecord(val fields: Map<String, DataField>, operation: Operation = Oper
init {
fields.forEach { (_, field) -> field.record = this }
}
fun prepareStatement(table: String) = when (operation) {
Operation.INSERT -> "INSERT INTO `$table` SET $parameters;"
else -> null
}
private val parameters = fields.map { (column, _) -> "`$column` = ?" }.joinToString(", ")
}

View File

@@ -51,11 +51,7 @@ class QueryResultView : View() {
override val root = borderpane {
top = toolbar {
button(graphic = FontIcon("fa-refresh")) {
action {
databaseController.execute(queryVM.query, queryVM.name, queryVM.table)?.let {
queryVM.item = it
}
}
action { refresh() }
}
button(graphic = FontIcon("fa-plus")) {
@@ -82,11 +78,20 @@ class QueryResultView : View() {
enableWhen(queryVM.tableProperty.isNotNull)
action {
println(queryVM.data.size)
val success = databaseController.submitBatch(queryVM.name, queryVM.data)
if (success) {
refresh()
}
}
}
}
center = table
}
private fun refresh() {
databaseController.execute(queryVM.query, queryVM.name, queryVM.table)?.let {
queryVM.item = it
}
}
}