migrate(local-db): replace Room with SQLDelight for JS/WASM compatibility

Replaced Room with SQLDelight for improved multiplatform support, enabling JavaScript and WebAssembly targets. Added custom database driver implementations for JVM, JS, and WASM. Updated Gradle configurations, dependencies, and project structure accordingly.
This commit is contained in:
2026-01-09 12:32:12 +01:00
parent 6443edd386
commit 13cfc37b37
26 changed files with 833 additions and 397 deletions
+5 -5
View File
@@ -29,11 +29,11 @@ kotlin {
implementation(projects.frontend.shared)
// Compose dependencies
implementation("org.jetbrains.compose.runtime:runtime:1.10.0-rc02")
implementation("org.jetbrains.compose.foundation:foundation:1.10.0-rc02")
implementation("org.jetbrains.compose.material3:material3:1.9.0-beta03")
implementation("org.jetbrains.compose.ui:ui:1.10.0-rc02")
implementation("org.jetbrains.compose.components:components-resources:1.10.0-rc02")
implementation(compose.runtime)
implementation(compose.foundation)
implementation(compose.material3)
implementation(compose.ui)
implementation(compose.components.resources)
// Coroutines
implementation(libs.kotlinx.coroutines.core)
+28 -13
View File
@@ -5,12 +5,12 @@ import org.jetbrains.kotlin.gradle.ExperimentalKotlinGradlePluginApi
plugins {
alias(libs.plugins.kotlinMultiplatform)
alias(libs.plugins.kotlinSerialization)
alias(libs.plugins.androidx.room)
alias(libs.plugins.ksp)
alias(libs.plugins.sqldelight)
}
kotlin {
// Toolchain is now handled centrally in the root build.gradle.kts
val enableWasm = providers.gradleProperty("enableWasm").orNull == "true"
jvm()
js {
@@ -19,18 +19,34 @@ kotlin {
}
}
if (enableWasm) {
@OptIn(org.jetbrains.kotlin.gradle.ExperimentalWasmDsl::class)
wasmJs {
browser()
}
}
sourceSets {
commonMain.dependencies {
implementation(libs.koin.core)
implementation(libs.kotlinx.coroutines.core)
implementation(libs.androidx.room.runtime)
implementation(libs.androidx.sqlite.bundled)
implementation(libs.bundles.kmp.common) // Coroutines, Serialization, DateTime
implementation(libs.sqldelight.runtime)
implementation(libs.sqldelight.coroutines)
}
jvmMain.dependencies {
implementation(libs.sqldelight.driver.sqlite)
}
jsMain.dependencies {
implementation(libs.sqldelight.driver.web)
}
if (enableWasm) {
val wasmJsMain = getByName("wasmJsMain")
wasmJsMain.dependencies {
implementation(libs.sqldelight.driver.web)
}
}
commonTest.dependencies {
@@ -39,12 +55,11 @@ kotlin {
}
}
room {
schemaDirectory("$projectDir/schemas")
}
dependencies {
add("kspCommonMainMetadata", libs.androidx.room.compiler)
add("kspJvm", libs.androidx.room.compiler)
// add("kspJs", libs.androidx.room.compiler) // Room compiler support for JS might vary, check specific version support
sqldelight {
databases {
create("AppDatabase") {
packageName.set("at.mocode.frontend.core.localdb")
generateAsync.set(true) // WICHTIG: Async-First für JS/Wasm Support
}
}
}
@@ -0,0 +1,8 @@
package at.mocode.frontend.core.localdb
import app.cash.sqldelight.db.SqlDriver
@Suppress("EXPECT_ACTUAL_CLASSIFIERS_ARE_IN_BETA_WARNING")
expect class DatabaseDriverFactory {
suspend fun createDriver(): SqlDriver
}
@@ -1,34 +0,0 @@
@file:Suppress("EXPECT_ACTUAL_CLASSIFIERS_ARE_IN_BETA_WARNING")
package at.mocode.frontend.core.localdb
import androidx.room.RoomDatabase
import androidx.sqlite.driver.bundled.BundledSQLiteDriver
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.IO
import org.koin.dsl.module
// Abstract Room Database class definition
// @Database(entities = [MyEntity::class], version = 1) // Entities need to be defined
abstract class MeldestelleDb : RoomDatabase() {
// abstract fun myDao(): MyDao
}
// Factory to create the database builder platform-specifically
expect class DatabaseBuilderFactory() {
fun create(): RoomDatabase.Builder<MeldestelleDb>
}
class DatabaseProvider(private val factory: DatabaseBuilderFactory) {
fun createDatabase(): MeldestelleDb {
return factory.create()
.setDriver(BundledSQLiteDriver())
.setQueryCoroutineContext(Dispatchers.IO)
.build()
}
}
val localDbModule = module {
single { DatabaseBuilderFactory() }
single { DatabaseProvider(get()).createDatabase() }
}
@@ -0,0 +1,17 @@
CREATE TABLE Task (
id TEXT NOT NULL PRIMARY KEY,
content TEXT NOT NULL,
is_completed INTEGER NOT NULL DEFAULT 0
);
selectAll:
SELECT *
FROM Task;
insert:
INSERT INTO Task(id, content, is_completed)
VALUES ?;
delete:
DELETE FROM Task
WHERE id = ?;
@@ -0,0 +1,22 @@
package at.mocode.frontend.core.localdb
import app.cash.sqldelight.db.SqlDriver
import app.cash.sqldelight.driver.worker.WebWorkerDriver
import org.w3c.dom.Worker
actual class DatabaseDriverFactory {
actual suspend fun createDriver(): SqlDriver {
// Load the worker script. This assumes the worker is bundled correctly by Webpack.
// We use a custom worker entry point to support OPFS if needed (as per report).
// For now, we point to a resource we will create.
val worker = Worker(
js("""new URL("sqlite.worker.js", import.meta.url)""")
)
val driver = WebWorkerDriver(worker)
// Initialize schema asynchronously
AppDatabase.Schema.create(driver).await()
return driver
}
}
@@ -1,26 +0,0 @@
@file:Suppress("EXPECT_ACTUAL_CLASSIFIERS_ARE_IN_BETA_WARNING")
package at.mocode.frontend.core.localdb
import app.cash.sqldelight.db.SqlDriver
import app.cash.sqldelight.driver.worker.WebWorkerDriver
import org.w3c.dom.Worker
actual class DatabaseDriverFactory {
actual suspend fun createDriver(): SqlDriver {
val worker = js(
"new Worker(new URL('@cashapp/sqldelight-sqljs-worker/sqljs.worker.js', import.meta.url))"
) as Worker
val driver = WebWorkerDriver(worker)
// Create schema asynchronously
MeldestelleDb.Schema.create(driver).await()
return driver
}
}
actual class DatabaseProvider {
actual suspend fun createDatabase(): MeldestelleDb {
val driver = DatabaseDriverFactory().createDriver()
return MeldestelleDb(driver)
}
}
@@ -0,0 +1,23 @@
import { runWorker } from '@cashapp/sqldelight-sqljs-worker';
import sqlite3InitModule from '@sqlite.org/sqlite-wasm';
sqlite3InitModule({
print: console.log,
printErr: console.error,
}).then((sqlite3) => {
const opfsAvailable = 'opfs' in sqlite3;
runWorker({
driver: {
open: (name) => {
if (opfsAvailable) {
console.log("Initialisiere persistente OPFS Datenbank: " + name);
return new sqlite3.oo1.OpfsDb(name);
} else {
console.warn("OPFS nicht verfügbar, Fallback auf In-Memory");
return new sqlite3.oo1.DB(name);
}
}
}
});
});
@@ -0,0 +1,34 @@
package at.mocode.frontend.core.localdb
import app.cash.sqldelight.db.SqlDriver
import app.cash.sqldelight.driver.jdbc.sqlite.JdbcSqliteDriver
import java.io.File
actual class DatabaseDriverFactory {
actual suspend fun createDriver(): SqlDriver {
// For desktop, we use a persistent file database
// In dev mode, we might want to use a temporary file or user home
val dbFile = File(System.getProperty("user.home"), ".meldestelle/app_database.db")
dbFile.parentFile.mkdirs()
val driver = JdbcSqliteDriver("jdbc:sqlite:${dbFile.absolutePath}")
// Schema creation/migration needs to be handled carefully.
// For now, we just create it if it doesn't exist.
// In a real app, we'd check version and migrate.
// Since generateAsync=true, the Schema.create signature might be suspend or return AsyncResult.
// However, JdbcSqliteDriver is synchronous. We might need to wrap or await.
// But wait! Schema.create(driver) returns void or Unit usually.
// Let's check the generated code later. For now, we assume standard behavior.
try {
AppDatabase.Schema.create(driver).await()
} catch (e: Exception) {
// Schema might already exist.
// SQLDelight doesn't have "createIfNotExists" built-in easily without version check.
// We'll leave this simple for now and refine with proper migration logic later.
}
return driver
}
}
@@ -1,22 +0,0 @@
@file:Suppress("EXPECT_ACTUAL_CLASSIFIERS_ARE_IN_BETA_WARNING")
package at.mocode.frontend.core.localdb
import app.cash.sqldelight.db.SqlDriver
import app.cash.sqldelight.driver.jdbc.sqlite.JdbcSqliteDriver
actual class DatabaseDriverFactory {
actual suspend fun createDriver(): SqlDriver {
val driver = JdbcSqliteDriver(JdbcSqliteDriver.IN_MEMORY)
// Create schema on first run (in-memory is always new)
MeldestelleDb.Schema.create(driver)
return driver
}
}
actual class DatabaseProvider {
actual suspend fun createDatabase(): MeldestelleDb {
val driver = DatabaseDriverFactory().createDriver()
return MeldestelleDb(driver)
}
}
@@ -0,0 +1,19 @@
package at.mocode.frontend.core.localdb
import app.cash.sqldelight.db.SqlDriver
import app.cash.sqldelight.driver.worker.WebWorkerDriver
import org.w3c.dom.Worker
actual class DatabaseDriverFactory {
actual suspend fun createDriver(): SqlDriver {
// Same as JS, we use a Web Worker for Wasm to support OPFS
val worker = Worker(
js("""new URL("sqlite.worker.js", import.meta.url)""")
)
val driver = WebWorkerDriver(worker)
AppDatabase.Schema.create(driver).await()
return driver
}
}
@@ -0,0 +1,23 @@
import { runWorker } from '@cashapp/sqldelight-sqljs-worker';
import sqlite3InitModule from '@sqlite.org/sqlite-wasm';
sqlite3InitModule({
print: console.log,
printErr: console.error,
}).then((sqlite3) => {
const opfsAvailable = 'opfs' in sqlite3;
runWorker({
driver: {
open: (name) => {
if (opfsAvailable) {
console.log("Initialisiere persistente OPFS Datenbank: " + name);
return new sqlite3.oo1.OpfsDb(name);
} else {
console.warn("OPFS nicht verfügbar, Fallback auf In-Memory");
return new sqlite3.oo1.DB(name);
}
}
}
});
});
@@ -0,0 +1,29 @@
package at.mocode.frontend.core.network
import kotlinx.browser.window
@Suppress("UnsafeCastFromDynamic", "EXPECT_ACTUAL_CLASSIFIERS_ARE_IN_BETA_WARNING")
actual object PlatformConfig {
actual fun resolveApiBaseUrl(): String {
// 1) Prefer a global JS variable (can be injected by index.html or nginx)
val global =
js("typeof globalThis !== 'undefined' ? globalThis : (typeof window !== 'undefined' ? window : (typeof self !== 'undefined' ? self : {}))")
val fromGlobal = try {
(global.API_BASE_URL as? String)?.trim().orEmpty()
} catch (_: dynamic) {
""
}
if (fromGlobal.isNotEmpty()) return fromGlobal.removeSuffix("/")
// 2) Try window location origin (same origin gateway/proxy setup)
val origin = try {
window.location.origin
} catch (_: dynamic) {
null
}
if (!origin.isNullOrBlank()) return origin.removeSuffix("/")
// 3) Fallback to the local gateway
return "http://localhost:8081"
}
}
+18 -39
View File
@@ -45,45 +45,30 @@ kotlin {
// Shared Konfig & Utilities (AppConfig + BuildConfig)
implementation(projects.frontend.shared)
// Compose dependencies
//implementation("org.jetbrains.compose.runtime:runtime:1.10.0-rc02")
implementation("org.jetbrains.compose.runtime:runtime:1.10.0-rc02")
implementation("org.jetbrains.compose.foundation:foundation:1.10.0-rc02")
implementation("org.jetbrains.compose.material3:material3:1.9.0-beta03")
implementation("org.jetbrains.compose.ui:ui:1.10.0-rc02")
implementation("org.jetbrains.compose.components:components-resources:1.10.0-rc02")
implementation("org.jetbrains.compose.material:material-icons-extended:1.7.3")
// Ktor client for HTTP calls
implementation(libs.ktor.client.core)
implementation(libs.ktor.client.contentNegotiation)
implementation(libs.ktor.client.serialization.kotlinx.json)
implementation(libs.ktor.client.logging)
implementation(libs.ktor.client.auth)
// DI
implementation(libs.koin.core)
// Network core (provides apiClient + TokenProvider)
implementation(projects.frontend.core.network)
// Coroutines and serialization
implementation(libs.kotlinx.coroutines.core)
implementation(libs.kotlinx.serialization.json)
// Compose dependencies (Core UI)
implementation(compose.runtime)
implementation(compose.foundation)
implementation(compose.material3)
implementation(compose.ui)
implementation(compose.components.resources)
implementation(compose.materialIconsExtended)
// DateTime for multiplatform time handling
implementation(libs.kotlinx.datetime)
// ViewModel lifecycle
implementation(libs.androidx.lifecycle.viewmodelCompose)
implementation(libs.androidx.lifecycle.runtimeCompose)
// Bundles (Cleaned up dependencies)
implementation(libs.bundles.kmp.common) // Coroutines, Serialization, DateTime
implementation(libs.bundles.ktor.client.common) // Ktor Client (Core, Auth, JSON, Logging)
implementation(libs.bundles.compose.common) // ViewModel & Lifecycle
// DI
implementation(libs.koin.core)
}
commonTest.dependencies {
implementation(libs.kotlin.test)
implementation(libs.kotlinx.coroutines.test)
implementation("io.ktor:ktor-client-mock:${libs.versions.ktor.get()}")
implementation(libs.ktor.client.mock)
}
jvmTest.dependencies {
@@ -98,10 +83,6 @@ kotlin {
jsMain.dependencies {
implementation(libs.ktor.client.js)
implementation(libs.ktor.client.auth)
implementation(libs.kotlinx.coroutines.core)
implementation(libs.kotlinx.serialization.json)
implementation(libs.kotlinx.datetime)
}
// WASM SourceSet, nur wenn aktiviert
@@ -110,12 +91,10 @@ kotlin {
wasmJsMain.dependencies {
implementation(libs.ktor.client.js) // WASM verwendet JS-Client [cite: 7]
// ✅ HINZUFÜGEN: Compose für shared UI components für WASM
implementation("org.jetbrains.compose.runtime:runtime:1.10.0-rc02")
implementation("org.jetbrains.compose.foundation:foundation:1.10.0-rc02")
implementation("org.jetbrains.compose.material3:material3:1.9.0-beta03")
// Compose für shared UI components für WASM
implementation(compose.runtime)
implementation(compose.foundation)
implementation(compose.material3)
}
}
}
@@ -55,30 +55,16 @@ kotlin {
implementation(compose.components.resources)
implementation(compose.materialIconsExtended)
// Ktor client for HTTP calls
implementation(libs.ktor.client.core)
implementation(libs.ktor.client.contentNegotiation)
implementation(libs.ktor.client.serialization.kotlinx.json)
implementation(libs.ktor.client.logging)
implementation(libs.ktor.client.auth)
// Coroutines and serialization
implementation(libs.kotlinx.coroutines.core)
implementation(libs.kotlinx.serialization.json)
// DateTime for multiplatform time handling
implementation(libs.kotlinx.datetime)
// ViewModel lifecycle
implementation(libs.androidx.lifecycle.viewmodelCompose)
implementation(libs.androidx.lifecycle.runtimeCompose)
// Bundles (Cleaned up dependencies)
implementation(libs.bundles.kmp.common) // Coroutines, Serialization, DateTime
implementation(libs.bundles.ktor.client.common) // Ktor Client (Core, Auth, JSON, Logging)
implementation(libs.bundles.compose.common) // ViewModel & Lifecycle
}
commonTest.dependencies {
implementation(libs.kotlin.test)
implementation(libs.kotlinx.coroutines.test)
implementation("io.ktor:ktor-client-mock:${libs.versions.ktor.get()}")
implementation(libs.ktor.client.mock)
}
jvmTest.dependencies {
@@ -93,10 +79,6 @@ kotlin {
jsMain.dependencies {
implementation(libs.ktor.client.js)
implementation(libs.ktor.client.auth)
implementation(libs.kotlinx.coroutines.core)
implementation(libs.kotlinx.serialization.json)
implementation(libs.kotlinx.datetime)
}
// WASM SourceSet, nur wenn aktiviert
@@ -105,7 +87,7 @@ kotlin {
wasmJsMain.dependencies {
implementation(libs.ktor.client.js) // WASM verwendet JS-Client [cite: 7]
// ✅ HINZUFÜGEN: Compose für shared UI components für WASM
// Compose für shared UI components für WASM
implementation(compose.runtime)
implementation(compose.foundation)
implementation(compose.material3)
+14 -24
View File
@@ -49,32 +49,26 @@ kotlin {
implementation(projects.frontend.shared)
// Compose dependencies
implementation("org.jetbrains.compose.foundation:foundation:1.10.0-rc02")
implementation("org.jetbrains.compose.runtime:runtime:1.10.0-rc02")
implementation("org.jetbrains.compose.material3:material3:1.9.0-beta03")
implementation("org.jetbrains.compose.ui:ui:1.10.0-rc02")
implementation("org.jetbrains.compose.components:components-resources:1.10.0-rc02")
implementation("org.jetbrains.compose.material:material-icons-extended:1.7.3")
implementation(compose.foundation)
implementation(compose.runtime)
implementation(compose.material3)
implementation(compose.ui)
implementation(compose.components.resources)
implementation(compose.materialIconsExtended)
// Ktor client for HTTP calls
implementation(libs.ktor.client.core)
// Coroutines and serialization
implementation(libs.kotlinx.coroutines.core)
// Bundles (Cleaned up dependencies)
implementation(libs.bundles.kmp.common) // Coroutines, Serialization, DateTime
implementation(libs.bundles.ktor.client.common) // Ktor Client (Core, Auth, JSON, Logging)
implementation(libs.bundles.compose.common) // ViewModel & Lifecycle
// DI (Koin) for resolving apiClient from container
implementation(libs.koin.core)
// ViewModel lifecycle
implementation(libs.bundles.compose.common)
}
commonTest.dependencies {
implementation(libs.kotlin.test)
implementation(libs.kotlinx.coroutines.test)
implementation(libs.ktor.client.mock)
}
jvmTest.dependencies {
@@ -85,13 +79,10 @@ kotlin {
jvmMain.dependencies {
implementation(libs.ktor.client.cio)
// Auth-Models Zugriff (nur für JVM)
//implementation(project(":infrastructure:auth:auth-client"))
}
jsMain.dependencies {
implementation(libs.ktor.client.js)
}
// WASM SourceSet, nur wenn aktiviert
@@ -100,11 +91,10 @@ kotlin {
wasmJsMain.dependencies {
implementation(libs.ktor.client.js) // WASM verwendet JS-Client [cite: 7]
// ✅ HINZUFÜGEN: Compose für shared UI components für WASM
implementation("org.jetbrains.compose.runtime:runtime:1.10.0-rc02")
implementation("org.jetbrains.compose.foundation:foundation:1.10.0-rc02")
implementation("org.jetbrains.compose.material3:material3:1.9.0-beta03")
// Compose für shared UI components für WASM
implementation(compose.runtime)
implementation(compose.foundation)
implementation(compose.material3)
}
}
}
+3 -4
View File
@@ -72,10 +72,9 @@ kotlin {
implementation(projects.frontend.core.network)
// Compose für shared UI components (common)
// KORREKTUR: Verwendung der korrekten Compose-Dependencies ohne Deprecation-Warnung
implementation("org.jetbrains.compose.runtime:runtime:1.10.0-rc02")
implementation("org.jetbrains.compose.foundation:foundation:1.10.0-rc02")
implementation("org.jetbrains.compose.material3:material3:1.9.0-beta03")
implementation(compose.runtime)
implementation(compose.foundation)
implementation(compose.material3)
}
commonTest.dependencies {
@@ -88,7 +88,6 @@ kotlin {
implementation(libs.koin.compose.viewmodel)
// Compose Multiplatform
// KORREKTUR: Verwendung der Plugin-Extension 'compose' statt hardcodierter Strings oder libs
implementation(compose.runtime)
implementation(compose.foundation)
implementation(compose.material3)
@@ -96,25 +95,18 @@ kotlin {
implementation(compose.components.resources)
implementation(compose.materialIconsExtended)
// ViewModel lifecycle
implementation(libs.bundles.compose.common)
// Coroutines, Serialization, DateTime
// KORREKTUR: Explizite Auflistung statt Bundle, um Accessor-Probleme zu vermeiden
implementation(libs.kotlinx.coroutines.core)
implementation(libs.kotlinx.serialization.json)
implementation(libs.kotlinx.datetime)
// Bundles (Cleaned up dependencies)
implementation(libs.bundles.kmp.common) // Coroutines, Serialization, DateTime
implementation(libs.bundles.compose.common) // ViewModel & Lifecycle
}
jvmMain.dependencies {
implementation(compose.desktop.currentOs)
implementation(libs.kotlinx.coroutines.swing)
implementation(libs.kotlinx.coroutines.core)
implementation(libs.koin.core)
}
jsMain.dependencies {
// KORREKTUR: compose.html.core statt libs.compose.html.core
implementation(compose.html.core)
}
@@ -124,12 +116,10 @@ kotlin {
wasmJsMain.dependencies {
implementation(libs.ktor.client.js) // WASM verwendet JS-Client [cite: 7]
// ✅ HINZUFÜGEN: Compose für shared UI components für WASM
// KORREKTUR: Verwendung der Plugin-Extension
// Compose für shared UI components für WASM
implementation(compose.runtime)
implementation(compose.foundation)
implementation(compose.material3)
}
}
@@ -0,0 +1,8 @@
// Essenzielle Header für OPFS Support (SharedArrayBuffer)
// Siehe: https://sqlite.org/wasm/doc/trunk/persistence.html#opfs
config.devServer = config.devServer || {};
config.devServer.headers = {
...config.devServer.headers,
"Cross-Origin-Opener-Policy": "same-origin",
"Cross-Origin-Embedder-Policy": "require-corp"
};