Skip to content

Commit

Permalink
6.0.12 fix database (transaction update)
Browse files Browse the repository at this point in the history
  • Loading branch information
Bkm016 committed Sep 24, 2023
1 parent 47e31ab commit 045e9f4
Show file tree
Hide file tree
Showing 8 changed files with 143 additions and 78 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ class ActionSelect(val table: String) : ActionFilterable() {
private var distincts = arrayListOf<String>()

/** 查询行 */
private var rows = arrayListOf<String>()
private var rows = arrayListOf("*")

/** 连接 */
private val join = arrayListOf<Join>()
Expand Down Expand Up @@ -61,6 +61,7 @@ class ActionSelect(val table: String) : ActionFilterable() {
* 选择并返回表中关于 [row] 的所有数据,与 [distincts] 互斥
*/
fun rows(vararg row: String) {
rows.clear()
rows += row
distincts.clear()
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,15 +68,15 @@ open class ExecutableSource(val table: Table<*, *>, var dataSource: DataSource,
return ResultProcessor(query, object : Executable<ResultSet> {

override fun <C> invoke(func: ResultSet.() -> C): C {
return connection.prepareStatement(query, autoGeneratedKeys).use { statement ->
try {
return try {
connection.prepareStatement(query, autoGeneratedKeys).use { statement ->
action?.elements?.forEachIndexed { index, any -> statement.setObject(index + 1, any) }
statement.executeQuery().use { func(it) }.also { action?.callFinally(statement, connection) }
} catch (ex: SQLException) {
warning(query)
warning("Statement parameter (${action?.elements?.size ?: 0}): ${action?.elements}")
throw ex
}
} catch (ex: SQLException) {
warning("Query: $query")
warning("Parameters (${action?.elements?.size ?: 0}): ${action?.elements}")
throw ex
}
}
}).also { processors += it }
Expand All @@ -85,15 +85,15 @@ open class ExecutableSource(val table: Table<*, *>, var dataSource: DataSource,
/** 执行更新语句 */
open fun executeUpdate(query: String, action: Action? = null): ResultProcessor {
return ResultProcessor.Update(query) {
connection.prepareStatement(query, autoGeneratedKeys).use { statement ->
try {
try {
connection.prepareStatement(query, autoGeneratedKeys).use { statement ->
action?.elements?.forEachIndexed { index, any -> statement.setObject(index + 1, any) }
statement.executeUpdate().also { action?.callFinally(statement, connection) }
} catch (ex: SQLException) {
warning(query)
warning("Statement parameter (${action?.elements?.size ?: 0}): ${action?.elements}")
throw ex
}
} catch (ex: SQLException) {
warning("Query: $query")
warning("Parameters (${action?.elements?.size ?: 0}): ${action?.elements}")
throw ex
}
}.also { processors += it }
}
Expand Down Expand Up @@ -127,6 +127,13 @@ open class ExecutableSource(val table: Table<*, *>, var dataSource: DataSource,
}
}

/**
* 关闭链接
*/
open fun close() {
connection.close()
}

/**
* 生成数据表创建语句
*/
Expand All @@ -143,38 +150,41 @@ open class ExecutableSource(val table: Table<*, *>, var dataSource: DataSource,
// 列表
stat.addSegment(columns.joinToString { it.query })
// 主键
stat.addSegmentIfTrue(primaryKeyForLegacy.isNotEmpty()) {
addSegment("PRIMARY KEY")
addKeys(primaryKeyForLegacy.toTypedArray())
stat.addSegmentSequence(prefix = ", ") {
// 主键
addSegmentIfTrue(primaryKeyForLegacy.isNotEmpty()) {
addSegment("PRIMARY KEY")
addKeys(primaryKeyForLegacy.toTypedArray())
}
// 索引
addSegment(columns.asSequence()
.filterIsInstance<ColumnSQL>()
.filter { it.options.contains(ColumnOptionSQL.KEY) }
.groupBy { it.indexType }
.map { (key, value) ->
Statement()
.addSegment("KEY `idx_${value.joinToString("_") { it.name }}`")
.addSegment("(${value.joinToString { "${it.name.asFormattedColumnName()} ${if (it.desc) "desc" else ""}".trim() }})")
.addSegmentIfTrue(key != IndexType.DEFAULT) {
addSegment("USING $key")
}.build()
}.joinToString()
)
// 唯一索引
addSegment(columns.asSequence()
.filterIsInstance<ColumnSQL>()
.filter { it.options.contains(ColumnOptionSQL.UNIQUE_KEY) }
.groupBy { it.indexType }
.map { (key, value) ->
Statement()
.addSegment("UNIQUE `uk_${value.joinToString("_") { it.name }}`")
.addSegment("(${value.joinToString { "${it.name.asFormattedColumnName()} ${if (it.desc) "desc" else ""}".trim() }})")
.addSegmentIfTrue(key != IndexType.DEFAULT) {
addSegment("USING $key")
}.build()
}.joinToString()
)
}
// 索引
stat.addSegment(columns.asSequence()
.filterIsInstance<ColumnSQL>()
.filter { it.options.contains(ColumnOptionSQL.KEY) }
.groupBy { it.indexType }
.map { (key, value) ->
Statement()
.addSegment("KEY `idx_${value.joinToString("_") { it.name }}`")
.addSegment("(${value.joinToString { "${it.name.asFormattedColumnName()} ${if (it.desc) "desc" else ""}".trim() }})")
.addSegmentIfTrue(key != IndexType.DEFAULT) {
addSegment("USING $key")
}.build()
}.joinToString()
)
// 唯一索引
stat.addSegment(columns.asSequence()
.filterIsInstance<ColumnSQL>()
.filter { it.options.contains(ColumnOptionSQL.UNIQUE_KEY) }
.groupBy { it.indexType }
.map { (key, value) ->
Statement()
.addSegment("UNIQUE `uk_${value.joinToString("_") { it.name }}`")
.addSegment("(${value.joinToString { "${it.name.asFormattedColumnName()} ${if (it.desc) "desc" else ""}".trim() }})")
.addSegmentIfTrue(key != IndexType.DEFAULT) {
addSegment("USING $key")
}.build()
}.joinToString()
)
stat.addSegment(")")
return stat.build()
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ abstract class Filterable {
infix fun String.inside(value: Array<Any>): Criteria {
if (value.isEmpty()) error("empty value")
val el = arrayListOf<Any>()
return Criteria("${asFormattedColumnName()} IN (${unwrapArray(value, el)}})", el).apply(this@Filterable)
return Criteria("${asFormattedColumnName()} IN (${unwrapArray(value, el)})", el).apply(this@Filterable)
}

/** 在某范围之内 */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,20 @@ open class ResultProcessor(val query: String, val executor: Executable<ResultSet
}
}
}

/** 运行并遍历所有结果 */
open fun forEachIndexed(call: ResultSet.(index: Int) -> Unit) {
if (isExecuted) {
error("processor is already executed: $query")
}
isExecuted = true
executor.invoke {
var i = 0
while (next()) {
call(this, i++)
}
}
}
}

/** 向下兼容 */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import java.sql.ResultSet
* @author sky
* @since 2021/6/23 2:11 下午
*/
open class ResultProcessorList(processors: List<ResultProcessor>, val transaction: Boolean = false) {
open class ResultProcessorList(processors: List<ResultProcessor>, val source: ExecutableSource? = null) {

val processors = processors.toMutableList()

Expand All @@ -28,8 +28,12 @@ open class ResultProcessorList(processors: List<ResultProcessor>, val transactio
}
isExecuted = true
val last = processors.removeLast()
processors.forEach { it.executor.invoke { fetchSize } }
return last.executor.invoke { fetchSize }
return try {
processors.forEach { it.run() }
last.run()
} finally {
source?.close()
}
}

open fun find(): Boolean {
Expand All @@ -38,8 +42,12 @@ open class ResultProcessorList(processors: List<ResultProcessor>, val transactio
}
isExecuted = true
val last = processors.removeLast()
processors.forEach { it.executor.invoke { fetchSize } }
return last.executor.invoke { next() }
return try {
processors.forEach { it.run() }
last.executor.invoke { next() }
} finally {
source?.close()
}
}

open fun <T> first(resultSet: ResultSet.() -> T): T {
Expand All @@ -48,10 +56,14 @@ open class ResultProcessorList(processors: List<ResultProcessor>, val transactio
}
isExecuted = true
val last = processors.removeLast()
processors.forEach { it.executor.invoke { fetchSize } }
return last.executor.invoke {
next()
resultSet(this)
return try {
processors.forEach { it.run() }
last.executor.invoke {
next()
resultSet(this)
}
} finally {
source?.close()
}
}

Expand All @@ -61,13 +73,17 @@ open class ResultProcessorList(processors: List<ResultProcessor>, val transactio
}
isExecuted = true
val last = processors.removeLast()
processors.forEach { it.executor.invoke { fetchSize } }
return last.executor.invoke {
if (next()) {
resultSet(this)
} else {
null
return try {
processors.forEach { it.run() }
last.executor.invoke {
if (next()) {
resultSet(this)
} else {
null
}
}
} finally {
source?.close()
}
}

Expand All @@ -77,13 +93,17 @@ open class ResultProcessorList(processors: List<ResultProcessor>, val transactio
}
isExecuted = true
val last = processors.removeLast()
processors.forEach { it.executor.invoke { fetchSize } }
return last.executor.invoke {
ArrayList<T>().also {
return try {
processors.forEach { it.run() }
last.executor.invoke {
val arr = ArrayList<T>()
while (next()) {
it += resultSet(this)
arr += resultSet(this)
}
arr
}
} finally {
source?.close()
}
}

Expand All @@ -93,11 +113,15 @@ open class ResultProcessorList(processors: List<ResultProcessor>, val transactio
}
isExecuted = true
val last = processors.removeLast()
processors.forEach { it.executor.invoke { fetchSize } }
last.executor.invoke {
while (next()) {
resultSet(this)
try {
processors.forEach { it.run() }
last.executor.invoke {
while (next()) {
resultSet(this)
}
}
} finally {
source?.close()
}
}

Expand All @@ -107,12 +131,16 @@ open class ResultProcessorList(processors: List<ResultProcessor>, val transactio
}
isExecuted = true
val last = processors.removeLast()
processors.forEach { it.executor.invoke { fetchSize } }
last.executor.invoke {
var i = 0
while (next()) {
resultSet(this, i++)
try {
processors.forEach { it.run() }
last.executor.invoke {
var i = 0
while (next()) {
resultSet(this, i++)
}
}
} finally {
source?.close()
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@ class Statement {

/** 追加语句 */
fun addSegment(literal: String): Statement {
query += literal
if (literal.isNotEmpty()) {
query += literal
}
return this
}

Expand All @@ -32,7 +34,16 @@ class Statement {
/** 追加语句 */
fun addSegmentIfTrue(predicate: Boolean, builder: Statement.() -> Unit): Statement {
if (predicate) {
query += Statement().also(builder).query
query += Statement().also(builder).query.joinToString(" ")
}
return this
}

/** 追加语句 */
fun addSegmentSequence(prefix: String = "", suffix: String = "", builder: Statement.() -> Unit): Statement {
val children = Statement().also(builder).query
if (children.isNotEmpty()) {
query += "$prefix${children.joinToString()}$suffix"
}
return this
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,8 @@ open class Table<T : Host<E>, E : ColumnBuilder>(val name: String, val host: Hos
* 需要注意的是,上面工作空间中的 `select` 操作只会执行一次,且在 `run()` 之前。
*/
open fun workspace(dataSource: DataSource, func: ExecutableSource.() -> Unit): ResultProcessorList {
return ResultProcessorList(ExecutableSource(this, dataSource, false).also(func).processors, false)
val source = ExecutableSource(this, dataSource, false).also(func)
return ResultProcessorList(source.processors, source)
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,8 @@ fun <T> PreparedStatement.use(func: (statement: PreparedStatement) -> T): T {
*/
internal fun Any.asFormattedColumnName(): String {
val str = this.toString()
// 如果字符串是 "null" || 如果字符串是一个函数或表达式 || 如果字符串已经被格式化
if (str == "null" || str.contains(Regex("\\(.+\\)")) || (str.startsWith("`") && str.endsWith("`"))) {
// 如果字符串是 "*" 或 "null" || 如果字符串是一个函数或表达式 || 如果字符串已经被格式化
if (str == "*" || str == "null" || str.contains(Regex("\\(.+\\)")) || (str.startsWith("`") && str.endsWith("`"))) {
return str
}
// 通过 "." 分割字符串并分别格式化每个部分
Expand Down

0 comments on commit 045e9f4

Please sign in to comment.