Skip to content

Commit

Permalink
Fix deleteDatabase blocking due to open connections
Browse files Browse the repository at this point in the history
- Automatically close database connections on delete
- Handle "blocked" event in deleteDatabase
  • Loading branch information
janne-koschinski committed Jan 23, 2024
1 parent 222f3a0 commit 06c1231
Showing 1 changed file with 11 additions and 3 deletions.
14 changes: 11 additions & 3 deletions core/src/jsMain/kotlin/Database.kt
Original file line number Diff line number Diff line change
Expand Up @@ -46,15 +46,22 @@ public suspend fun openDatabase(
public suspend fun deleteDatabase(name: String) {
val factory = checkNotNull(window.indexedDB) { "Your browser doesn't support IndexedDB." }
val request = factory.deleteDatabase(name)
request.onNextEvent("success", "error") { event ->
request.onNextEvent("success", "error", "blocked") { event ->
when (event.type) {
"error" -> throw ErrorEventException(event)
"error", "blocked" -> throw ErrorEventException(event)
else -> null
}
}
}

public class Database internal constructor(internal val database: IDBDatabase) {
public class Database internal constructor(database: IDBDatabase) {
private var _database: IDBDatabase? = database
internal val database: IDBDatabase
get() = _database ?: throw Exception("Database closed")
init {
database.addEventListener("versionchange", { close() })
database.addEventListener("close", { close() })
}

/**
* Inside the [action] block, you must not call any `suspend` functions except for:
Expand Down Expand Up @@ -102,6 +109,7 @@ public class Database internal constructor(internal val database: IDBDatabase) {

public fun close() {
database.close()
_database = null
}
}

Expand Down

0 comments on commit 06c1231

Please sign in to comment.