├── .editorconfig ├── .github └── workflows │ └── ci.yaml ├── .gitignore ├── LICENSE ├── README.md ├── build.gradle.kts ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src ├── main └── kotlin │ └── com │ └── github │ └── michaelbull │ └── jdbc │ ├── Connection.kt │ ├── Transaction.kt │ └── context │ ├── CoroutineConnection.kt │ ├── CoroutineDataSource.kt │ └── CoroutineTransaction.kt └── test └── kotlin └── com └── github └── michaelbull └── jdbc ├── ConnectionTest.kt ├── TransactionTest.kt └── context ├── CoroutineConnectionTest.kt ├── CoroutineDataSourceTest.kt └── CoroutineTransactionTest.kt /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | charset = utf-8 5 | end_of_line = lf 6 | insert_final_newline = true 7 | trim_trailing_whitespace = true 8 | 9 | [*.{kt, kts, gradle}] 10 | indent_style = space 11 | indent_size = 4 12 | continuation_indent_size = 4 13 | -------------------------------------------------------------------------------- /.github/workflows/ci.yaml: -------------------------------------------------------------------------------- 1 | name: ci 2 | 3 | on: [ push, pull_request ] 4 | 5 | jobs: 6 | check: 7 | runs-on: ubuntu-latest 8 | 9 | steps: 10 | - uses: actions/checkout@v2 11 | 12 | - uses: actions/cache@v1 13 | with: 14 | path: ~/.gradle/wrapper 15 | key: ${{ runner.os }}-gradle-wrapper-${{ hashFiles('gradle/wrapper/gradle-wrapper.*') }} 16 | restore-keys: | 17 | ${{ runner.os }}-gradle-wrapper- 18 | 19 | - uses: actions/cache@v1 20 | with: 21 | path: ~/.gradle/caches 22 | key: ${{ runner.os }}-gradle-caches-${{ hashFiles('**/*.gradle.kts') }} }} 23 | restore-keys: | 24 | ${{ runner.os }}-gradle-caches- 25 | 26 | - uses: actions/setup-java@v1 27 | with: 28 | java-version: 1.8 29 | 30 | - run: ./gradlew check 31 | 32 | publish: 33 | needs: check 34 | if: github.ref == 'refs/heads/master' && github.event_name == 'push' && needs.check.result == 'success' 35 | runs-on: ubuntu-latest 36 | 37 | steps: 38 | - uses: actions/checkout@v2 39 | 40 | - uses: actions/cache@v1 41 | with: 42 | path: ~/.gradle/wrapper 43 | key: ${{ runner.os }}-gradle-wrapper-${{ hashFiles('gradle/wrapper/gradle-wrapper.*') }} 44 | restore-keys: | 45 | ${{ runner.os }}-gradle-wrapper- 46 | 47 | - uses: actions/cache@v1 48 | with: 49 | path: ~/.gradle/caches 50 | key: ${{ runner.os }}-gradle-caches-${{ hashFiles('**/*.gradle.kts') }} }} 51 | restore-keys: | 52 | ${{ runner.os }}-gradle-caches- 53 | 54 | - uses: actions/setup-java@v1 55 | with: 56 | java-version: 1.8 57 | 58 | - run: ./gradlew publish 59 | env: 60 | ORG_GRADLE_PROJECT_ossrhUsername: ${{ secrets.OSSRH_USERNAME }} 61 | ORG_GRADLE_PROJECT_ossrhPassword: ${{ secrets.OSSRH_PASSWORD }} 62 | ORG_GRADLE_PROJECT_signingKeyId: ${{ secrets.SIGNING_KEY_ID }} 63 | ORG_GRADLE_PROJECT_signingKey: ${{ secrets.SIGNING_KEY }} 64 | ORG_GRADLE_PROJECT_signingPassword: ${{ secrets.SIGNING_PASSWORD }} 65 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Hidden files 2 | .* 3 | 4 | # Temporary files 5 | *~ 6 | 7 | # Git 8 | !.git* 9 | 10 | # GitHub 11 | !/.github 12 | 13 | # EditorConfig 14 | !.editorconfig 15 | 16 | # IntelliJ Idea 17 | out/ 18 | *.iml 19 | *.ipr 20 | *.iws 21 | 22 | # Gradle 23 | build/ 24 | 25 | # JVM error logs 26 | hs_err_pid*.log 27 | replay_pid*.log 28 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2019-2021 Michael Bull (https://www.michael-bull.com) 2 | 3 | Permission to use, copy, modify, and/or distribute this software for any 4 | purpose with or without fee is hereby granted, provided that the above 5 | copyright notice and this permission notice appear in all copies. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 8 | WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 9 | MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 10 | ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 11 | WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 12 | ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 13 | OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 14 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # kotlin-coroutines-jdbc 2 | 3 | [![Maven Central](https://img.shields.io/maven-central/v/com.michael-bull.kotlin-coroutines-jdbc/kotlin-coroutines-jdbc.svg)](https://search.maven.org/search?q=g:com.michael-bull.kotlin-coroutines-jdbc) [![CI Status](https://github.com/michaelbull/kotlin-coroutines-jdbc/workflows/ci/badge.svg)](https://github.com/michaelbull/kotlin-coroutines-jdbc/actions?query=workflow%3Aci) [![License](https://img.shields.io/github/license/michaelbull/kotlin-coroutines-jdbc.svg)](https://github.com/michaelbull/kotlin-coroutines-jdbc/blob/master/LICENSE) 4 | 5 | A library for interacting with blocking JDBC drivers using [Kotlin Coroutines][coroutines]. 6 | 7 | Use of this library allows you to offload blocking JDBC calls to a dedicated 8 | [`CoroutineDispatcher`][CoroutineDispatcher] (e.g. 9 | [`Dispatchers.IO`][Dispatchers.IO]), thus suspending your coroutine and freeing 10 | your thread for other work while waiting. 11 | 12 | ## Installation 13 | 14 | ```groovy 15 | repositories { 16 | mavenCentral() 17 | } 18 | 19 | dependencies { 20 | implementation("com.michael-bull.kotlin-coroutines-jdbc:kotlin-coroutines-jdbc:1.0.2") 21 | } 22 | ``` 23 | 24 | ## Introduction 25 | 26 | The primary higher-order function exposed by the library is the 27 | [`transaction`][transaction] function. 28 | 29 | ```kotlin 30 | suspend inline fun transaction(crossinline block: suspend CoroutineScope.() -> T): T 31 | ``` 32 | 33 | Calling this function with a specific suspending block will run the block in 34 | the context of a [`CoroutineTransaction`][CoroutineTransaction]. 35 | 36 | Calls to `transaction` can be nested inside another, with each child re-using 37 | the first `CoroutineTransaction`. Only the outermost call will either 38 | [`commit`][Connection.commit] or [`rollback`][Connection.rollback] the 39 | transaction. 40 | 41 | Starting a fresh transaction will add a 42 | [`CoroutineTransaction`][CoroutineTransaction] to the current 43 | [`CoroutineContext`][CoroutineContext]. Transactions cannot be re-used after 44 | completion and attempting to do so will result in a runtime failure. 45 | 46 | A transaction will establish a new [`Connection`][Connection] if an open one 47 | does not already exist in the active [`CoroutineContext`][CoroutineContext]. 48 | If the transaction does establish a new [`Connection`][Connection], it will 49 | attempt to [`close`][Connection.close] it upon completion. 50 | 51 | An active [`CoroutineConnection`][CoroutineConnection] is accessible from the 52 | current [`CoroutineContext`][CoroutineContext]. The connection from the context 53 | can be used to [prepare statements][Connection.prepareStatement]. 54 | 55 | ## Example 56 | 57 | ```kotlin 58 | import com.github.michaelbull.jdbc.context.CoroutineDataSource 59 | import com.github.michaelbull.jdbc.context.connection 60 | import com.github.michaelbull.jdbc.transaction 61 | import kotlinx.coroutines.CoroutineScope 62 | import kotlinx.coroutines.Dispatchers 63 | import kotlinx.coroutines.launch 64 | import javax.sql.DataSource 65 | import kotlin.coroutines.coroutineContext 66 | 67 | class Example(dataSource: DataSource) { 68 | 69 | private val scope = CoroutineScope(Dispatchers.IO + CoroutineDataSource(dataSource)) 70 | private val customers = CustomerRepository() 71 | 72 | fun query() { 73 | scope.launchTransaction() 74 | } 75 | 76 | private fun CoroutineScope.launchTransaction() = launch { 77 | val customers = addThenFindAllCustomers() 78 | customers.forEach(::println) 79 | } 80 | 81 | private suspend fun addThenFindAllCustomers(): List { 82 | return transaction { 83 | customers.add("John Doe") 84 | customers.findAll() 85 | } 86 | } 87 | } 88 | 89 | class CustomerRepository { 90 | 91 | suspend fun add(name: String) { 92 | coroutineContext.connection.prepareStatement("INSERT INTO customers VALUES (?)").use { stmt -> 93 | stmt.setString(1, name) 94 | stmt.executeUpdate() 95 | } 96 | } 97 | 98 | suspend fun findAll(): List { 99 | val customers = mutableListOf() 100 | 101 | coroutineContext.connection.prepareStatement("SELECT name FROM customers").use { stmt -> 102 | stmt.executeQuery().use { rs -> 103 | while (rs.next()) { 104 | customers += rs.getString("name") 105 | } 106 | } 107 | } 108 | 109 | return customers 110 | } 111 | } 112 | ``` 113 | 114 | ## Further Reading 115 | 116 | - [andrewoma/coroutine-jdbc](https://github.com/andrewoma/coroutine-jdbc) 117 | - [Coroutine Context and Scope - Roman Elizarov](https://medium.com/@elizarov/coroutine-context-and-scope-c8b255d59055) 118 | - [Blocking threads, suspending coroutines - Roman Elizarov](https://medium.com/@elizarov/blocking-threads-suspending-coroutines-d33e11bf4761) 119 | 120 | ## Contributing 121 | 122 | Bug reports and pull requests are welcome on [GitHub][github]. 123 | 124 | ## License 125 | 126 | This project is available under the terms of the ISC license. See the 127 | [`LICENSE`](LICENSE) file for the copyright information and licensing terms. 128 | 129 | [github]: https://github.com/michaelbull/kotlin-coroutines-jdbc 130 | [transaction]: https://github.com/michaelbull/kotlin-coroutines-jdbc/blob/master/src/main/kotlin/com/github/michaelbull/jdbc/Transaction.kt 131 | [CoroutineTransaction]: https://github.com/michaelbull/kotlin-coroutines-jdbc/blob/master/src/main/kotlin/com/github/michaelbull/jdbc/context/CoroutineTransaction.kt 132 | [CoroutineConnection]: https://github.com/michaelbull/kotlin-coroutines-jdbc/blob/master/src/main/kotlin/com/github/michaelbull/jdbc/context/CoroutineConnection.kt 133 | 134 | [coroutines]: https://kotlinlang.org/docs/reference/coroutines-overview.html 135 | [CoroutineContext]: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.coroutines/-coroutine-context/ 136 | [CoroutineDispatcher]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-dispatcher/index.html 137 | [Dispatchers.IO]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-dispatchers/-i-o.html 138 | 139 | [Connection]: https://docs.oracle.com/javase/8/docs/api/java/sql/Connection.html 140 | [Connection.close]: https://docs.oracle.com/javase/8/docs/api/java/sql/Connection.html#close-- 141 | [Connection.isClosed]: https://docs.oracle.com/javase/8/docs/api/java/sql/Connection.html#isClosed-- 142 | [Connection.commit]: https://docs.oracle.com/javase/8/docs/api/java/sql/Connection.html#commit-- 143 | [Connection.rollback]: https://docs.oracle.com/javase/8/docs/api/java/sql/Connection.html#rollback-- 144 | [Connection.prepareStatement]: https://docs.oracle.com/javase/8/docs/api/java/sql/Connection.html#prepareStatement-java.lang.String- 145 | -------------------------------------------------------------------------------- /build.gradle.kts: -------------------------------------------------------------------------------- 1 | import com.github.benmanes.gradle.versions.updates.DependencyUpdatesTask 2 | import org.jetbrains.dokka.gradle.DokkaTask 3 | import org.jetbrains.kotlin.gradle.tasks.KotlinCompile 4 | 5 | val ossrhUsername: String? by project 6 | val ossrhPassword: String? by project 7 | 8 | val signingKeyId: String? by project // must be the last 8 digits of the key 9 | val signingKey: String? by project 10 | val signingPassword: String? by project 11 | 12 | description = "A library for interacting with blocking JDBC drivers using Kotlin Coroutines." 13 | 14 | plugins { 15 | `maven-publish` 16 | signing 17 | kotlin("jvm") version "1.6.10" 18 | id("com.github.ben-manes.versions") version "0.39.0" 19 | id("org.jetbrains.dokka") version "1.6.0" 20 | } 21 | 22 | repositories { 23 | mavenCentral() 24 | jcenter() 25 | } 26 | 27 | dependencies { 28 | implementation(kotlin("stdlib")) 29 | implementation("com.michael-bull.kotlin-inline-logger:kotlin-inline-logger:1.0.4") 30 | implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.2") 31 | testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.5.2") 32 | testImplementation("org.junit.jupiter:junit-jupiter:5.8.2") 33 | testImplementation("io.mockk:mockk:1.12.1") 34 | } 35 | 36 | tasks.withType { 37 | rejectVersionIf { 38 | listOf("alpha", "beta", "rc", "cr", "m", "eap", "pr").any { 39 | candidate.version.contains(it, ignoreCase = true) 40 | } 41 | } 42 | } 43 | 44 | tasks.withType { 45 | kotlinOptions { 46 | jvmTarget = "1.8" 47 | freeCompilerArgs = listOf("-Xuse-experimental=kotlin.contracts.ExperimentalContracts") 48 | } 49 | } 50 | 51 | tasks.withType { 52 | useJUnitPlatform() 53 | } 54 | 55 | val dokkaJavadoc by tasks.existing(DokkaTask::class) 56 | 57 | val javadocJar by tasks.registering(Jar::class) { 58 | group = LifecycleBasePlugin.BUILD_GROUP 59 | description = "Assembles a jar archive containing the Javadoc API documentation." 60 | archiveClassifier.set("javadoc") 61 | from(dokkaJavadoc) 62 | } 63 | 64 | val sourcesJar by tasks.registering(Jar::class) { 65 | group = LifecycleBasePlugin.BUILD_GROUP 66 | description = "Assembles a jar archive containing the main classes with sources." 67 | archiveClassifier.set("sources") 68 | from(sourceSets["main"].allSource) 69 | } 70 | 71 | publishing { 72 | repositories { 73 | maven { 74 | if (project.version.toString().endsWith("SNAPSHOT")) { 75 | setUrl("https://oss.sonatype.org/content/repositories/snapshots") 76 | } else { 77 | setUrl("https://oss.sonatype.org/service/local/staging/deploy/maven2") 78 | } 79 | 80 | credentials { 81 | username = ossrhUsername 82 | password = ossrhPassword 83 | } 84 | } 85 | } 86 | 87 | publications { 88 | register("mavenJava", MavenPublication::class) { 89 | from(components["java"]) 90 | artifact(javadocJar.get()) 91 | artifact(sourcesJar.get()) 92 | 93 | pom { 94 | name.set(project.name) 95 | description.set(project.description) 96 | url.set("https://github.com/michaelbull/kotlin-coroutines-jdbc") 97 | inceptionYear.set("2019") 98 | 99 | licenses { 100 | license { 101 | name.set("ISC License") 102 | url.set("https://opensource.org/licenses/isc-license.txt") 103 | } 104 | } 105 | 106 | developers { 107 | developer { 108 | name.set("Michael Bull") 109 | url.set("https://www.michael-bull.com") 110 | } 111 | } 112 | 113 | contributors { 114 | contributor { 115 | name.set("huntj88") 116 | url.set("https://github.com/huntj88") 117 | } 118 | } 119 | 120 | scm { 121 | connection.set("scm:git:https://github.com/michaelbull/kotlin-coroutines-jdbc") 122 | developerConnection.set("scm:git:git@github.com:michaelbull/kotlin-coroutines-jdbc.git") 123 | url.set("https://github.com/michaelbull/kotlin-coroutines-jdbc") 124 | } 125 | 126 | issueManagement { 127 | system.set("GitHub") 128 | url.set("https://github.com/michaelbull/kotlin-coroutines-jdbc/issues") 129 | } 130 | 131 | ciManagement { 132 | system.set("GitHub") 133 | url.set("https://github.com/michaelbull/kotlin-coroutines-jdbc/actions?query=workflow%3Aci") 134 | } 135 | } 136 | } 137 | } 138 | } 139 | 140 | signing { 141 | useInMemoryPgpKeys(signingKeyId, signingKey, signingPassword) 142 | sign(publishing.publications) 143 | } 144 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | kotlin.code.style=official 2 | 3 | group=com.michael-bull.kotlin-coroutines-jdbc 4 | version=1.0.3-SNAPSHOT 5 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/michaelbull/kotlin-coroutines-jdbc/e0ab56ccced77cbca41c5ec54e61b7b088067fb3/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.8.1-all.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | 86 | # Determine the Java command to use to start the JVM. 87 | if [ -n "$JAVA_HOME" ] ; then 88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 89 | # IBM's JDK on AIX uses strange locations for the executables 90 | JAVACMD="$JAVA_HOME/jre/sh/java" 91 | else 92 | JAVACMD="$JAVA_HOME/bin/java" 93 | fi 94 | if [ ! -x "$JAVACMD" ] ; then 95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 96 | 97 | Please set the JAVA_HOME variable in your environment to match the 98 | location of your Java installation." 99 | fi 100 | else 101 | JAVACMD="java" 102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 103 | 104 | Please set the JAVA_HOME variable in your environment to match the 105 | location of your Java installation." 106 | fi 107 | 108 | # Increase the maximum file descriptors if we can. 109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 110 | MAX_FD_LIMIT=`ulimit -H -n` 111 | if [ $? -eq 0 ] ; then 112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 113 | MAX_FD="$MAX_FD_LIMIT" 114 | fi 115 | ulimit -n $MAX_FD 116 | if [ $? -ne 0 ] ; then 117 | warn "Could not set maximum file descriptor limit: $MAX_FD" 118 | fi 119 | else 120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 121 | fi 122 | fi 123 | 124 | # For Darwin, add options to specify how the application appears in the dock 125 | if $darwin; then 126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 127 | fi 128 | 129 | # For Cygwin or MSYS, switch paths to Windows format before running java 130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 133 | 134 | JAVACMD=`cygpath --unix "$JAVACMD"` 135 | 136 | # We build the pattern for arguments to be converted via cygpath 137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 138 | SEP="" 139 | for dir in $ROOTDIRSRAW ; do 140 | ROOTDIRS="$ROOTDIRS$SEP$dir" 141 | SEP="|" 142 | done 143 | OURCYGPATTERN="(^($ROOTDIRS))" 144 | # Add a user-defined pattern to the cygpath arguments 145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 147 | fi 148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 149 | i=0 150 | for arg in "$@" ; do 151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 153 | 154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 156 | else 157 | eval `echo args$i`="\"$arg\"" 158 | fi 159 | i=`expr $i + 1` 160 | done 161 | case $i in 162 | 0) set -- ;; 163 | 1) set -- "$args0" ;; 164 | 2) set -- "$args0" "$args1" ;; 165 | 3) set -- "$args0" "$args1" "$args2" ;; 166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 172 | esac 173 | fi 174 | 175 | # Escape application args 176 | save () { 177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 178 | echo " " 179 | } 180 | APP_ARGS=`save "$@"` 181 | 182 | # Collect all arguments for the java command, following the shell quoting and substitution rules 183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 184 | 185 | exec "$JAVACMD" "$@" 186 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'kotlin-coroutines-jdbc' 2 | -------------------------------------------------------------------------------- /src/main/kotlin/com/github/michaelbull/jdbc/Connection.kt: -------------------------------------------------------------------------------- 1 | package com.github.michaelbull.jdbc 2 | 3 | import com.github.michaelbull.jdbc.context.CoroutineConnection 4 | import com.github.michaelbull.jdbc.context.dataSource 5 | import com.github.michaelbull.logging.InlineLogger 6 | import kotlinx.coroutines.CoroutineScope 7 | import kotlinx.coroutines.withContext 8 | import java.sql.Connection 9 | import java.sql.SQLException 10 | import javax.sql.DataSource 11 | import kotlin.contracts.InvocationKind 12 | import kotlin.contracts.contract 13 | import kotlin.coroutines.CoroutineContext 14 | import kotlin.coroutines.coroutineContext 15 | 16 | @PublishedApi 17 | internal val logger = InlineLogger() 18 | 19 | /** 20 | * Calls the specified suspending [block] [with the context][withContext] of a [CoroutineConnection], suspends until it 21 | * completes, and returns the result. 22 | * 23 | * When the [coroutineContext] has an [open][hasOpenConnection] [Connection], the specified suspending [block] will be 24 | * called [with this context][withContext]. 25 | * 26 | * When the [coroutineContext] has no [Connection], or it [is closed][isClosedCatching], the specified suspending 27 | * [block] will be called [with the context][withContext] of a new [Connection]. This new [Connection] will be 28 | * established from the [DataSource] in the [coroutineContext], or throw an [IllegalStateException] if no such 29 | * [DataSource] exists, and will be [closed][closeCatching] after the specified suspending [block] completes. 30 | */ 31 | suspend inline fun withConnection(crossinline block: suspend CoroutineScope.() -> T): T { 32 | contract { 33 | callsInPlace(block, InvocationKind.EXACTLY_ONCE) 34 | } 35 | 36 | return if (coroutineContext.hasOpenConnection()) { 37 | withContext(coroutineContext) { 38 | block() 39 | } 40 | } else { 41 | val connection = coroutineContext.dataSource.connection 42 | 43 | try { 44 | withContext(CoroutineConnection(connection)) { 45 | block() 46 | } 47 | } finally { 48 | connection.closeCatching() 49 | } 50 | } 51 | } 52 | 53 | /** 54 | * Returns `true` if this [CoroutineContext] contains a [Connection] that is not [closed][isClosedCatching], 55 | * otherwise `false`. 56 | */ 57 | @PublishedApi 58 | internal fun CoroutineContext.hasOpenConnection(): Boolean { 59 | val connection = get(CoroutineConnection)?.connection 60 | return connection != null && !connection.isClosedCatching() 61 | } 62 | 63 | /** 64 | * Calls [close][Connection.close] on this [Connection], catching any [SQLException] that was thrown and logging it. 65 | */ 66 | @PublishedApi 67 | internal fun Connection.closeCatching() { 68 | try { 69 | close() 70 | } catch (ex: SQLException) { 71 | logger.warn(ex) { "Failed to close database connection cleanly:" } 72 | } 73 | } 74 | 75 | /** 76 | * Calls [isClosed][Connection.isClosed] on this [Connection] and returns its result, catching any [SQLException] that 77 | * was thrown then logging it and returning `true`. 78 | */ 79 | @PublishedApi 80 | internal fun Connection.isClosedCatching(): Boolean { 81 | return try { 82 | isClosed 83 | } catch (ex: SQLException) { 84 | logger.warn(ex) { "Connection isClosedCatching check failed, assuming closed:" } 85 | true 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/main/kotlin/com/github/michaelbull/jdbc/Transaction.kt: -------------------------------------------------------------------------------- 1 | package com.github.michaelbull.jdbc 2 | 3 | import com.github.michaelbull.jdbc.context.CoroutineTransaction 4 | import com.github.michaelbull.jdbc.context.connection 5 | import kotlinx.coroutines.CoroutineScope 6 | import kotlinx.coroutines.withContext 7 | import java.sql.Connection 8 | import kotlin.contracts.InvocationKind 9 | import kotlin.contracts.contract 10 | import kotlin.coroutines.coroutineContext 11 | 12 | /** 13 | * Calls the specified suspending [block] in the context of a [CoroutineTransaction], suspends until it completes, and 14 | * returns the result. 15 | * 16 | * When the [coroutineContext] has no [CoroutineTransaction], the specified suspending [block] will be 17 | * [ran transactionally][runTransactionally] [with the context of a Connection][withConnection]. 18 | * 19 | * When the [coroutineContext] has an [incomplete][CoroutineTransaction.incomplete] [CoroutineTransaction], the 20 | * specified suspending [block] will be called [with this context][withContext]. 21 | * 22 | * When the [coroutineContext] has a [completed][CoroutineTransaction.completed] [CoroutineTransaction], an 23 | * [IllegalStateException] will be thrown as the transaction cannot be re-used. 24 | */ 25 | suspend inline fun transaction(crossinline block: suspend CoroutineScope.() -> T): T { 26 | contract { 27 | callsInPlace(block, InvocationKind.AT_MOST_ONCE) 28 | } 29 | 30 | val existingTransaction = coroutineContext[CoroutineTransaction] 31 | 32 | return when { 33 | existingTransaction == null -> { 34 | withConnection { 35 | runTransactionally { 36 | block() 37 | } 38 | } 39 | } 40 | 41 | existingTransaction.incomplete -> { 42 | withContext(coroutineContext) { 43 | block() 44 | } 45 | } 46 | 47 | else -> error("Attempted to start new transaction within: $existingTransaction") 48 | } 49 | } 50 | 51 | /** 52 | * Calls the specified suspending [block] [with the context][withContext] of a [CoroutineTransaction] and returns its 53 | * result. 54 | * 55 | * If invocation of the suspending [block] was successful, [commit][Connection.commit] is then called on the 56 | * [Connection] in the [coroutineContext]. 57 | * 58 | * If invocation of the suspending [block] throws a [Throwable] exception, [rollback][Connection.rollback] is then 59 | * called on the [Connection] in the [coroutineContext] and the exception is thrown. 60 | */ 61 | @PublishedApi 62 | internal suspend inline fun runTransactionally(crossinline block: suspend CoroutineScope.() -> T): T { 63 | contract { 64 | callsInPlace(block, InvocationKind.EXACTLY_ONCE) 65 | } 66 | 67 | coroutineContext.connection.runWithManualCommit { 68 | val transaction = CoroutineTransaction() 69 | 70 | try { 71 | val result = withContext(transaction) { 72 | block() 73 | } 74 | 75 | commit() 76 | return result 77 | } catch (ex: Throwable) { 78 | rollback() 79 | throw ex 80 | } finally { 81 | transaction.complete() 82 | } 83 | } 84 | } 85 | 86 | /** 87 | * Disables [autoCommit][Connection.getAutoCommit] mode on `this` [Connection], then calls a specific function [block] 88 | * with `this` [Connection] as its receiver and returns its result, then sets the [autoCommit][Connection.getAutoCommit] 89 | * mode on `this` [Connection] back to its original value. 90 | */ 91 | @PublishedApi 92 | internal inline fun Connection.runWithManualCommit(block: Connection.() -> T): T { 93 | contract { 94 | callsInPlace(block, InvocationKind.EXACTLY_ONCE) 95 | } 96 | 97 | val before = autoCommit 98 | 99 | return try { 100 | autoCommit = false 101 | this.run(block) 102 | } finally { 103 | autoCommit = before 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /src/main/kotlin/com/github/michaelbull/jdbc/context/CoroutineConnection.kt: -------------------------------------------------------------------------------- 1 | package com.github.michaelbull.jdbc.context 2 | 3 | import java.sql.Connection 4 | import kotlin.coroutines.AbstractCoroutineContextElement 5 | import kotlin.coroutines.CoroutineContext 6 | 7 | val CoroutineContext.connection: Connection 8 | get() = get(CoroutineConnection)?.connection ?: error("No connection in context") 9 | 10 | class CoroutineConnection( 11 | val connection: Connection 12 | ) : AbstractCoroutineContextElement(CoroutineConnection) { 13 | 14 | companion object Key : CoroutineContext.Key 15 | 16 | override fun toString() = "CoroutineConnection($connection)" 17 | } 18 | -------------------------------------------------------------------------------- /src/main/kotlin/com/github/michaelbull/jdbc/context/CoroutineDataSource.kt: -------------------------------------------------------------------------------- 1 | package com.github.michaelbull.jdbc.context 2 | 3 | import javax.sql.DataSource 4 | import kotlin.coroutines.AbstractCoroutineContextElement 5 | import kotlin.coroutines.CoroutineContext 6 | 7 | val CoroutineContext.dataSource: DataSource 8 | get() = get(CoroutineDataSource)?.dataSource ?: error("No data source in context") 9 | 10 | class CoroutineDataSource( 11 | val dataSource: DataSource 12 | ) : AbstractCoroutineContextElement(CoroutineDataSource) { 13 | 14 | companion object Key : CoroutineContext.Key 15 | 16 | override fun toString() = "CoroutineDataSource($dataSource)" 17 | } 18 | -------------------------------------------------------------------------------- /src/main/kotlin/com/github/michaelbull/jdbc/context/CoroutineTransaction.kt: -------------------------------------------------------------------------------- 1 | package com.github.michaelbull.jdbc.context 2 | 3 | import kotlin.coroutines.AbstractCoroutineContextElement 4 | import kotlin.coroutines.CoroutineContext 5 | 6 | @PublishedApi 7 | internal class CoroutineTransaction( 8 | private var completed: Boolean = false 9 | ) : AbstractCoroutineContextElement(CoroutineTransaction) { 10 | 11 | companion object Key : CoroutineContext.Key 12 | 13 | val incomplete: Boolean 14 | get() = !completed 15 | 16 | fun complete() { 17 | completed = true 18 | } 19 | 20 | override fun toString(): String = "CoroutineTransaction(completed=$completed)" 21 | } 22 | -------------------------------------------------------------------------------- /src/test/kotlin/com/github/michaelbull/jdbc/ConnectionTest.kt: -------------------------------------------------------------------------------- 1 | package com.github.michaelbull.jdbc 2 | 3 | import com.github.michaelbull.jdbc.context.CoroutineConnection 4 | import com.github.michaelbull.jdbc.context.CoroutineDataSource 5 | import com.github.michaelbull.jdbc.context.connection 6 | import io.mockk.every 7 | import io.mockk.just 8 | import io.mockk.mockk 9 | import io.mockk.runs 10 | import io.mockk.verify 11 | import kotlinx.coroutines.ExperimentalCoroutinesApi 12 | import kotlinx.coroutines.test.runBlockingTest 13 | import org.junit.jupiter.api.Assertions.assertEquals 14 | import org.junit.jupiter.api.Test 15 | import org.junit.jupiter.api.assertThrows 16 | import java.sql.Connection 17 | import java.sql.SQLException 18 | import javax.sql.DataSource 19 | 20 | @ExperimentalCoroutinesApi 21 | class ConnectionTest { 22 | 23 | @Test 24 | fun `withConnection throws IllegalStateException if no connection & dataSource in context`() { 25 | assertThrows { 26 | runBlockingTest { 27 | withConnection { 28 | 29 | } 30 | } 31 | } 32 | } 33 | 34 | @Test 35 | fun `withConnection adds new connection to context if no connection in context`() { 36 | val newConnection = mockk { 37 | every { close() } just runs 38 | } 39 | 40 | val dataSource = mockk { 41 | every { connection } returns newConnection 42 | } 43 | 44 | val context = CoroutineDataSource(dataSource) 45 | 46 | runBlockingTest(context) { 47 | val actual = withConnection { 48 | coroutineContext.connection 49 | } 50 | 51 | assertEquals(newConnection, actual) 52 | } 53 | } 54 | 55 | @Test 56 | fun `withConnection adds new connection to context if existing connection isClosed returns true`() { 57 | val existingConnection = mockk { 58 | every { isClosed } returns true 59 | } 60 | 61 | val newConnection = mockk { 62 | every { close() } just runs 63 | } 64 | 65 | val dataSource = mockk { 66 | every { connection } returns newConnection 67 | } 68 | 69 | val context = CoroutineDataSource(dataSource) + CoroutineConnection(existingConnection) 70 | 71 | runBlockingTest(context) { 72 | val actual = withConnection { 73 | coroutineContext.connection 74 | } 75 | 76 | assertEquals(newConnection, actual) 77 | } 78 | } 79 | 80 | @Test 81 | fun `withConnection adds new connection to context if existing connection isClosed throws exception`() { 82 | val existingConnection = mockk { 83 | every { isClosed } throws SQLException() 84 | } 85 | 86 | val newConnection = mockk { 87 | every { close() } just runs 88 | } 89 | 90 | val dataSource = mockk { 91 | every { connection } returns newConnection 92 | } 93 | 94 | val context = CoroutineDataSource(dataSource) + CoroutineConnection(existingConnection) 95 | 96 | runBlockingTest(context) { 97 | val actual = withConnection { 98 | coroutineContext.connection 99 | } 100 | 101 | assertEquals(newConnection, actual) 102 | } 103 | } 104 | 105 | @Test 106 | fun `withConnection reuses existing connection in context if not closed`() { 107 | val existing = mockk { 108 | every { isClosed } returns false 109 | } 110 | 111 | val dataSource = mockk() 112 | val context = CoroutineDataSource(dataSource) + CoroutineConnection(existing) 113 | 114 | runBlockingTest(context) { 115 | val actual = withConnection { 116 | coroutineContext.connection 117 | } 118 | 119 | assertEquals(existing, actual) 120 | } 121 | } 122 | 123 | @Test 124 | fun `withConnection closes connection if added to context`() { 125 | val newConnection = mockk { 126 | every { close() } just runs 127 | } 128 | 129 | val dataSource = mockk { 130 | every { connection } returns newConnection 131 | } 132 | 133 | val context = CoroutineDataSource(dataSource) 134 | 135 | runBlockingTest(context) { 136 | withConnection { } 137 | } 138 | 139 | verify(exactly = 1) { newConnection.close() } 140 | } 141 | 142 | @Test 143 | fun `withConnection ignores SQLExceptions when closing connection added to context`() { 144 | val newConnection = mockk { 145 | every { close() } throws SQLException() 146 | } 147 | 148 | val dataSource = mockk { 149 | every { connection } returns newConnection 150 | } 151 | 152 | val context = CoroutineDataSource(dataSource) 153 | 154 | runBlockingTest(context) { 155 | withConnection { } 156 | } 157 | 158 | verify(exactly = 1) { newConnection.close() } 159 | } 160 | 161 | @Test 162 | fun `withConnection does not close connection if connection was not added to context`() { 163 | val existing = mockk { 164 | every { isClosed } returns false 165 | } 166 | 167 | val dataSource = mockk { 168 | every { connection } returns existing 169 | } 170 | 171 | val context = CoroutineDataSource(dataSource) + CoroutineConnection(existing) 172 | 173 | runBlockingTest(context) { 174 | withConnection { } 175 | } 176 | 177 | verify(exactly = 0) { existing.close() } 178 | } 179 | } 180 | -------------------------------------------------------------------------------- /src/test/kotlin/com/github/michaelbull/jdbc/TransactionTest.kt: -------------------------------------------------------------------------------- 1 | package com.github.michaelbull.jdbc 2 | 3 | import com.github.michaelbull.jdbc.context.CoroutineConnection 4 | import com.github.michaelbull.jdbc.context.CoroutineTransaction 5 | import io.mockk.every 6 | import io.mockk.just 7 | import io.mockk.mockk 8 | import io.mockk.runs 9 | import io.mockk.verify 10 | import kotlinx.coroutines.ExperimentalCoroutinesApi 11 | import kotlinx.coroutines.test.runBlockingTest 12 | import org.junit.jupiter.api.Assertions.assertEquals 13 | import org.junit.jupiter.api.Assertions.assertNotNull 14 | import org.junit.jupiter.api.Test 15 | import org.junit.jupiter.api.assertThrows 16 | import java.sql.Connection 17 | 18 | @ExperimentalCoroutinesApi 19 | class TransactionTest { 20 | 21 | @Test 22 | fun `nested transactions`() { 23 | val connection = mockk(relaxed = true) { 24 | every { isClosed } returns false 25 | every { autoCommit } returns true 26 | } 27 | 28 | val context = CoroutineConnection(connection) 29 | 30 | val expected = (((((5 * 2) * 3) / 2) + 5) * 100) / 2 31 | var actual = 0 32 | 33 | runBlockingTest(context) { 34 | transaction { 35 | actual = 5 36 | 37 | transaction { 38 | actual *= 2 39 | } 40 | 41 | transaction { 42 | actual *= 3 43 | } 44 | 45 | transaction { 46 | actual /= 2 47 | 48 | transaction { 49 | actual += 5 50 | 51 | transaction { 52 | actual *= 100 53 | } 54 | } 55 | } 56 | 57 | transaction { 58 | actual /= 2 59 | } 60 | } 61 | } 62 | 63 | assertEquals(expected, actual) 64 | } 65 | 66 | @Test 67 | fun `transaction reuses existing transaction in context if incomplete`() { 68 | val incompleteTransaction = CoroutineTransaction(completed = false) 69 | 70 | runBlockingTest(incompleteTransaction) { 71 | val actual = transaction { 72 | coroutineContext[CoroutineTransaction] 73 | } 74 | 75 | assertEquals(incompleteTransaction, actual) 76 | } 77 | } 78 | 79 | @Test 80 | fun `transaction throws IllegalStateException if existing transaction in context is completed`() { 81 | val completeTransaction = CoroutineTransaction(completed = true) 82 | 83 | assertThrows { 84 | runBlockingTest(completeTransaction) { 85 | transaction { } 86 | } 87 | } 88 | } 89 | 90 | @Test 91 | fun `transaction throws IllegalStateException if context is empty`() { 92 | assertThrows { 93 | runBlockingTest { 94 | transaction { 95 | 96 | } 97 | } 98 | } 99 | } 100 | 101 | @Test 102 | fun `transaction adds new transaction to context if no transaction in context`() { 103 | val connection = mockk(relaxed = true) { 104 | every { isClosed } returns false 105 | every { autoCommit } returns true 106 | } 107 | 108 | val context = CoroutineConnection(connection) 109 | 110 | runBlockingTest(context) { 111 | val transaction = transaction { 112 | coroutineContext[CoroutineTransaction] 113 | } 114 | 115 | assertNotNull(transaction) 116 | } 117 | } 118 | 119 | @Test 120 | fun `runTransactionally adds new transaction to context`() { 121 | val connection = mockk(relaxed = true) { 122 | every { autoCommit } returns true 123 | } 124 | 125 | val context = CoroutineConnection(connection) 126 | 127 | runBlockingTest(context) { 128 | val transaction = runTransactionally { 129 | coroutineContext[CoroutineTransaction] 130 | } 131 | 132 | assertNotNull(transaction) 133 | } 134 | } 135 | 136 | @Test 137 | fun `runTransactionally calls commit on success`() { 138 | val connection = mockk(relaxed = true) { 139 | every { autoCommit } returns true 140 | } 141 | 142 | val context = CoroutineConnection(connection) 143 | 144 | runBlockingTest(context) { 145 | runTransactionally {} 146 | } 147 | 148 | verify(exactly = 1) { connection.commit() } 149 | } 150 | 151 | @Test 152 | fun `runTransactionally does not call rollback on success`() { 153 | val connection = mockk(relaxed = true) { 154 | every { autoCommit } returns true 155 | } 156 | 157 | val context = CoroutineConnection(connection) 158 | 159 | runBlockingTest(context) { 160 | runTransactionally {} 161 | } 162 | 163 | verify(exactly = 0) { connection.rollback() } 164 | } 165 | 166 | @Test 167 | fun `runTransactionally calls rollback on failure`() { 168 | val connection = mockk(relaxed = true) { 169 | every { autoCommit } returns true 170 | } 171 | 172 | val context = CoroutineConnection(connection) 173 | 174 | try { 175 | runBlockingTest(context) { 176 | runTransactionally { 177 | throw Throwable() 178 | } 179 | } 180 | } catch (ignored: Throwable) { 181 | 182 | } 183 | 184 | verify(exactly = 1) { connection.rollback() } 185 | } 186 | 187 | @Test 188 | fun `runTransactionally does not call commit on failure`() { 189 | val connection = mockk(relaxed = true) { 190 | every { autoCommit } returns true 191 | } 192 | 193 | val context = CoroutineConnection(connection) 194 | 195 | try { 196 | runBlockingTest(context) { 197 | runTransactionally { 198 | throw Throwable() 199 | } 200 | } 201 | } catch (ignored: Throwable) { 202 | 203 | } 204 | 205 | verify(exactly = 0) { connection.commit() } 206 | } 207 | 208 | @Test 209 | fun `runTransactionally rethrows exceptions`() { 210 | val connection = mockk(relaxed = true) { 211 | every { autoCommit } returns true 212 | } 213 | 214 | val context = CoroutineConnection(connection) 215 | 216 | assertThrows { 217 | runBlockingTest(context) { 218 | runTransactionally { 219 | throw IllegalArgumentException() 220 | } 221 | } 222 | } 223 | } 224 | 225 | @Test 226 | fun `runWithManualCommit sets autoCommit to false before running`() { 227 | val connection = mockk { 228 | every { autoCommit } returns true 229 | every { autoCommit = any() } just runs 230 | } 231 | 232 | connection.runWithManualCommit { 233 | verify(exactly = 1) { connection.autoCommit = false } 234 | } 235 | } 236 | 237 | @Test 238 | fun `runWithManualCommit restores autoCommit to original value after running`() { 239 | val connection = mockk { 240 | every { autoCommit } returns true 241 | every { autoCommit = any() } just runs 242 | } 243 | 244 | connection.runWithManualCommit { } 245 | 246 | verify(exactly = 1) { connection.autoCommit = true } 247 | } 248 | } 249 | -------------------------------------------------------------------------------- /src/test/kotlin/com/github/michaelbull/jdbc/context/CoroutineConnectionTest.kt: -------------------------------------------------------------------------------- 1 | package com.github.michaelbull.jdbc.context 2 | 3 | import io.mockk.mockk 4 | import kotlinx.coroutines.ExperimentalCoroutinesApi 5 | import kotlinx.coroutines.test.runBlockingTest 6 | import org.junit.jupiter.api.Assertions.assertEquals 7 | import org.junit.jupiter.api.Test 8 | import org.junit.jupiter.api.assertThrows 9 | import java.sql.Connection 10 | 11 | @ExperimentalCoroutinesApi 12 | class CoroutineConnectionTest { 13 | 14 | @Test 15 | fun `connection throws IllegalStateException if not in context`() { 16 | assertThrows { 17 | runBlockingTest { 18 | coroutineContext.connection 19 | } 20 | } 21 | } 22 | 23 | @Test 24 | fun `connection returns connection if in context`() { 25 | val expected = mockk() 26 | 27 | runBlockingTest(CoroutineConnection(expected)) { 28 | val actual = coroutineContext.connection 29 | assertEquals(expected, actual) 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/test/kotlin/com/github/michaelbull/jdbc/context/CoroutineDataSourceTest.kt: -------------------------------------------------------------------------------- 1 | package com.github.michaelbull.jdbc.context 2 | 3 | import io.mockk.mockk 4 | import kotlinx.coroutines.ExperimentalCoroutinesApi 5 | import kotlinx.coroutines.test.runBlockingTest 6 | import org.junit.jupiter.api.Assertions 7 | import org.junit.jupiter.api.Test 8 | import org.junit.jupiter.api.assertThrows 9 | import javax.sql.DataSource 10 | 11 | @ExperimentalCoroutinesApi 12 | class CoroutineDataSourceTest { 13 | 14 | @Test 15 | fun `dataSource throws IllegalStateException if not in context`() { 16 | assertThrows { 17 | runBlockingTest { 18 | coroutineContext.dataSource 19 | } 20 | } 21 | } 22 | 23 | @Test 24 | fun `dataSource returns connection if in context`() { 25 | val expected = mockk() 26 | 27 | runBlockingTest(CoroutineDataSource(expected)) { 28 | val actual = coroutineContext.dataSource 29 | Assertions.assertEquals(expected, actual) 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/test/kotlin/com/github/michaelbull/jdbc/context/CoroutineTransactionTest.kt: -------------------------------------------------------------------------------- 1 | package com.github.michaelbull.jdbc.context 2 | 3 | import org.junit.jupiter.api.Assertions.assertFalse 4 | import org.junit.jupiter.api.Test 5 | 6 | class CoroutineTransactionTest { 7 | 8 | @Test 9 | fun `CoroutineTransaction can be completed`() { 10 | val transaction = CoroutineTransaction() 11 | transaction.complete() 12 | assertFalse(transaction.incomplete) 13 | } 14 | } 15 | --------------------------------------------------------------------------------