Hi I want to pre-populate the database in my KMM p...
# squarelibraries
a
Hi I want to pre-populate the database in my KMM project. I’m using SQLDelight. I have this implementation for the Android side.
Copy code
actual fun Scope.createDriver(): SqlDriver {

    val context = androidContext()
    val fileName = "dbFileName"
    val database: File = context.getDatabasePath(fileName)

    if (!database.exists()) {
        val inputStream = context.assets.open(fileName)
        val outputStream = FileOutputStream(database.absolutePath)

        inputStream.use { input ->
            outputStream.use {
                input.copyTo(it)
            }
        }
    }

    return AndroidSqliteDriver(NoteDatabase.Schema, context, fileName)
}
What are the steps for the iOS side..? thanks!
j
Similar like this:
package com.jetbrains.handson.kmm.shared.cache
import com.squareup.sqldelight.db.SqlDriver
import com.squareup.sqldelight.drivers.native.NativeSqliteDriver
actual class DatabaseDriverFactory {
actual fun createDriver(): SqlDriver {
return NativeSqliteDriver(AppDatabase.Schema, "test.db")
}
}
Also see https://kotlinlang.org/docs/multiplatform-mobile-ktor-sqldelight.html#create-platform-database-drivers
a
I did it exactly for a simple use case but it'll not work to pre-populate the database. Let me know any other suggestions. Thanks!
j
@Ahmad Hassan Cant you just initiate the database driver and directly populate database? Or any reason need to prepopulate it?
a
I have a lot of data in the database and need to pre-populate. I did this on the Android side using this approach. It’s working fine.
Copy code
actual fun Scope.createDriver(): SqlDriver {

    val context = androidContext()
    val fileName = "dbFileName"
    val database: File = context.getDatabasePath(fileName)

    if (!database.exists()) {
        val inputStream = context.assets.open(fileName)
        val outputStream = FileOutputStream(database.absolutePath)

        inputStream.use { input ->
            outputStream.use {
                input.copyTo(it)
            }
        }
    }

    return AndroidSqliteDriver(NoteDatabase.Schema, context, fileName)
}
Now looking for iOS implementation.
245 Views