https://kotlinlang.org logo
Join SlackCommunities
Powered by
# room
  • e

    Eduardo Ruesta

    12/04/2024, 2:32 PM
    Hey team! im having an issue using Room for a KMM project. The issue only happened on iOS. I have a logout method that clear all the database:
    Copy code
    suspend fun logout(): Flow<Any> {
        return flow {
            userDao.clearAll()
            profileDao.clearAll()
            qrCodeDao.clearAll()
            teamDao.clearFavoriteCategory()
        }
    }
    this is my Dao for QrCode:
    Copy code
    @Query("DELETE FROM QRCode")
    suspend fun clearAll()
    when the user clicks on logout and then login again in the same session (without killing the app) and goes to the Qr code screen will see again the old Qr code
    b
    • 2
    • 4
  • e

    Eduardo Ruesta

    12/10/2024, 12:14 AM
    Hey!! do you know why in the App Inspection i see all my room databases closed?
    • 1
    • 2
  • p

    Pablo

    12/16/2024, 11:35 AM
    How can I get a snapshot of the current query in Room instead of a Flow? I need to get the query but not to update the UI if the room database changes before I press the "update" button. Now I got this:
    Copy code
    val uiState: StateFlow<BusStopsDBScreenUiState> = busDataRepository.getBusStops()
        .map<List<BusStop>, BusStopsDBScreenUiState> { busStops ->
            BusStopsDBScreenUiState.Success(busStops, Res.string.bus_stops_db_filled)
        }
        .catch { throwable ->
            emit(BusStopsDBScreenUiState.Error(throwable))
        }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), BusStopsDBScreenUiState.Loading)
    getBusStops returns a flow
    Copy code
    @Query("SELECT * FROM BusStops")
    fun getBusStops(): Flow<List<BusStopEntity>>
    s
    • 2
    • 2
  • g

    Giorgi

    12/19/2024, 7:31 PM
    Hi. with Room version 2.7.0-alpha12 I get error
    e: KLIB resolver: Could not find "/Users/Giorgi_Shalvashvili/IdeaProjects/app/data/build/kotlinTransformedMetadataLibraries/commonMain/androidx.room-room-runtime-2.7.0-alpha12-commonMain-Tlq32w.klib" in [/Users/Giorgi_Shalvashvili/Library/Application Support/kotlin/daemon]
    👀 2
    • 1
    • 1
  • p

    Pablo

    12/23/2024, 11:42 PM
    I have a Room database with a many to many relationship between BusStops and Lines
    Copy code
    @Entity(tableName = "BusStops")
    data class BusStopEntity(
        @PrimaryKey val id: Int = 0,
        val name: String,
        val lat: Double,
        val lon: Double
    )
    
    @Entity(tableName = "Lines")
    data class LineEntity(
        @PrimaryKey val id: Int = 0,
        val name: String
    )
    
    @Entity(primaryKeys = ["busStopId", "lineId"])
    data class BusStopLineEntity(
        val busStopId: Int,
        val lineId: Int
    )
    • 1
    • 1
  • h

    hafiz

    01/06/2025, 2:34 AM
    Hi team, I want to ask even though room already has upgrade version the library but why they still not removing? :
    Copy code
    // The Room compiler generates the `actual` implementations.
    @Suppress("NO_ACTUAL_FOR_EXPECT")
    expect object AppDatabaseConstructor : RoomDatabaseConstructor<AppDatabase>
    a
    • 2
    • 2
  • c

    calidion

    01/13/2025, 5:13 AM
    how to pass entity member in room query like this?
    Copy code
    @Transaction
        @Query("SELECT * FROM peer where id = :${peer.id}")
        fun getMessage(peer: Peer): List<PeerMessages>
    s
    • 2
    • 3
  • p

    Pablo

    01/13/2025, 10:07 PM
    I have a room database which haves thousands of registers in various tables. When I download all the data from internet, it deletes the table and fill it again from scratch. The sqlite has a size of 300KB. If i press update... it gets a size of 600, if I press again, 900, and then, after a fourth update, it comes back to 300 kb. Any idea why this happens? If I open the sqlite with a sqlite browsers, the data is supposedly always the same with every size.
    not kotlin but kotlin colored 1
    e
    • 2
    • 2
  • f

    FlowFan

    01/17/2025, 8:42 AM
    room:2.7.0-alpha12 ksp:2.1.0-1.0.29 I got crash with runRelease on desktop, but it works fine on debug and other target, how can I fix it?
    Copy code
    Caused by: java.lang.RuntimeException: Cannot find implementation for com.develop.db.AppDatabase. AppDatabase_Impl does not exist. Is Room annotation processor correctly configured?
  • c

    calidion

    01/30/2025, 5:45 PM
    how to remove room data in desktop environment?
    Copy code
    Room cannot verify the data integrity. Looks like you've changed schema but forgot to update the version number. You can simply fix this by increasing the version number. Expected identity hash: 38767ca95e25ff4f114395416eb5f824, found: b6766d3311ce100dfdedbb4695613e5b
    creation code, useless even when i deleted the db file.
    Copy code
    fun getDatabaseBuilder(): RoomDatabase.Builder<AppDatabase> {
        val dbFile = File(System.getProperty("java.io.tmpdir"), "room.db")
        dbFile.delete()
        return Room.databaseBuilder<AppDatabase>(
            name = dbFile.absolutePath,
        )
    }
    
    fun getRoomDatabase(
        builder: RoomDatabase.Builder<AppDatabase>
    ): AppDatabase {
        return builder
    //        .addMigrations(MIGRATIONS)
    //        .fallbackToDestructiveMigrationOnDowngrade(true)
            .setDriver(BundledSQLiteDriver())
            .setQueryCoroutineContext(<http://Dispatchers.IO|Dispatchers.IO>)
            .build()
    }
    s
    • 2
    • 10
  • h

    hafiz

    02/07/2025, 9:19 AM
    does room safe to store in the phone? it is room has own mechanism to encrypt the data in kotlin multiplatform?
  • b

    Bradleycorn

    02/13/2025, 1:58 PM
    I added Room to a KMP project (targeting Android and iOS), and since then, Xcode Previews for my iOS app fail, with several errors around sqlite. Has anyone else run into this problem? I have tried adding
    -lsqlite3
    to the "Other Linker Flags" build setting, but the problem persists. That shouldn't be necessary, because I am using the BundledSqliteDriver ... I have also tried using the NativeSqliteDriver, but I get the same results Error message looks like:
    Copy code
    Undefined symbols for architecture arm64:
          "_sqlite3_mutex_held", referenced from:
              _sqlite3_sqlite3_mutex_held_wrapper226 in RailBirdKit[81](libandroidx.sqlite:sqlite-framework-cinterop-sqlite3-cache.a.o)
          "_sqlite3_mutex_notheld", referenced from:
              _sqlite3_sqlite3_mutex_notheld_wrapper227 in RailBirdKit[81](libandroidx.sqlite:sqlite-framework-cinterop-sqlite3-cache.a.o)
          "_sqlite3_unlock_notify", referenced from:
              _sqlite3_sqlite3_unlock_notify_wrapper252 in RailBirdKit[81](libandroidx.sqlite:sqlite-framework-cinterop-sqlite3-cache.a.o)
          "_sqlite3_win32_set_directory", referenced from:
              _sqlite3_sqlite3_win32_set_directory_wrapper181 in RailBirdKit[81](libandroidx.sqlite:sqlite-framework-cinterop-sqlite3-cache.a.o)
          "_sqlite3_win32_set_directory16", referenced from:
              _sqlite3_sqlite3_win32_set_directory16_wrapper183 in RailBirdKit[81](libandroidx.sqlite:sqlite-framework-cinterop-sqlite3-cache.a.o)
          "_sqlite3_win32_set_directory8", referenced from:
              _sqlite3_sqlite3_win32_set_directory8_wrapper182 in RailBirdKit[81](libandroidx.sqlite:sqlite-framework-cinterop-sqlite3-cache.a.o)
        ld: symbol(s) not found for architecture arm64
        clang: error: linker command failed with exit code 1 (use -v to see invocation)
    • 1
    • 1
  • e

    Eduardo Ruesta

    02/13/2025, 6:50 PM
    Hey, one question about using Room in a Compose Multiplatform project. What should i do when for example a make an update on one of my database, for example adding another key. ex (Table User with: name, surname, age) release the app. And then i want to add a new key (address) what should i do?. Because what im doing today is uninstall the app, delete cache and run it again. Removed all the data from the app. But for a real app i don't want that for my users
    s
    • 2
    • 3
  • j

    John O'Reilly

    02/13/2025, 9:17 PM
    getting same as following on iOS and also
    java.lang.ClassNotFoundException: androidx.sqlite.SQLiteDriver
    in Compose for Desktop client using. 2.7.0-beta01 https://kotlinlang.slack.com/archives/C3PQML5NU/p1739479027685279
    d
    • 2
    • 3
  • t

    Tlaster

    02/14/2025, 7:11 AM
    I'm getting
    java.lang.NullPointerException: null cannot be cast to non-null type androidx.room.compiler.processing.XAnnotation
    when building iOS project after upgrading room to 2.7.0-beta01, but the Android project builds fine, full stack trace in thread.
    ➕ 4
    b
    в
    h
    • 4
    • 5
  • b

    Bradleycorn

    02/14/2025, 7:57 PM
    Hi all! I'm having issues getting SwiftUI previews to work in Xcode since adding Room to my project. It's little diagnostic tool shows a bunch of missing (not found) sqlite3 symbols. Has anyone else had this problem?
    • 1
    • 1
  • в

    Василий

    02/19/2025, 1:51 PM
    Apple could not verify “androidx_sqliteJni10441516714404854592.tmp” is free of malware that may harm your Mac or compromise your privacy
    👀 1
    d
    • 2
    • 4
  • c

    calidion

    03/03/2025, 9:19 AM
    how to get relation ordered ? for this relation:
    Copy code
    data class ExamWithDates(
        @Embedded val exam: Exam,
        @Relation(
            parentColumn = "id",
            entityColumn = "id",
            associateBy = Junction(
                value = ExamDate::class,
                parentColumn = "examId",
                entityColumn = "dateId",
            )
        )
        val dates: List<Date>
    )
    I need dates ordered by date
    d
    • 2
    • 4
  • t

    Thomas Hormes

    03/05/2025, 6:32 AM
    Hi, is there any way to add Entities to our Database that come from a different module? I am currently building a kmp app and my setup is that I have a
    :database
    module where most Entities, Daos, etc. live. However i now have a different module, say
    :test
    where I want to add another Entity that I can add to my
    @Database
    Declaration in the
    :database
    module. Whenever I try, i get an error saying I need to add a migration. When I add a migration however, I get the following error (see 🧵 )
    d
    • 2
    • 2
  • p

    Pablo

    03/14/2025, 5:26 PM
    I'm using Room in Android with a room .db file with preload data in assets. When I compile and install the app in Android Studio emulator with new data (same schema but more or different data on the tables) in the .db preloaded database of assets floder... the app doesn't display it. It seems that room sees that the database has been already loaded from the .db file previously and doesn't update it. Is there any function or configuration in room necessary to always preload the .db file when it has new data? for example, after an update of the app etc... I don't want to preserve data, I just want that when an update of the app has come, or the .db file has more or different data, the .db file must be loaded, removing/ovewritting the previous cached database. Is there any built in feature in room to help with this? For example, specifying that the DB version has been changed, and telling Room that it must remove the cached version and reload the assets .db file. But is that possible?
    • 1
    • 2
  • a

    Ahmed

    03/16/2025, 3:16 PM
    Is there a way to write queries with window functions?
  • p

    Pablo

    03/16/2025, 4:01 PM
    About preloading .db files, what means this sentence in the room documentation?
    Copy code
    Note: Automated Room migrations rely on the generated database schema for both the old and the new versions of the database. If exportSchema is set to false, or if you have not yet compiled the database with the new version number, then automated migrations fail.
    Specifically the part on if you have not yet compiled the database with the new version number. What is refering to? maybe google is telling that we need to open the sqlite file with an external tool and edit the pragma user_version value? Is that mandatory to make room migrations work?
    a
    • 2
    • 2
  • m

    Morgane Soula

    03/18/2025, 4:02 PM
    Hello, I have an issue with Room and KSP (KMP context) and I don't seem to find a workaround. I am using Room 2.7.0-rc02, KSP 2.1.10-1.0.31 and Kotlin 2.1.10. I have a multi-module project with a module for the database and another one for the DAO. I always encounter the following issue:
    Copy code
    [ksp] [MissingType]: Element 'com.msoula.hobbymatchmaker.core.database.dao.converters.Converters' references a type that is not present
    My build.gradle (dao module - database is pretty similar)
    Copy code
    import org.jetbrains.kotlin.gradle.dsl.JvmTarget
    
    plugins {
        `kotlin-multiplatform`
        `android-library`
        alias(libs.plugins.compose.compiler)
        alias(libs.plugins.compose.multiplatform)
        alias(libs.plugins.serialization)
        alias(libs.plugins.room.multiplatform)
        alias(libs.plugins.ksp)
    }
    
    kotlin {
        applyDefaultHierarchyTemplate()
    
        androidTarget {
            compilerOptions {
                jvmTarget.set(JvmTarget.JVM_21)
            }
        }
    
        iosX64()
        iosArm64()
        iosSimulatorArm64()
    
        sourceSets {
            commonMain.dependencies {
                implementation(compose.runtime)
                implementation(libs.kotlinx.coroutines.kmp)
                implementation(libs.kotlinx.serialization)
    
                //
                implementation(libs.room.common)
                implementation(libs.room.runtime)
            }
    
            androidMain.dependencies {
                // Room
                implementation(libs.room.runtime.android)
            }
        }
    }
    
    room { schemaDirectory("$projectDir/schemas") }
    
    android {
        namespace = "com.msoula.hobbymatchmaker.core.database.dao"
        compileSdk = AndroidConfig.COMPILE_SDK
    
        compileOptions {
            sourceCompatibility = JavaVersion.VERSION_21
            targetCompatibility = JavaVersion.VERSION_21
        }
    
        defaultConfig {
            minSdk = AndroidConfig.MIN_SDK
        }
    }
    
    dependencies {
        add("kspCommonMainMetadata", libs.room.compiler)
        add("kspAndroid", libs.room.compiler)
        add("kspIosX64", libs.room.compiler)
        add("kspIosArm64", libs.room.compiler)
        add("kspIosSimulatorArm64", libs.room.compiler)
    }
    And the converter class
    Copy code
    class Converters {
    
        val jsonParser = Json { encodeDefaults = true; ignoreUnknownKeys = true }
    
        @TypeConverter
        fun fromGenreStringList(genres: List<String>?): String? {
            return genres?.joinToString(",")
        }
    
        @TypeConverter
        fun toGenreStringList(data: String?): List<String>? {
            return data?.split(",")?.map { it.trim() }
        }
    
        @TypeConverter
        fun fromGenreList(genres: List<Genre>?): String? {
            return genres?.let { jsonParser.encodeToString(it) }
        }
    
        @TypeConverter
        fun toGenreList(genreString: String?): List<Genre> {
            return genreString?.let { jsonParser.decodeFromString<List<Genre>>(it) } ?: emptyList()
        }
    
        @TypeConverter
        fun fromActorList(actors: List<Actor>?): String? {
            return actors?.let { jsonParser.encodeToString(it) }
        }
    
        @TypeConverter
        fun toActorList(actorString: String?): List<Actor> {
            return actorString?.let { jsonParser.decodeFromString<List<Actor>>(it) } ?: emptyList()
        }
    }
    i
    • 2
    • 2
  • m

    Manoj Kumar

    03/19/2025, 9:41 AM
    I'm trying to encrypt the KMP's room DB for android and iOS using SQLCipher. For android, I can get it done by the openHelperFactory
    Copy code
    internal fun getDatabaseBuilder(app: Application): RoomDatabase.Builder<MyDatabase> {
        val passphrase: ByteArray = SQLiteDatabase.getBytes("temp_passphrase".toCharArray())
        val factory = SupportFactory(passphrase)
        val dbFile = app.getDatabasePath(KMPConstants.DB_FILE_NAME)
        return Room.databaseBuilder<MyDatabase>(
            context = app,
            name = dbFile.absolutePath,
        )
            .openHelperFactory(factory)
    }
    How do I do it for iOS?
    d
    • 2
    • 2
  • i

    Istvan Lorincz

    03/21/2025, 3:58 PM
    Dear all, any of you face massive build slowdown after adding room and KSP? My build takes longer than 30 minutes now. It is especially painful on Bitrise that I want to use for deployment. My gradle properties:
    Copy code
    kotlin.code.style=official
    
    kotlin.daemon.jvmargs=-Xmx6g
    
    #Gradle
    org.gradle.jvmargs=-Xmx6g -Dfile.encoding=UTF-8 -XX:+UseG1GC
    
    #Android
    android.nonTransitiveRClass=true
    android.useAndroidX=true
    
    # Enable Gradle Daemon
    org.gradle.daemon=true
    # Enable Configure on demand
    org.gradle.configureondemand=true
    # Enable parallel builds
    org.gradle.parallel=true
    # Enable Build Cache
    #android.enableBuildCache=true
    # Enable simple gradle caching
    org.gradle.caching=true
    # Increase memory allotted to JVM
    
    ksp.incremental=true
    
    #
    ## Enable Kotlin Incremental Compilation
    kotlin.incremental=true
    kotlin.incremental.multiplatform=true
    #
    ## Enable Configuration Cache
    #org.gradle.configuration-cache=true
  • i

    Istvan Lorincz

    03/22/2025, 11:31 PM
    Did any of you encountered the following issue on iOS? Uncaught Kotlin exception: kotlin.native.internal.IrLinkageError: Function ‘use’ can not be called: No function found for symbol
  • p

    Pablichjenkov

    04/02/2025, 4:24 PM
    Is it ok having multiple room databases in an Android App. Like 10 or so? Or is better to have only 1 with a lot of tables? There are not many join queries in the existing codebase, in case this info helps.
    not kotlin but kotlin colored 1
    j
    • 2
    • 2
  • g

    Grigory Panko

    04/11/2025, 11:34 AM
    Hi everyone! I'm trying to insert row or update it on existing id into my table, and I see 2 options for doing this in Room:
    @Upsert
    and
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    . It seems to me that
    @Upsert
    should be more efficient (it was introduced more recently and has semantics of
    INSERT ... ON CONFLICT DO UPDATE
    within single query), while
    OnConflictStrategy.REPLACE
    looks like it will try to insert row in first query, and if it fails, run another query with update. But looking at the generated dao implementation, I see that
    OnConflictStrategy.REPLACE
    uses
    INSERT OR REPLACE INTO
    , while
    @Upsert
    has 2 separate
    INSERT
    and
    UPDATE
    queries. Does it mean that
    OnConflictStrategy.REPLACE
    should be more efficient when updating rows?
    s
    d
    • 3
    • 3
  • a

    alexhelder

    05/12/2025, 12:57 AM
    Hi everyone, a data modeling question: I am using Paging3 / RemoteMediator to store paged
    Foos
    (from network) in Room. There can be some ‘local only’ state (like DownloadManager ID and favorite status) that also needs to be associated with each
    Foo
    . Would you put those ‘local state’ columns in the same Room table storing the Paged
    Foos
    , or do a 1:1 relationship with the paged
    Foo
    table and another table, like
    LocalFooState
    ?
  • o

    Olivier Patry

    05/12/2025, 5:51 PM
    What is the expectations regarding nullable parameters in Room DAO? I have the following function not working
    Copy code
    @Query(
        """
            SELECT * FROM task
            WHERE parent_list_local_id = :taskListLocalId
              AND parent_local_id = :parentTaskLocalId
              AND position <= :position
              AND is_completed = false
            ORDER BY position ASC
        """
    )
    suspend fun getTasksUpToPosition(taskListLocalId: Long, parentTaskLocalId: Long?, position: String): List<TaskEntity>
    If I force
    parent_local_id IS NULL
    , it's ok If I force
    parent_local_id = 0L
    , it's ok But can't have both at the same time using (equivalent of
    = NULL
    ) I went for
    COALESCE(parent_local_id, -1) = COALESCE(:parentTaskLocalId, -1)
    for concision (knowing my ID is always positive) I also made it work with an
    OR
    parent_local_id = :parentTaskLocalId OR (:parentTaskLocalId IS NULL AND parent_local_id IS NULL)
    I was expecting the generator to deal with nullable parameter itself. In the generated code, it deals with it, and use
    bindNull
    but nothing more fancy. Do I miss something? Is it a requirement of Room somehow? Why? Would it be desirable to have it working? (FTR, I'm using Room on desktop with SQLite Bundled)