question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Related to Koin injection combine with Ktorm

See original GitHub issue

Demo project

https://github.com/Lisooo790926/Koin_Ktor_Test

Background:

我們使用Ktorm (Database ORM) + Koin (IOC container) 來實作我們的DAO, 如下

class TestDao : KoinComponent {

    private val dataSource: DataSource by inject()
    private val database = Database.connect(dataSource)
    private val random = Random()

    fun selectCount(): Int {
        return database.from(TestTable).select(count())
            .mapNotNull { r -> r.getInt(1) }.single()
    }

    fun insert() {
        database.insert(TestTable) {
            set(it.name, "TestUser")
            set(it.age, random.nextInt())
        }
    }

    fun insertWithInputDatabase(database: Database) {
        database.insert(TestTable) {
            set(it.name, "TestUser")
            set(it.age, random.nextInt())
        }
    }
}

object TestTable : Table<Nothing>("test") {
    val id = long("id")
    val name = varchar("name")
    val age = int("age")
    val createTime = timestamp("create_time")
}

Question:

測試時發現使用 database.useTransaction時, 如果在內部使用Koin的bean而其內部也是透過inject去建立新的connection, 如下

  // ideally this scenario should use the same transaction
  get("/dao-database/use-transaction-to-insert-data") {
      database.useTransaction {
          testDao.insert() // create new connection
          testDao.insert()
          testDao.insert()
          throw Exception("To rollback whole transaction")
      }
  }

我們原先認為他會使用同一條connection, 但此處因為建立一條新的connection而喪失atomic 只有在我們將當前的connection傳進去後, 才能維持atomic

  get("/same-database/use-transaction-to-insert-data") {
      database.useTransaction {
          testDao.insertWithInputDatabase(database) // keep orignal conneciton
          testDao.insertWithInputDatabase(database)
          testDao.insertWithInputDatabase(database)
          throw Exception("To rollback whole transaction")
      }
  }

請問當Koin + Ktorm要使用useTransaction時有甚麼建議嗎, 或者以上問題可以改善嗎?

感謝

Issue Analytics

  • State:open
  • Created a year ago
  • Comments:6 (2 by maintainers)

github_iconTop GitHub Comments

1reaction
vincentlauvlwjcommented, Aug 4, 2022

還是Database 內部會自動調用pool的connection, 不需要重複建立?

Yes

0reactions
Lisooo790926commented, Aug 4, 2022

所以理想情況一個Database的singleton, 基本連同datasource一起建立即可

single { buildDatabase(config) }

fun buildDatabase(config: ApplicationConfig): Database {
    val hikariConfig = HikariConfig().apply {
        poolName = config.propertyOrNull("dataSource.poolName")?.getString()
        .... 
    return Database.connect(HikariDataSource(hikariConfig))
}

不需要兩個singleton in Koin

Read more comments on GitHub >

github_iconTop Results From Across the Web

Dependency Injection with Kotlin and Koin - Auth0
In this post, we'll look at a simple application taking advantage of Koin to inject dependencies into our custom classes. Prerequisites. To ...
Read more >
Query - Ktorm
Query is an abstraction of query operations and the core of Ktorm's query DSL. Its constructor accepts two parameters: database is the database...
Read more >
How to Build an Android Wellness App with the Ktor ... - Perpetio
The Ktor's microsystem is well-integrated with Android development (similar libraries, like Koin, for dependency injection, Ktor allows HTTP requests, etc.) ...
Read more >
Guide to the Kotlin Exposed Framework - Baeldung
As we can see, it is a sequence of comparisons combined together with and ... In the general case, the full form of...
Read more >
Kotlin Native and GraalVM — The Story So Far - ITNEXT
We can of course combine our Kotlin code with C code, ... native version of our code that we can then inject into...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found