diff --git a/src/jvmMain/kotlin/ru/landgrafhomyak/db/jdbc_kotlin_extensions/extensions.kt b/src/jvmMain/kotlin/ru/landgrafhomyak/db/jdbc_kotlin_extensions/extensions.kt index ba9ef0b..adf9129 100644 --- a/src/jvmMain/kotlin/ru/landgrafhomyak/db/jdbc_kotlin_extensions/extensions.kt +++ b/src/jvmMain/kotlin/ru/landgrafhomyak/db/jdbc_kotlin_extensions/extensions.kt @@ -4,12 +4,15 @@ package ru.landgrafhomyak.db.jdbc_kotlin_extensions +import org.intellij.lang.annotations.Language import java.sql.Connection import java.sql.PreparedStatement +import java.sql.ResultSet import kotlin.contracts.ExperimentalContracts +import kotlin.contracts.InvocationKind import kotlin.contracts.contract -public fun Connection.mapQuery(sql: String, action: PreparedStatementPrepareAndFetch, to: MutableList) { +public fun > Connection.mapQuery(sql: String, action: PreparedStatementPrepareAndFetch, to: C): C { this.prepareStatement(sql).use { ps -> action.prepare(ps) ps.executeQuery().use { rs -> @@ -18,6 +21,7 @@ public fun Connection.mapQuery(sql: String, action: PreparedStatementPrepare } } } + return to } public fun Connection.mapQuery(sql: String, action: PreparedStatementPrepareAndFetch): List { @@ -28,7 +32,7 @@ public fun Connection.mapQuery(sql: String, action: PreparedStatementPrepare public inline fun Connection.transaction(t: (Connection) -> R): R { contract { - callsInPlace(t) + callsInPlace(t, InvocationKind.EXACTLY_ONCE) } this.prepareStatement("BEGIN TRANSACTION").use { ps -> ps.executeUpdate() } @@ -48,9 +52,32 @@ public inline fun Connection.transaction(t: (Connection) -> R): R { } -public inline fun Connection.prepareStatement(sql: String, action: (PreparedStatement) -> R): R { +public inline fun Connection.prepareStatement(@Language("SQL") sql: String, action: (PreparedStatement) -> R): R { contract { - callsInPlace(action) + callsInPlace(action, InvocationKind.EXACTLY_ONCE) } - this.prepareStatement(sql).use { ps -> return action(ps) } + this.prepareStatement(sql/*.trim(' ', '\n', '\t')*/).use { ps -> return action(ps) } +} + +public inline fun > ResultSet.mapTo(to: C, transform: (rs: ResultSet) -> R): C { + while (this.next()) { + to.add(transform(this)) + } + return to +} + +public inline fun ResultSet.map(transform: (rs: ResultSet) -> R): List = + this.mapTo(ArrayList(), transform) + +public inline fun > ResultSet.mapToThenClose(to: C, transform: (rs: ResultSet) -> R): C = + this.use { rs -> rs.mapTo(to, transform) } + +public inline fun ResultSet.mapThenClose(transform: (rs: ResultSet) -> R): List = + this.use { rs -> rs.map(transform) } + +public inline fun PreparedStatement.executeQuery(action: (ResultSet) -> R): R { + contract { + callsInPlace(action, InvocationKind.EXACTLY_ONCE) + } + return this.executeQuery().use(action) } \ No newline at end of file