Alexander KLimov
Alexander KLimov

Reputation: 61

Kotlin Exposed transaction{} magic

I've touched Exposed SQL framework a bit and can't find answer to a question: where transaction{} block obtain a DB connection from?

It's simple test

@Test
    fun test() {
        Database.connect({
            DriverManager.getConnection("jdbc:postgresql://localhost/foo?user=postgres&password=q1")
        })

        transaction {
            connection.isClosed()
        }
    }

transaction itself is a function

fun <T> transaction(db: Database? = null, statement: Transaction.() -> T): T

or

fun <T> transaction(transactionIsolation: Int, repetitionAttempts: Int, db: Database? = null, statement: Transaction.() -> T): T

Anyway, I don't call it with any defined args.

Could someone tell me please, where this function obtains DB from when I write

transaction{
    ...
}

Thanks in advance!

Upvotes: 1

Views: 2588

Answers (1)

Alexey Soshin
Alexey Soshin

Reputation: 17721

For those that are still interested, transaction obtains DB from the TransactionManager

You can see the code here:

https://github.com/JetBrains/Exposed/blob/master/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/transactions/ThreadLocalTransactionManager.kt#L160

ThreadLocalTransactionManager holds an atomic reference to the current database:

https://github.com/JetBrains/Exposed/blob/master/exposed-core/src/main/kotlin/org/jetbrains/exposed/sql/transactions/TransactionApi.kt#L65

Upvotes: 1

Related Questions