From 06c12317e7089bf52c430adab5183e5f613d0b80 Mon Sep 17 00:00:00 2001 From: Janne Mareike Koschinski Date: Tue, 23 Jan 2024 10:37:48 +0100 Subject: [PATCH] Fix deleteDatabase blocking due to open connections - Automatically close database connections on delete - Handle "blocked" event in deleteDatabase --- core/src/jsMain/kotlin/Database.kt | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/core/src/jsMain/kotlin/Database.kt b/core/src/jsMain/kotlin/Database.kt index 4c6c9bd..82a3982 100644 --- a/core/src/jsMain/kotlin/Database.kt +++ b/core/src/jsMain/kotlin/Database.kt @@ -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: @@ -102,6 +109,7 @@ public class Database internal constructor(internal val database: IDBDatabase) { public fun close() { database.close() + _database = null } }