Migrate local persistence from Room to SQLDelight with multiplatform support (Android+iOS); replace NoteEntity/DAO/Repository with generated SQLDelight schema, add DatabaseFactory for drivers, integrate Flow support for Compose UI updates

This commit is contained in:
2025-09-26 20:57:05 +02:00
parent a42070e36b
commit 52ffb2c958
14 changed files with 99 additions and 101 deletions

View File

@@ -125,8 +125,8 @@ dependencies {
// Use Ktor-based multiplatform networking backend for Coil
implementation("io.coil-kt.coil3:coil-network-ktor3:3.3.0")
// SQLDelight coroutine-extensions (för Android-appen, krävs för .asFlow() och .mapToList())
implementation("app.cash.sqldelight:coroutines-extensions:2.1.0")
}
androidComponents {

View File

@@ -30,13 +30,13 @@ import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.decodeToImageBitmap
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import app.cash.sqldelight.coroutines.asFlow // SQLDelight coroutine-extensions (Flow-stöd för queries)
import app.cash.sqldelight.coroutines.mapToList // SQLDelight coroutine-extensions (Flow-stöd för queries)
import app.klottr.auth.AuthPlatform
import app.klottr.create.CreateNoteOutcome
import app.klottr.create.QueueOutboxOutcome
import app.klottr.create.createNoteFlow
import app.klottr.create.queueNoteDocOutbox
import app.klottr.data.AppDatabase
import app.klottr.data.NoteRepository
import app.klottr.events.FoundEvents
import app.klottr.location.LastLocationStore
import app.klottr.location.LocationServiceProvider
@@ -114,17 +114,30 @@ fun KlottrAppShell(
val locService = remember { LocationServiceProvider.get() }
LaunchedEffect(Unit) { locService.start() }
val currentLoc = locService.location.collectAsState(initial = null)
val context = LocalContext.current
val scope = rememberCoroutineScope()
// Hämta Android-Context (behövs för att skapa databasen på Android).
val context = LocalContext.current
// Inloggning
val loggedIn by AuthShared.loggedIn.collectAsState(initial = false)
LaunchedEffect(Unit) { AuthPlatform.refreshSilently(context) { } }
// DB/Repo
val db = remember { AppDatabase.Companion.getInstance(context) }
val repo = remember { NoteRepository(db.noteDao()) }
val notes by repo.allNotes().collectAsState(initial = emptyList())
// Initiera SQLDelight-databasen med hjälp av DatabaseFactory.
val db = remember {
val driver = app.klottr.db.DatabaseFactory(context).createDriver()
app.klottr.db.KlottrDatabase(driver)
}
// Exponera notes som en State<List<Note>> med Compose-stöd.
// asFlow() -> gör queryn reaktiv (ström av ändringar).
// mapToList() -> konverterar varje queryresultat till en lista.
// collectAsState() -> gör om Flow till Compose-State, så UI ritas om automatiskt.
val notes by db.notesQueries.all()
.asFlow()
.mapToList(Dispatchers.IO)
.collectAsState(initial = emptyList())
// Settings-state
// Läser från KMP SettingsStore (no-arg-API). Inga Context-beroenden här längre.

View File

@@ -17,6 +17,8 @@ import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalContext
import app.klottr.db.DatabaseFactory
import app.klottr.db.KlottrDatabase
import app.klottr.net.ImageReader
import app.klottr.shared.SharedPing
import app.klottr.theme.KlottrTheme
@@ -40,6 +42,12 @@ class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Initiera SQLDelight-databasen
val driver = DatabaseFactory(this).createDriver()
val database = KlottrDatabase(driver)
val notesQueries = database.notesQueries
KLog.setEnabled(BuildConfig.KLLOG_DEBUG) // Styr loggnivå via buildflagga
app.klottr.prefs.KvPrefs.init(applicationContext)
LocationServiceProvider.init(applicationContext)

View File

@@ -1,38 +0,0 @@
package app.klottr.data
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
//TODO: OH: We should use something more platform independent for local DB instead of Room.
// ChatGPT suggests SQLDelight
@Database(entities = [NoteEntity::class], version = 2)
abstract class AppDatabase : RoomDatabase() {
abstract fun noteDao(): NoteDao
companion object {
@Volatile private var INSTANCE: AppDatabase? = null
// Migration: lägg till kolumnen createdAt (INTEGER NOT NULL DEFAULT 0)
private val MIGRATION_1_2 = object : Migration(1, 2) {
override fun migrate(db: SupportSQLiteDatabase) {
db.execSQL("ALTER TABLE notes ADD COLUMN createdAt INTEGER NOT NULL DEFAULT 0")
}
}
fun getInstance(ctx: Context): AppDatabase =
INSTANCE ?: synchronized(this) {
INSTANCE ?: Room.databaseBuilder(
ctx.applicationContext,
AppDatabase::class.java,
"klottr.db"
)
.addMigrations(MIGRATION_1_2)
.build().also { INSTANCE = it }
}
}
}

View File

@@ -1,13 +0,0 @@
package app.klottr.data
import androidx.room.*
import kotlinx.coroutines.flow.Flow
@Dao
interface NoteDao {
@Query("SELECT * FROM notes ORDER BY id DESC")
fun all(): Flow<List<NoteEntity>>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun upsert(note: NoteEntity)
}

View File

@@ -1,18 +0,0 @@
package app.klottr.data
import androidx.room.Entity
import androidx.room.Index
import androidx.room.PrimaryKey
@Entity(
tableName = "notes",
indices = [Index(value = ["lat", "lon"], unique = true)]
)
data class NoteEntity(
@PrimaryKey(autoGenerate = true) val id: Long = 0,
val lat: Double,
val lon: Double,
val text: String,
// Ny tidsstämpel (ms sedan 1970). Gamla rader får 0 via migration.
val createdAt: Long = System.currentTimeMillis()
)

View File

@@ -1,8 +0,0 @@
package app.klottr.data
import kotlinx.coroutines.flow.Flow
class NoteRepository(private val dao: NoteDao) {
fun allNotes(): Flow<List<NoteEntity>> = dao.all()
suspend fun upsert(note: NoteEntity) = dao.upsert(note)
}

View File

@@ -6,7 +6,6 @@ import android.app.NotificationManager
import android.content.Context
import android.os.Build
import androidx.core.app.NotificationCompat
import app.klottr.data.NoteEntity
import app.klottr.R
object Notifications {
@@ -38,18 +37,6 @@ object Notifications {
val nm = ctx.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
nm.notify(ONGOING_ID, buildOngoing(ctx, text))
}
fun showHit(ctx: Context, note: NoteEntity) {
val nm = ctx.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val n = NotificationCompat.Builder(ctx, CHANNEL_HIT)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Klottr – sparad plats")
.setContentText(note.text.take(80))
.setStyle(NotificationCompat.BigTextStyle().bigText("${note.text}\n(${note.lat}, ${note.lon})"))
.setAutoCancel(true)
.build()
nm.notify(note.id.toInt().coerceAtLeast(2), n)
}
}
// Enkel in‑app “toast”

View File

@@ -9,4 +9,4 @@ plugins {
alias(libs.plugins.kotlin.serialization) apply false
alias(libs.plugins.ksp) apply false
alias(libs.plugins.compose) apply false
}
}

View File

@@ -7,6 +7,7 @@ pluginManagement {
includeGroupByRegex("androidx.*")
}
}
gradlePluginPortal()
mavenCentral()
maven("https://maven.pkg.jetbrains.space/public/p/compose/dev")
gradlePluginPortal()

View File

@@ -22,6 +22,7 @@ plugins {
id("com.codingfeline.buildkonfig") version "0.17.1"
kotlin("native.cocoapods")
id("app.cash.sqldelight") version "2.1.0"
}
kotlin {
@@ -128,6 +129,13 @@ kotlin {
// Use Ktor-based multiplatform networking backend for Coil
implementation("io.coil-kt.coil3:coil-network-ktor3:3.3.0")
// SQLDelight Coroutines Extensions:
// Gör att queries (t.ex. notesQueries.all()) kan exponeras som Flow.
// Flow används ihop med Compose för att automatiskt uppdatera UI när DB-data ändras.
implementation("app.cash.sqldelight:coroutines-extensions:2.1.0")
// Kotlinx coroutines-core (krävs för Flow + SQLDelight coroutines-extensions)
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.9.0")
// för Compose i :shared (Android-del)
@@ -165,6 +173,10 @@ kotlin {
implementation("androidx.activity:activity-compose:1.11.0")
// PickVisualMediaRequest + ActivityResultContracts.*
implementation("androidx.activity:activity:1.11.0")
// SQLDelight Android-driver
implementation("app.cash.sqldelight:android-driver:2.1.0")
// SQLDelight coroutine-extensions (JVM/Android)
implementation("app.cash.sqldelight:coroutines-extensions:2.1.0")
}
}
@@ -228,4 +240,12 @@ buildkonfig {
buildConfigField(BOOLEAN, "KLLOG_DEBUG", propOr("KLLOG_DEBUG", "false"))
buildConfigField(BOOLEAN, "KLLOG_HTTP_DEBUG", propOr("KLLOG_HTTP_DEBUG", "false"))
}
}
}
sqldelight {
databases {
create("KlottrDatabase") {
packageName.set("app.klottr.db")
}
}
}

View File

@@ -0,0 +1,19 @@
package app.klottr.db
import android.content.Context
import app.cash.sqldelight.db.SqlDriver
import app.cash.sqldelight.driver.android.AndroidSqliteDriver
/**
* Android-implementation av DatabaseFactory.
* Skapar en SqlDriver med AndroidSqliteDriver för att köra KlottrDatabase.
*/
actual class DatabaseFactory(private val context: Context) {
actual fun createDriver(): SqlDriver {
return AndroidSqliteDriver(
schema = KlottrDatabase.Schema,
context = context,
name = "klottr.db" // samma namn som tidigare Room använde
)
}
}

View File

@@ -0,0 +1,11 @@
package app.klottr.db
import app.cash.sqldelight.db.SqlDriver
/**
* Common deklaration: här säger vi bara att varje plattform
* (Android/iOS) måste implementera DatabaseFactory.
*/
expect class DatabaseFactory {
fun createDriver(): SqlDriver
}

View File

@@ -0,0 +1,16 @@
CREATE TABLE notes (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
lat REAL NOT NULL,
lon REAL NOT NULL,
text TEXT NOT NULL,
createdAt INTEGER NOT NULL DEFAULT 0
);
CREATE UNIQUE INDEX notes_lat_lon_index ON notes(lat, lon);
all:
SELECT * FROM notes ORDER BY id DESC;
upsert:
INSERT OR REPLACE INTO notes(id, lat, lon, text, createdAt)
VALUES (?, ?, ?, ?, ?);